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