1 package com.github.mygreen.supercsv.cellprocessor.constraint;
2
3 import org.supercsv.cellprocessor.ift.CellProcessor;
4 import org.supercsv.cellprocessor.ift.StringCellProcessor;
5 import org.supercsv.exception.SuperCsvCellProcessorException;
6 import org.supercsv.exception.SuperCsvConstraintViolationException;
7 import org.supercsv.util.CsvContext;
8
9 import com.github.mygreen.supercsv.cellprocessor.ValidationCellProcessor;
10
11
12
13
14
15
16
17
18
19 public class LengthBetween extends ValidationCellProcessor implements StringCellProcessor {
20
21 private final int min;
22
23 private final int max;
24
25 public LengthBetween(final int min, final int max) {
26 super();
27 checkPreconditions(min, max);
28 this.min = min;
29 this.max = max;
30 }
31
32 public LengthBetween(final int min, final int max, final CellProcessor next) {
33 super(next);
34 checkPreconditions(min, max);
35 this.min = min;
36 this.max = max;
37 }
38
39
40
41
42
43
44
45
46
47
48
49 private static void checkPreconditions(final int min, final int max) {
50 if( min > max ) {
51 throw new IllegalArgumentException(String.format("max (%d) should not be < min (%d)", max, min));
52 }
53
54 if( min < 0 ) {
55 throw new IllegalArgumentException(String.format("min length (%d) should not be < 0", min));
56 }
57 }
58
59
60
61
62
63
64
65
66
67 @SuppressWarnings("unchecked")
68 public Object execute(final Object value, final CsvContext context) {
69
70 if(value == null) {
71 return next.execute(value, context);
72 }
73
74 final String stringValue = value.toString();
75 final int length = stringValue.length();
76 if( length < min || length > max ) {
77 throw createValidationException(context)
78 .messageFormat("the length (%d) of value '%s' does not lie between the min (%d) and max (%d) values (inclusive)",
79 length, stringValue, min, max)
80 .rejectedValue(stringValue)
81 .messageVariables("min", getMin())
82 .messageVariables("max", getMax())
83 .messageVariables("length", length)
84 .build();
85
86 }
87
88 return next.execute(stringValue, context);
89 }
90
91
92
93
94
95 public int getMin() {
96 return min;
97 }
98
99
100
101
102
103 public int getMax() {
104 return max;
105 }
106
107 }