1 package com.github.mygreen.supercsv.cellprocessor.format;
2
3 import java.lang.reflect.InvocationTargetException;
4 import java.lang.reflect.Method;
5 import java.util.HashMap;
6 import java.util.Map;
7 import java.util.Objects;
8 import java.util.Optional;
9
10 import org.joda.time.ReadableInstant;
11 import org.joda.time.ReadablePartial;
12 import org.joda.time.format.DateTimeFormatter;
13
14 import com.github.mygreen.supercsv.util.Utils;
15
16
17
18
19
20
21
22
23
24 public class JodaFormatWrapper<T> extends AbstractTextFormatter<T> {
25
26 private final DateTimeFormatter formatter;
27
28 private final Class<T> type;
29
30 private final Method parseMethod;
31
32 private String pattern;
33
34
35
36
37
38
39
40
41
42 public JodaFormatWrapper(final DateTimeFormatter formatter, final Class<T> type) {
43 Objects.requireNonNull(formatter);
44 Objects.requireNonNull(type);
45
46 this.formatter = formatter;
47 this.type = type;
48
49 try {
50 this.parseMethod = type.getMethod("parse", String.class, DateTimeFormatter.class);
51
52 } catch (NoSuchMethodException | SecurityException e) {
53 throw new IllegalArgumentException(String.format("Cannot suuport type : %s.", type.getName()));
54 }
55 }
56
57
58
59
60
61
62 @SuppressWarnings("unchecked")
63 @Override
64 public T parse(final String text) {
65
66 try {
67 return (T) parseMethod.invoke(type, text, formatter);
68
69 } catch(IllegalAccessException | InvocationTargetException e) {
70 throw new TextParseException(text, type, "Cannot suuport type.");
71
72 } catch(IllegalArgumentException e) {
73 throw new TextParseException(text, type, e);
74 }
75
76 }
77
78 @Override
79 public String print(final T object) {
80 if(object instanceof ReadablePartial) {
81 return formatter.print((ReadablePartial)object);
82 }
83
84 if(object instanceof ReadableInstant) {
85 return formatter.print((ReadableInstant)object);
86 }
87
88 throw new TextPrintException(object, String.format("Cannot suuport type [%s].", object.getClass().getName()));
89 }
90
91 @Override
92 public Optional<String> getPattern() {
93 if(Utils.isEmpty(pattern)) {
94 return Optional.empty();
95 } else {
96 return Optional.of(pattern);
97 }
98 }
99
100 public void setPattern(String pattern) {
101 this.pattern = pattern;
102 }
103
104 @Override
105 public Map<String, Object> getMessageVariables() {
106 final Map<String, Object> vars = new HashMap<>();
107
108 getPattern().ifPresent(p -> vars.put("pattern", p));
109
110 return vars;
111 }
112
113 }