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