1 package org.supercsv.cellprocessor.time;
2
3 import java.time.format.DateTimeFormatter;
4 import java.time.format.DateTimeParseException;
5 import java.time.temporal.TemporalAccessor;
6 import java.util.Objects;
7
8 import org.supercsv.cellprocessor.CellProcessorAdaptor;
9 import org.supercsv.cellprocessor.ift.CellProcessor;
10 import org.supercsv.cellprocessor.ift.StringCellProcessor;
11 import org.supercsv.exception.SuperCsvCellProcessorException;
12 import org.supercsv.util.CsvContext;
13
14
15
16
17
18
19
20
21 public abstract class AbstractTemporalAccessorParsingProcessor<T extends TemporalAccessor> extends CellProcessorAdaptor
22 implements StringCellProcessor {
23
24 private final DateTimeFormatter formatter;
25
26
27
28
29
30 public AbstractTemporalAccessorParsingProcessor() {
31 this.formatter = null;
32 }
33
34
35
36
37
38
39
40
41
42 public AbstractTemporalAccessorParsingProcessor(final CellProcessor next) {
43 super(next);
44 this.formatter = null;
45 }
46
47
48
49
50
51
52
53
54 public AbstractTemporalAccessorParsingProcessor(final DateTimeFormatter formatter) {
55 checkPreconditions(formatter);
56 this.formatter = formatter;
57 }
58
59
60
61
62
63
64
65
66
67
68 public AbstractTemporalAccessorParsingProcessor(final DateTimeFormatter formatter, final CellProcessor next) {
69 super(next);
70 checkPreconditions(formatter);
71 this.formatter = formatter;
72 }
73
74
75
76
77
78
79
80
81 private static void checkPreconditions(final DateTimeFormatter formatter) {
82 Objects.requireNonNull(formatter, "formatter should not be null");
83 }
84
85
86
87
88
89
90 public Object execute(final Object value, final CsvContext context) {
91 validateInputNotNull(value, context);
92 if( !(value instanceof String) ) {
93 throw new SuperCsvCellProcessorException(String.class, value, context, this);
94 }
95
96 final String string = (String) value;
97 final T result;
98 try {
99 if( formatter != null ) {
100 result = parse(string, formatter);
101 } else {
102 result = parse(string);
103 }
104 }
105 catch(DateTimeParseException e) {
106 throw new SuperCsvCellProcessorException("Failed to parse value", context, this, e);
107 }
108
109 return next.execute(result, context);
110 }
111
112
113
114
115
116
117
118
119 protected abstract T parse(final String string);
120
121
122
123
124
125
126
127
128
129
130 protected abstract T parse(final String string, final DateTimeFormatter formatter);
131
132 }