1 package com.github.mygreen.supercsv.builder.standard;
2
3 import java.text.DateFormat;
4 import java.text.SimpleDateFormat;
5 import java.util.Date;
6 import java.util.Locale;
7 import java.util.Optional;
8 import java.util.TimeZone;
9
10 import org.supercsv.cellprocessor.ift.CellProcessor;
11
12 import com.github.mygreen.supercsv.annotation.constraint.CsvDateTimeRange;
13 import com.github.mygreen.supercsv.annotation.constraint.CsvDateTimeMin;
14 import com.github.mygreen.supercsv.annotation.constraint.CsvDateTimeMax;
15 import com.github.mygreen.supercsv.annotation.format.CsvDateTimeFormat;
16 import com.github.mygreen.supercsv.builder.AbstractProcessorBuilder;
17 import com.github.mygreen.supercsv.builder.Configuration;
18 import com.github.mygreen.supercsv.builder.FieldAccessor;
19 import com.github.mygreen.supercsv.cellprocessor.constraint.DateTimeRangeFactory;
20 import com.github.mygreen.supercsv.cellprocessor.constraint.DateTimeMinFactory;
21 import com.github.mygreen.supercsv.cellprocessor.constraint.DateTimeMaxFactory;
22 import com.github.mygreen.supercsv.cellprocessor.format.DateFormatWrapper;
23 import com.github.mygreen.supercsv.cellprocessor.format.SimpleDateFormatBuilder;
24 import com.github.mygreen.supercsv.util.Utils;
25
26
27
28
29
30
31
32
33
34 public abstract class AbstractDateProcessorBuilder<T extends Date> extends AbstractProcessorBuilder<T> {
35
36 public AbstractDateProcessorBuilder() {
37 super();
38
39 }
40
41 @Override
42 protected void init() {
43 super.init();
44
45
46 registerForConstraint(CsvDateTimeRange.class, new DateTimeRangeFactory<>());
47 registerForConstraint(CsvDateTimeMin.class, new DateTimeMinFactory<>());
48 registerForConstraint(CsvDateTimeMax.class, new DateTimeMaxFactory<>());
49
50 }
51
52
53
54
55
56
57
58
59 @SuppressWarnings("unchecked")
60 protected DateFormatWrapper<T> getDefaultFormatter(final FieldAccessor field, final Configuration config) {
61
62 final Optional<CsvDateTimeFormat> formatAnno = field.getAnnotation(CsvDateTimeFormat.class);
63 if(!formatAnno.isPresent()) {
64 return new DateFormatWrapper<>(new SimpleDateFormat(getDefaultPattern()), (Class<T>)field.getType());
65 }
66
67 String pattern = formatAnno.get().pattern();
68 if(pattern.isEmpty()) {
69 pattern = getDefaultPattern();
70 }
71
72 final boolean lenient = formatAnno.get().lenient();
73 final Locale locale = Utils.getLocale(formatAnno.get().locale());
74 final TimeZone timeZone = formatAnno.get().timezone().isEmpty() ? TimeZone.getDefault()
75 : TimeZone.getTimeZone(formatAnno.get().timezone());
76
77 final DateFormat formatter = SimpleDateFormatBuilder.create(pattern)
78 .lenient(lenient)
79 .locale(locale)
80 .timeZone(timeZone)
81 .build();
82
83 final DateFormatWrapper<T> wrapper = new DateFormatWrapper<>(formatter, (Class<T>)field.getType());
84 wrapper.setValidationMessage(formatAnno.get().message());
85
86 return wrapper;
87
88 }
89
90
91
92
93
94
95 protected abstract String getDefaultPattern();
96
97 }