1 package com.github.mygreen.supercsv.cellprocessor.format;
2
3 import org.supercsv.cellprocessor.ift.CellProcessor;
4 import org.supercsv.cellprocessor.ift.StringCellProcessor;
5 import org.supercsv.util.CsvContext;
6
7 import com.github.mygreen.supercsv.cellprocessor.ValidationCellProcessor;
8 import com.github.mygreen.supercsv.util.Utils;
9
10
11
12
13
14
15
16
17
18 public class ParseProcessor<T> extends ValidationCellProcessor implements StringCellProcessor {
19
20 private final Class<T> type;
21
22 private final TextParser<T> parser;
23
24 public ParseProcessor(final Class<T> type, final TextParser<T> parser) {
25 super();
26 checkPreconditions(type, parser);
27 this.type = type;
28 this.parser = parser;
29 }
30
31 public ParseProcessor(final Class<T> type, final TextParser<T> parser, final CellProcessor next) {
32 super(next);
33 checkPreconditions(type, parser);
34 this.type = type;
35 this.parser = parser;
36 }
37
38
39
40
41
42
43 private static <T> void checkPreconditions(final Class<T> type, final TextParser<T> parser) {
44 if(type == null) {
45 throw new NullPointerException("type is null.");
46 }
47
48 if(parser == null) {
49 throw new NullPointerException("parser is null.");
50 }
51 }
52
53 @SuppressWarnings("unchecked")
54 @Override
55 public Object execute(final Object value, final CsvContext context) {
56
57 final String text = (String)value;
58 if(Utils.isEmpty(text)) {
59 if(type.isPrimitive()) {
60
61 return next.execute(Utils.getPrimitiveDefaultValue(type), context);
62
63 } else if(!String.class.isAssignableFrom(type)) {
64
65 return next.execute(null, context);
66
67 }
68 }
69
70 try {
71 final T result = parser.parse((String) value);
72 return next.execute(result, context);
73
74 } catch(TextParseException e) {
75 throw createValidationException(context)
76 .messageFormat("'%s' could not parse to %s.", value, getType().getName())
77 .exception(e)
78 .rejectedValue(value)
79 .validationMessageIfPresent(parser.getValidationMessage())
80 .messageVariables(parser.getMessageVariables())
81 .parsedError(true)
82 .build();
83 }
84 }
85
86
87
88
89
90 public Class<T> getType() {
91 return type;
92 }
93
94
95
96
97
98 public TextParser<T> getParser() {
99 return parser;
100 }
101
102 }