1
2
3
4
5
6
7
8
9
10
11
12
13
14 package ch.qos.logback.core.rolling.helper;
15
16 import java.time.Instant;
17 import java.time.ZoneId;
18 import java.util.Date;
19 import java.util.List;
20
21 import ch.qos.logback.core.CoreConstants;
22 import ch.qos.logback.core.pattern.DynamicConverter;
23 import ch.qos.logback.core.util.CachingDateFormatter;
24 import ch.qos.logback.core.util.DatePatternToRegexUtil;
25
26
27
28
29
30
31
32 public class DateTokenConverter<E> extends DynamicConverter<E> implements MonoTypedConverter {
33
34
35
36
37 public final static String CONVERTER_KEY = "d";
38 public final static String AUXILIARY_TOKEN = "AUX";
39 public static final String DEFAULT_DATE_PATTERN = CoreConstants.DAILY_DATE_PATTERN;
40
41 private String datePattern;
42 private ZoneId zoneId;
43 private CachingDateFormatter cdf;
44
45
46 private boolean primary = true;
47
48 public void start() {
49 this.datePattern = getFirstOption();
50 if (this.datePattern == null) {
51 this.datePattern = DEFAULT_DATE_PATTERN;
52 }
53
54 final List<String> optionList = getOptionList();
55 if (optionList != null) {
56 for (int optionIndex = 1; optionIndex < optionList.size(); optionIndex++) {
57 String option = optionList.get(optionIndex);
58 if (AUXILIARY_TOKEN.equalsIgnoreCase(option)) {
59 primary = false;
60 } else {
61 zoneId = ZoneId.of(option);
62 }
63 }
64 }
65
66 cdf = new CachingDateFormatter(datePattern, zoneId);
67 }
68
69 public String convert(Date date) {
70 return cdf.format(date.getTime());
71 }
72
73 public String convert(Instant instant) {
74 return cdf.format(instant.toEpochMilli());
75 }
76
77 public String convert(Object o) {
78 if (o == null) {
79 throw new IllegalArgumentException("Null argument forbidden");
80 }
81 if (o instanceof Date) {
82 return convert((Date) o);
83 }
84 if (o instanceof Instant) {
85 return convert((Instant) o);
86 }
87
88 throw new IllegalArgumentException("Cannot convert " + o + " of type" + o.getClass().getName());
89 }
90
91
92
93
94 public String getDatePattern() {
95 return datePattern;
96 }
97
98 public ZoneId getZoneId() {
99 return zoneId;
100 }
101
102 public boolean isApplicable(Object o) {
103 if(o instanceof Date)
104 return true;
105 if(o instanceof Instant)
106 return true;
107 return false;
108 }
109
110 public String toRegex() {
111 DatePatternToRegexUtil datePatternToRegexUtil = new DatePatternToRegexUtil(datePattern);
112 return datePatternToRegexUtil.toRegex();
113 }
114
115 public boolean isPrimary() {
116 return primary;
117 }
118 }