1
2
3
4
5
6
7
8
9
10
11
12
13
14
15 package org.basepom.mojo.propertyhelper.fields;
16
17 import org.basepom.mojo.propertyhelper.Field;
18 import org.basepom.mojo.propertyhelper.FieldContext;
19 import org.basepom.mojo.propertyhelper.ValueProvider;
20 import org.basepom.mojo.propertyhelper.definitions.DateDefinition;
21
22 import java.time.ZoneId;
23 import java.time.ZonedDateTime;
24 import java.time.temporal.ChronoUnit;
25 import java.util.StringJoiner;
26
27 import com.google.common.annotations.VisibleForTesting;
28
29
30 public final class DateField extends Field<ZonedDateTime, DateDefinition> {
31
32 private final ValueProvider valueProvider;
33 private final ZoneId timezone;
34
35 @VisibleForTesting
36 public static DateField forTesting(DateDefinition dateDefinition, ValueProvider valueProvider) {
37 return new DateField(dateDefinition, valueProvider, FieldContext.forTesting());
38 }
39
40 public DateField(final DateDefinition dateDefinition, final ValueProvider valueProvider, FieldContext fieldContext) {
41 super(dateDefinition, fieldContext);
42
43 this.valueProvider = valueProvider;
44 this.timezone = dateDefinition.getTimezone();
45 }
46
47 @Override
48 public String getFieldName() {
49 return fieldDefinition.getId();
50 }
51
52 @Override
53 public String getValue() {
54 ZonedDateTime date = valueProvider.getValue()
55 .map(value -> fieldDefinition.getParser().apply(value))
56 .orElseGet(() -> fieldDefinition.getValue()
57 .map(fieldDefinition.getLongParser())
58 .orElseGet(this::now));
59
60 String result = formatResult(date);
61
62 if (fieldDefinition.getFormatter().isPresent()) {
63
64 valueProvider.setValue(result);
65 } else {
66
67 valueProvider.setValue(Long.toString(date.toInstant().toEpochMilli()));
68 }
69
70 return result;
71 }
72
73 @Override
74 public boolean isExposeAsProperty() {
75 return fieldDefinition.isExport();
76 }
77
78 private ZonedDateTime now() {
79
80 return ZonedDateTime.now(timezone).truncatedTo(ChronoUnit.MILLIS);
81 }
82
83 @Override
84 public String toString() {
85 return new StringJoiner(", ", DateField.class.getSimpleName() + "[", "]")
86 .add("valueProvider=" + valueProvider)
87 .toString();
88 }
89 }