/
TimeZoneLoader.java
324 lines (262 loc) · 14.2 KB
/
TimeZoneLoader.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
package net.fortuna.ical4j.model;
import net.fortuna.ical4j.data.CalendarBuilder;
import net.fortuna.ical4j.data.ParserException;
import net.fortuna.ical4j.model.component.Daylight;
import net.fortuna.ical4j.model.component.Observance;
import net.fortuna.ical4j.model.component.Standard;
import net.fortuna.ical4j.model.component.VTimeZone;
import net.fortuna.ical4j.model.property.*;
import net.fortuna.ical4j.util.Configurator;
import net.fortuna.ical4j.util.ResourceLoader;
import net.fortuna.ical4j.util.TimeZoneCache;
import org.apache.commons.lang3.Validate;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.io.InputStream;
import java.net.InetSocketAddress;
import java.net.Proxy;
import java.net.URL;
import java.net.URLConnection;
import java.text.ParseException;
import java.time.Period;
import java.time.*;
import java.time.format.DateTimeFormatter;
import java.time.temporal.TemporalAdjusters;
import java.time.zone.ZoneOffsetTransition;
import java.time.zone.ZoneOffsetTransitionRule;
import java.util.TimeZone;
import java.util.*;
public class TimeZoneLoader {
private static final String UPDATE_ENABLED = "net.fortuna.ical4j.timezone.update.enabled";
private static final String UPDATE_CONNECT_TIMEOUT = "net.fortuna.ical4j.timezone.update.timeout.connect";
private static final String UPDATE_READ_TIMEOUT = "net.fortuna.ical4j.timezone.update.timeout.read";
private static final String UPDATE_PROXY_ENABLED = "net.fortuna.ical4j.timezone.update.proxy.enabled";
private static final String UPDATE_PROXY_TYPE = "net.fortuna.ical4j.timezone.update.proxy.type";
private static final String UPDATE_PROXY_HOST = "net.fortuna.ical4j.timezone.update.proxy.host";
private static final String UPDATE_PROXY_PORT = "net.fortuna.ical4j.timezone.update.proxy.port";
private static final String TZ_CACHE_IMPL = "net.fortuna.ical4j.timezone.cache.impl";
private static final String DEFAULT_TZ_CACHE_IMPL = "net.fortuna.ical4j.util.JCacheTimeZoneCache";
private static final String MESSAGE_MISSING_DEFAULT_TZ_CACHE_IMPL = "Error loading default cache implementation. Please ensure the JCache API dependency is included in the classpath, or override the cache implementation (e.g. via configuration: net.fortuna.ical4j.timezone.cache.impl=net.fortuna.ical4j.util.MapTimeZoneCache)";
private static Proxy proxy = null;
private static final Set<String> TIMEZONE_DEFINITIONS = new HashSet<String>();
private static final String DATE_TIME_TPL = "yyyyMMdd'T'HHmmss";
private static final String RRULE_TPL = "FREQ=YEARLY;BYMONTH=%d;BYDAY=%d%s";
private static final Standard NO_TRANSITIONS;
static {
TIMEZONE_DEFINITIONS.addAll(Arrays.asList(net.fortuna.ical4j.model.TimeZone.getAvailableIDs()));
NO_TRANSITIONS = new Standard();
TzOffsetFrom offsetFrom = new TzOffsetFrom(ZoneOffset.UTC);
TzOffsetTo offsetTo = new TzOffsetTo(ZoneOffset.UTC);
NO_TRANSITIONS.getProperties().add(offsetFrom);
NO_TRANSITIONS.getProperties().add(offsetTo);
DtStart start = new DtStart();
start.setDate(Instant.EPOCH);
NO_TRANSITIONS.getProperties().add(start);
// Proxy configuration..
try {
if ("true".equals(Configurator.getProperty(UPDATE_PROXY_ENABLED).orElse("false"))) {
final Proxy.Type type = Configurator.getEnumProperty(Proxy.Type.class, UPDATE_PROXY_TYPE).orElse(Proxy.Type.DIRECT);
final String proxyHost = Configurator.getProperty(UPDATE_PROXY_HOST).orElse("");
final int proxyPort = Configurator.getIntProperty(UPDATE_PROXY_PORT).orElse(-1);
proxy = new Proxy(type, new InetSocketAddress(proxyHost, proxyPort));
}
}
catch (Throwable e) {
LoggerFactory.getLogger(TimeZoneLoader.class).warn(
"Error loading proxy server configuration: " + e.getMessage());
}
}
private final String resourcePrefix;
private final TimeZoneCache cache;
public TimeZoneLoader(String resourcePrefix) {
this(resourcePrefix, cacheInit());
}
public TimeZoneLoader(String resourcePrefix, TimeZoneCache cache) {
this.resourcePrefix = resourcePrefix;
this.cache = cache;
}
/**
* Loads an existing VTimeZone from the classpath corresponding to the specified Java timezone.
*
* @throws ParseException
*/
public VTimeZone loadVTimeZone(String id) throws IOException, ParserException, ParseException {
Validate.notBlank(id, "Invalid TimeZone ID: [%s]", id);
if (!cache.containsId(id)) {
final URL resource = ResourceLoader.getResource(resourcePrefix + id + ".ics");
if (resource != null) {
try (InputStream in = resource.openStream()) {
final CalendarBuilder builder = new CalendarBuilder();
final Calendar calendar = builder.build(in);
final VTimeZone vTimeZone = (VTimeZone) calendar.getComponent(Component.VTIMEZONE);
// load any available updates for the timezone.. can be explicility enabled via configuration
if ("true".equals(Configurator.getProperty(UPDATE_ENABLED).orElse("false"))) {
return updateDefinition(vTimeZone);
}
if (vTimeZone != null) {
cache.putIfAbsent(id, vTimeZone);
}
}
} else {
return generateTimezoneForId(id);
}
}
return cache.getTimezone(id);
}
/**
* @param vTimeZone
* @return
*/
private VTimeZone updateDefinition(VTimeZone vTimeZone) throws IOException, ParserException {
final TzUrl tzUrl = vTimeZone.getTimeZoneUrl();
if (tzUrl != null) {
final int connectTimeout = Configurator.getIntProperty(UPDATE_CONNECT_TIMEOUT).orElse(0);
final int readTimeout = Configurator.getIntProperty(UPDATE_READ_TIMEOUT).orElse(0);
URLConnection connection;
URL url = tzUrl.getUri().toURL();
if ("true".equals(Configurator.getProperty(UPDATE_PROXY_ENABLED).orElse("false")) && proxy != null) {
connection = url.openConnection(proxy);
} else {
connection = url.openConnection();
}
connection.setConnectTimeout(connectTimeout);
connection.setReadTimeout(readTimeout);
final CalendarBuilder builder = new CalendarBuilder();
final Calendar calendar = builder.build(connection.getInputStream());
final VTimeZone updatedVTimeZone = (VTimeZone) calendar.getComponent(Component.VTIMEZONE);
if (updatedVTimeZone != null) {
return updatedVTimeZone;
}
}
return vTimeZone;
}
private static VTimeZone generateTimezoneForId(String timezoneId) throws ParseException {
if (!TIMEZONE_DEFINITIONS.contains(timezoneId)) {
return null;
}
TimeZone javaTz = TimeZone.getTimeZone(timezoneId);
ZoneId zoneId = ZoneId.of(javaTz.getID(), ZoneId.SHORT_IDS);
int rawTimeZoneOffsetInSeconds = javaTz.getRawOffset() / 1000;
VTimeZone timezone = new VTimeZone();
timezone.getProperties().add(new TzId(timezoneId));
addTransitions(zoneId, timezone, rawTimeZoneOffsetInSeconds);
addTransitionRules(zoneId, rawTimeZoneOffsetInSeconds, timezone);
if (timezone.getObservances() == null || timezone.getObservances().isEmpty()) {
timezone.getObservances().add(NO_TRANSITIONS);
}
return timezone;
}
private static void addTransitionRules(ZoneId zoneId, int rawTimeZoneOffsetInSeconds, VTimeZone result) {
ZoneOffsetTransition zoneOffsetTransition = null;
if (!zoneId.getRules().getTransitions().isEmpty()) {
Collections.min(zoneId.getRules().getTransitions(),
Comparator.comparing(ZoneOffsetTransition::getDateTimeBefore));
}
LocalDateTime startDate = null;
if (zoneOffsetTransition != null) {
startDate = zoneOffsetTransition.getDateTimeBefore();
} else {
startDate = LocalDateTime.now(zoneId);
}
for (ZoneOffsetTransitionRule transitionRule : zoneId.getRules().getTransitionRules()) {
int transitionRuleMonthValue = transitionRule.getMonth().getValue();
DayOfWeek transitionRuleDayOfWeek = transitionRule.getDayOfWeek();
LocalDateTime ldt = LocalDateTime.now(zoneId)
.with(TemporalAdjusters.firstInMonth(transitionRuleDayOfWeek))
.withMonth(transitionRuleMonthValue)
.with(transitionRule.getLocalTime());
Month month = ldt.getMonth();
TreeSet<Integer> allDaysOfWeek = new TreeSet<Integer>();
do {
allDaysOfWeek.add(ldt.getDayOfMonth());
} while ((ldt = ldt.plus(Period.ofWeeks(1))).getMonth() == month);
Integer dayOfMonth = allDaysOfWeek.ceiling(transitionRule.getDayOfMonthIndicator());
if (dayOfMonth == null) {
dayOfMonth = allDaysOfWeek.last();
}
int weekdayIndexInMonth = 0;
for (Iterator<Integer> it = allDaysOfWeek.iterator(); it.hasNext() && it.next() != dayOfMonth; ) {
weekdayIndexInMonth++;
}
weekdayIndexInMonth = weekdayIndexInMonth >= 3 ? weekdayIndexInMonth - allDaysOfWeek.size() : weekdayIndexInMonth;
String rruleText = String.format(RRULE_TPL, transitionRuleMonthValue, weekdayIndexInMonth, transitionRuleDayOfWeek.name().substring(0, 2));
try {
TzOffsetFrom offsetFrom = new TzOffsetFrom(transitionRule.getOffsetBefore());
TzOffsetTo offsetTo = new TzOffsetTo(transitionRule.getOffsetAfter());
RRule rrule = new RRule(rruleText);
Observance observance = (transitionRule.getOffsetAfter().getTotalSeconds() > rawTimeZoneOffsetInSeconds) ? new Daylight() : new Standard();
observance.getProperties().add(offsetFrom);
observance.getProperties().add(offsetTo);
observance.getProperties().add(rrule);
observance.getProperties().add(new DtStart(startDate.withMonth(transitionRule.getMonth().getValue())
.withDayOfMonth(transitionRule.getDayOfMonthIndicator())
.with(transitionRule.getDayOfWeek()).format(DateTimeFormatter.ofPattern(DATE_TIME_TPL))));
result.getObservances().add(observance);
} catch (ParseException e) {
throw new RuntimeException(e);
}
}
}
private static void addTransitions(ZoneId zoneId, VTimeZone result, int rawTimeZoneOffsetInSeconds) throws ParseException {
Map<ZoneOffsetKey, Set<ZoneOffsetTransition>> zoneTransitionsByOffsets = new HashMap<ZoneOffsetKey, Set<ZoneOffsetTransition>>();
for (ZoneOffsetTransition zoneTransitionRule : zoneId.getRules().getTransitions()) {
ZoneOffsetKey offfsetKey = ZoneOffsetKey.of(zoneTransitionRule.getOffsetBefore(), zoneTransitionRule.getOffsetAfter());
Set<ZoneOffsetTransition> transitionRulesForOffset = zoneTransitionsByOffsets.computeIfAbsent(offfsetKey, k -> new HashSet<ZoneOffsetTransition>(1));
transitionRulesForOffset.add(zoneTransitionRule);
}
for (Map.Entry<ZoneOffsetKey, Set<ZoneOffsetTransition>> e : zoneTransitionsByOffsets.entrySet()) {
Observance observance = (e.getKey().offsetAfter.getTotalSeconds() > rawTimeZoneOffsetInSeconds) ? new Daylight() : new Standard();
LocalDateTime start = Collections.min(e.getValue()).getDateTimeBefore();
DtStart dtStart = new DtStart(start.format(DateTimeFormatter.ofPattern(DATE_TIME_TPL)));
TzOffsetFrom offsetFrom = new TzOffsetFrom(e.getKey().offsetBefore);
TzOffsetTo offsetTo = new TzOffsetTo(e.getKey().offsetAfter);
observance.getProperties().add(dtStart);
observance.getProperties().add(offsetFrom);
observance.getProperties().add(offsetTo);
for (ZoneOffsetTransition transition : e.getValue()) {
RDate rDate = new RDate(new ParameterList(), transition.getDateTimeBefore().format(DateTimeFormatter.ofPattern(DATE_TIME_TPL)));
observance.getProperties().add(rDate);
}
result.getObservances().add(observance);
}
}
private static TimeZoneCache cacheInit() {
Optional<TimeZoneCache> property = Configurator.getObjectProperty(TZ_CACHE_IMPL);
return property.orElseGet(() -> {
try {
return (TimeZoneCache) Class.forName(DEFAULT_TZ_CACHE_IMPL).newInstance();
} catch (InstantiationException | IllegalAccessException | ClassNotFoundException | NoClassDefFoundError e) {
throw new RuntimeException(MESSAGE_MISSING_DEFAULT_TZ_CACHE_IMPL, e);
}
});
}
private static class ZoneOffsetKey {
private final ZoneOffset offsetBefore;
private final ZoneOffset offsetAfter;
private ZoneOffsetKey(ZoneOffset offsetBefore, ZoneOffset offsetAfter) {
this.offsetBefore = offsetBefore;
this.offsetAfter = offsetAfter;
}
@Override
public boolean equals(Object obj) {
if (obj == null) {
return true;
}
if (!(obj instanceof ZoneOffsetKey)) {
return false;
}
ZoneOffsetKey otherZoneOffsetKey = (ZoneOffsetKey) obj;
return Objects.equals(this.offsetBefore, otherZoneOffsetKey.offsetBefore) && Objects.equals(this.offsetAfter, otherZoneOffsetKey.offsetAfter);
}
@Override
public int hashCode() {
int result = 31;
result = result * (this.offsetBefore == null ? 1 : this.offsetBefore.hashCode());
result = result * (this.offsetAfter == null ? 1 : this.offsetAfter.hashCode());
return result;
}
static ZoneOffsetKey of(ZoneOffset offsetBefore, ZoneOffset offsetAfter) {
return new ZoneOffsetKey(offsetBefore, offsetAfter);
}
}
}