1 package com.github.mygreen.supercsv.cellprocessor.constraint;
2
3 import java.util.Optional;
4
5 import org.supercsv.cellprocessor.ift.CellProcessor;
6
7 import com.github.mygreen.supercsv.annotation.constraint.CsvDateTimeRange;
8 import com.github.mygreen.supercsv.builder.Configuration;
9 import com.github.mygreen.supercsv.builder.FieldAccessor;
10 import com.github.mygreen.supercsv.cellprocessor.ConstraintProcessorFactory;
11 import com.github.mygreen.supercsv.cellprocessor.format.TextFormatter;
12 import com.github.mygreen.supercsv.cellprocessor.format.TextParseException;
13 import com.github.mygreen.supercsv.exception.SuperCsvInvalidAnnotationException;
14 import com.github.mygreen.supercsv.localization.MessageBuilder;
15
16
17
18
19
20
21
22
23 public class DateTimeRangeFactory<T extends Comparable<T>> implements ConstraintProcessorFactory<CsvDateTimeRange> {
24
25 @Override
26 public Optional<CellProcessor> create(final CsvDateTimeRange anno, final Optional<CellProcessor> next,
27 final FieldAccessor field, final TextFormatter<?> formatter, final Configuration config) {
28
29 @SuppressWarnings("unchecked")
30 final TextFormatter<T> typeFormatter = (TextFormatter<T>)formatter;
31
32 final T min;
33 try {
34 min = typeFormatter.parse(anno.min());
35
36 } catch(TextParseException e) {
37 throw new SuperCsvInvalidAnnotationException(anno, MessageBuilder.create("anno.attr.invalidType")
38 .var("property", field.getNameWithClass())
39 .varWithAnno("anno", anno.annotationType())
40 .var("attrName", "min")
41 .var("attrValue", anno.min())
42 .varWithClass("type", field.getType())
43 .var("pattern", typeFormatter.getPattern().orElseGet(null))
44 .format(true), e);
45 }
46
47 final T max;
48 try {
49 max = typeFormatter.parse(anno.max());
50
51 } catch(TextParseException e) {
52 throw new SuperCsvInvalidAnnotationException(anno, MessageBuilder.create("anno.attr.invalidType")
53 .var("property", field.getNameWithClass())
54 .varWithAnno("anno", anno.annotationType())
55 .var("attrName", "max")
56 .var("attrValue", anno.max())
57 .varWithClass("type", field.getType())
58 .var("pattern", typeFormatter.getPattern().orElseGet(null))
59 .format(true), e);
60 }
61
62 if(min.compareTo(max) > 0) {
63 throw new SuperCsvInvalidAnnotationException(anno, MessageBuilder.create("anno.CsvDateTimeRange.minMaxWrong")
64 .var("property", field.getNameWithClass())
65 .varWithAnno("anno", anno.annotationType())
66 .var("minValue", anno.min())
67 .var("maxValue", anno.max())
68 .format(true));
69
70 }
71
72 final DateTimeRange<T> processor = next.map(n -> new DateTimeRange<T>(min, max, anno.inclusive(), typeFormatter, n))
73 .orElseGet(() -> new DateTimeRange<T>(min, max, anno.inclusive(), typeFormatter));
74 processor.setValidationMessage(anno.message());
75
76 return Optional.of(processor);
77 }
78
79 }