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 LengthMax extends ValidationCellProcessor implements StringCellProcessor {
20
21 private final int max;
22
23 public LengthMax(final int max) {
24 super();
25 checkPreconditions(max);
26 this.max = max;
27 }
28
29 public LengthMax(final int max, final CellProcessor next) {
30 super(next);
31 checkPreconditions(max);
32 this.max = max;
33 }
34
35
36
37
38
39
40
41
42
43 private static void checkPreconditions(final int max) {
44 if( max <= 0 ) {
45 throw new IllegalArgumentException(String.format("max length (%d) should not be <= 0", max));
46 }
47 }
48
49
50
51
52
53
54
55
56
57 @SuppressWarnings("unchecked")
58 public Object execute(final Object value, final CsvContext context) {
59
60 if(value == null) {
61 return next.execute(value, context);
62 }
63
64 final String stringValue = value.toString();
65 final int length = stringValue.length();
66 if( length > max ) {
67 throw createValidationException(context)
68 .messageFormat("the length (%d) of value '%s' does not lie the max (%d) values (inclusive)",
69 length, stringValue, max)
70 .rejectedValue(stringValue)
71 .messageVariables("max", getMax())
72 .messageVariables("length", length)
73 .build();
74
75 }
76
77 return next.execute(stringValue, context);
78 }
79
80
81
82
83
84 public int getMax() {
85 return max;
86 }
87
88 }