1 package com.github.mygreen.supercsv.cellprocessor.constraint;
2
3 import java.util.Collection;
4 import java.util.stream.Collectors;
5
6 import org.supercsv.cellprocessor.ift.CellProcessor;
7 import org.supercsv.exception.SuperCsvCellProcessorException;
8 import org.supercsv.util.CsvContext;
9
10 import com.github.mygreen.supercsv.cellprocessor.ValidationCellProcessor;
11 import com.github.mygreen.supercsv.cellprocessor.format.TextPrinter;
12
13
14
15
16
17
18
19
20 public class Equals<T> extends ValidationCellProcessor {
21
22 private final Class<T> type;
23
24 private final Collection<T> equaledValues;
25
26 private final TextPrinter<T> printer;
27
28 public Equals(final Class<T> type, final Collection<T> equaledValues, final TextPrinter<T> printer) {
29 super();
30 checkPreconditions(type, equaledValues, printer);
31 this.type = type;
32 this.equaledValues = equaledValues.stream()
33 .distinct()
34 .collect(Collectors.toList());
35 this.printer = printer;
36 }
37
38 public Equals(final Class<T> type, final Collection<T> equaledValues, final TextPrinter<T> printer, final CellProcessor next) {
39 super(next);
40 checkPreconditions(type, equaledValues, printer);
41 this.type = type;
42 this.equaledValues = equaledValues.stream()
43 .distinct()
44 .collect(Collectors.toList());
45 this.printer = printer;
46 }
47
48 private static <T> void checkPreconditions(final Class<T> type, final Collection<T> equaledValues, final TextPrinter<T> printer) {
49 if(type == null || equaledValues == null || printer == null) {
50 throw new NullPointerException("type or equaledValues or printer, field should not be null.");
51 }
52 }
53
54 @SuppressWarnings("unchecked")
55 @Override
56 public Object execute(final Object value, final CsvContext context) {
57 if(value == null) {
58 return next.execute(value, context);
59 }
60
61 if(!type.isAssignableFrom(value.getClass())) {
62 throw new SuperCsvCellProcessorException(type, value, context, this);
63 }
64
65 final T result = (T) value;
66
67 if(!equaledValues.isEmpty() && !equaledValues.contains(value)) {
68 final String formattedValue = printer.print(result);
69 final String joinedFormattedValues = equaledValues.stream()
70 .map(v -> printer.print(v))
71 .collect(Collectors.joining(", "));
72
73 throw createValidationException(context)
74 .rejectedValue(result)
75 .messageFormat("'%s' is not equals any of [%s].", formattedValue, joinedFormattedValues)
76 .messageVariables("equalsValues", equaledValues)
77 .messageVariables("printer", getPrinter())
78 .build();
79 }
80
81 return next.execute(value, context);
82 }
83
84
85
86
87
88 public Collection<T> getEqualedValues() {
89 return equaledValues;
90 }
91
92
93
94
95
96 public TextPrinter<T> getPrinter() {
97 return printer;
98 }
99
100 }