1 package com.github.mygreen.supercsv.cellprocessor.constraint;
2
3 import java.util.Collection;
4 import java.util.Set;
5 import java.util.TreeSet;
6 import java.util.stream.Collectors;
7
8 import org.supercsv.cellprocessor.ift.CellProcessor;
9 import org.supercsv.cellprocessor.ift.StringCellProcessor;
10 import org.supercsv.exception.SuperCsvCellProcessorException;
11 import org.supercsv.exception.SuperCsvConstraintViolationException;
12 import org.supercsv.util.CsvContext;
13
14 import com.github.mygreen.supercsv.cellprocessor.ValidationCellProcessor;
15 import com.github.mygreen.supercsv.util.Utils;
16
17
18
19
20
21
22
23
24
25 public class LengthExact extends ValidationCellProcessor implements StringCellProcessor {
26
27 private final Set<Integer> requriedLengths = new TreeSet<>();
28
29 public LengthExact(final Collection<Integer> requriedLengths) {
30 super();
31 checkPreconditions(requriedLengths);
32 this.requriedLengths.addAll(requriedLengths);
33 }
34
35 public LengthExact(final Collection<Integer> requriedLengths, final CellProcessor next) {
36 super(next);
37 checkPreconditions(requriedLengths);
38 this.requriedLengths.addAll(requriedLengths);
39 }
40
41
42
43
44
45
46
47
48
49
50
51 private static void checkPreconditions(final Collection<Integer> requriedLengths) {
52 if( requriedLengths == null ) {
53 throw new NullPointerException("requriedLengths should not be null");
54 } else if( requriedLengths.isEmpty()) {
55 throw new IllegalArgumentException("requriedLengths should not be empty");
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
77 if( !requriedLengths.contains(length)) {
78 final String joinedLength = requriedLengths.stream()
79 .map(String::valueOf).collect(Collectors.joining(", "));
80
81 throw createValidationException(context)
82 .messageFormat("the length (%d) of value '%s' not any of required lengths (%s)",
83 length, stringValue, joinedLength)
84 .rejectedValue(stringValue)
85 .messageVariables("length", length)
86 .messageVariables("requiredLengths", getRequiredLengths())
87 .build();
88
89 }
90
91 return next.execute(stringValue, context);
92 }
93
94
95
96
97
98 public int[] getRequiredLengths() {
99 return Utils.toArray(requriedLengths);
100 }
101
102 }