1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 package org.codelibs.fess.validation;
17
18 import javax.validation.ConstraintValidator;
19 import javax.validation.ConstraintValidatorContext;
20
21 import org.codelibs.core.lang.StringUtil;
22 import org.codelibs.fess.mylasta.direction.FessConfig;
23 import org.codelibs.fess.util.ComponentUtil;
24 import org.hibernate.validator.constraintvalidation.HibernateConstraintValidatorContext;
25
26 public class CustomSizeValidator implements ConstraintValidator<CustomSize, CharSequence> {
27 private int min = 0;
28 private int max = Integer.MAX_VALUE;
29 private String message;
30
31 @Override
32 public void initialize(final CustomSize constraintAnnotation) {
33 final FessConfig fessConfig = ComponentUtil.getFessConfig();
34 final String minKey = constraintAnnotation.minKey();
35 if (StringUtil.isNotBlank(minKey)) {
36 min = Integer.parseInt(fessConfig.get(minKey));
37 }
38 final String maxKey = constraintAnnotation.maxKey();
39 if (StringUtil.isNotBlank(maxKey)) {
40 max = Integer.parseInt(fessConfig.get(maxKey));
41 }
42 message = constraintAnnotation.message();
43 validateParameters();
44 }
45
46 @Override
47 public boolean isValid(final CharSequence value, final ConstraintValidatorContext context) {
48 if (value == null) {
49 return true;
50 }
51
52 final HibernateConstraintValidatorContext hibernateContext = context.unwrap(HibernateConstraintValidatorContext.class);
53 hibernateContext.disableDefaultConstraintViolation();
54 hibernateContext.addMessageParameter("min", min).addMessageParameter("max", max).buildConstraintViolationWithTemplate(message)
55 .addConstraintViolation();
56 final int length = value.length();
57 return length >= min && length <= max;
58 }
59
60 private void validateParameters() {
61 if (min < 0) {
62 throw new IllegalArgumentException("The min parameter cannot be negative.");
63 }
64 if (max < 0) {
65 throw new IllegalArgumentException("The max parameter cannot be negative.");
66 }
67 if (max < min) {
68 throw new IllegalArgumentException("The length cannot be negative.");
69 }
70 }
71 }