|
| 1 | +import javax.validation.ConstraintValidator; |
| 2 | +import javax.validation.ConstraintValidatorContext; |
| 3 | +import org.hibernate.validator.constraintvalidation.HibernateConstraintValidatorContext; |
| 4 | +import java.util.regex.Matcher; |
| 5 | +import java.util.regex.Pattern; |
| 6 | + |
| 7 | +public class TestValidator implements ConstraintValidator<Object, String> { |
| 8 | + |
| 9 | + public static class InterpolationHelper { |
| 10 | + |
| 11 | + public static final char BEGIN_TERM = '{'; |
| 12 | + public static final char END_TERM = '}'; |
| 13 | + public static final char EL_DESIGNATOR = '$'; |
| 14 | + public static final char ESCAPE_CHARACTER = '\\'; |
| 15 | + |
| 16 | + private static final Pattern ESCAPE_MESSAGE_PARAMETER_PATTERN = Pattern.compile( "([\\" + ESCAPE_CHARACTER + BEGIN_TERM + END_TERM + EL_DESIGNATOR + "])" ); |
| 17 | + |
| 18 | + private InterpolationHelper() { |
| 19 | + } |
| 20 | + |
| 21 | + public static String escapeMessageParameter(String messageParameter) { |
| 22 | + if ( messageParameter == null ) { |
| 23 | + return null; |
| 24 | + } |
| 25 | + return ESCAPE_MESSAGE_PARAMETER_PATTERN.matcher( messageParameter ).replaceAll( Matcher.quoteReplacement( String.valueOf( ESCAPE_CHARACTER ) ) + "$1" ); |
| 26 | + } |
| 27 | + |
| 28 | + } |
| 29 | + |
| 30 | + @Override |
| 31 | + public boolean isValid(String object, ConstraintValidatorContext constraintContext) { |
| 32 | + String value = object + " is invalid"; |
| 33 | + |
| 34 | + // Bad: Bean properties (normally user-controlled) are passed directly to `buildConstraintViolationWithTemplate` |
| 35 | + constraintContext.buildConstraintViolationWithTemplate(value).addConstraintViolation().disableDefaultConstraintViolation(); |
| 36 | + |
| 37 | + // Good: Bean properties (normally user-controlled) are escaped |
| 38 | + String escaped = InterpolationHelper.escapeMessageParameter(value); |
| 39 | + constraintContext.buildConstraintViolationWithTemplate(escaped).addConstraintViolation().disableDefaultConstraintViolation(); |
| 40 | + |
| 41 | + // Good: Bean properties (normally user-controlled) are parameterized |
| 42 | + HibernateConstraintValidatorContext context = constraintContext.unwrap( HibernateConstraintValidatorContext.class ); |
| 43 | + context.addMessageParameter( "prop", object ); |
| 44 | + context.buildConstraintViolationWithTemplate( "{prop} is invalid").addConstraintViolation(); |
| 45 | + return false; |
| 46 | + } |
| 47 | + |
| 48 | +} |
0 commit comments