1 package com.github.mygreen.supercsv.cellprocessor.constraint;
2
3 import org.supercsv.cellprocessor.ift.CellProcessor;
4 import org.supercsv.cellprocessor.ift.DateCellProcessor;
5 import org.supercsv.exception.SuperCsvCellProcessorException;
6 import org.supercsv.util.CsvContext;
7
8 import com.github.mygreen.supercsv.cellprocessor.ValidationCellProcessor;
9 import com.github.mygreen.supercsv.cellprocessor.format.TextPrinter;
10
11
12
13
14
15
16
17
18
19 public class DateTimeMax<T extends Comparable<T>> extends ValidationCellProcessor implements DateCellProcessor {
20
21 private final T max;
22
23 private final boolean inclusive;
24
25 private final TextPrinter<T> printer;
26
27 public DateTimeMax(final T max, final boolean inclusive, final TextPrinter<T> printer) {
28 super();
29 checkPreconditions(max, printer);
30 this.max = max;
31 this.inclusive = inclusive;
32 this.printer = printer;
33 }
34
35 public DateTimeMax(final T max, final boolean inclusive, final TextPrinter<T> printer, final CellProcessor next) {
36 super(next);
37 checkPreconditions(max, printer);
38 this.max = max;
39 this.inclusive = inclusive;
40 this.printer = printer;
41 }
42
43 private static <T extends Comparable<T>> void checkPreconditions(final T max,
44 final TextPrinter<T> printer) {
45 if(max == null || printer == null) {
46 throw new NullPointerException("max and printer should not be null");
47 }
48
49 }
50
51 @SuppressWarnings("unchecked")
52 @Override
53 public Object execute(final Object value, final CsvContext context) {
54
55 if(value == null) {
56 return next.execute(value, context);
57 }
58
59 final Class<?> exepectedClass = getMax().getClass();
60 if(!exepectedClass.isAssignableFrom(value.getClass())) {
61 throw new SuperCsvCellProcessorException(exepectedClass, value, context, this);
62 }
63
64 final T result = (T) value;
65 if(!validate(result)) {
66 throw createValidationException(context)
67 .messageFormat("%s does not lie the max (%s) value.",
68 printValue(result), printValue(max))
69 .rejectedValue(value)
70 .messageVariables("max", getMax())
71 .messageVariables("inclusive", isInclusive())
72 .messageVariables("printer", getPrinter())
73 .build();
74
75 }
76
77 return next.execute(result, context);
78 }
79
80 private boolean validate(final T value) {
81 final int compared = value.compareTo(max);
82 if(compared < 0) {
83 return true;
84 }
85
86 if(inclusive && compared == 0) {
87 return true;
88 }
89
90 return false;
91
92 }
93
94 private String printValue(final T value) {
95 return getPrinter().print(value);
96 }
97
98
99
100
101
102 public T getMax() {
103 return max;
104 }
105
106
107
108
109
110 public boolean isInclusive() {
111 return inclusive;
112 }
113
114
115
116
117
118 public TextPrinter<T> getPrinter() {
119 return printer;
120 }
121
122 }