forked from apache/metron
-
Notifications
You must be signed in to change notification settings - Fork 0
/
DateFunctions.java
410 lines (358 loc) · 14.4 KB
/
DateFunctions.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
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.metron.stellar.dsl.functions;
import com.github.benmanes.caffeine.cache.CacheLoader;
import com.github.benmanes.caffeine.cache.Caffeine;
import com.github.benmanes.caffeine.cache.LoadingCache;
import org.apache.metron.stellar.dsl.BaseStellarFunction;
import org.apache.metron.stellar.dsl.Stellar;
import org.apache.metron.stellar.common.utils.ConversionUtils;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Optional;
import java.util.TimeZone;
import java.util.concurrent.ExecutionException;
/**
* Stellar data functions.
*/
public class DateFunctions {
private static class TimezonedFormat {
private String format;
private Optional<String> timezone;
public TimezonedFormat(String format, String timezone) {
this.format = format;
this.timezone = Optional.of(timezone);
}
public TimezonedFormat(String format) {
this.format = format;
this.timezone = Optional.empty();
}
public SimpleDateFormat toDateFormat() {
return createFormat(format, timezone);
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
TimezonedFormat that = (TimezonedFormat) o;
if (format != null ? !format.equals(that.format) : that.format != null) return false;
return timezone != null ? timezone.equals(that.timezone) : that.timezone == null;
}
@Override
public int hashCode() {
int result = format != null ? format.hashCode() : 0;
result = 31 * result + (timezone != null ? timezone.hashCode() : 0);
return result;
}
}
private static LoadingCache<TimezonedFormat, ThreadLocal<SimpleDateFormat>> formatCache =
Caffeine.newBuilder().build(
new CacheLoader<TimezonedFormat, ThreadLocal<SimpleDateFormat>>() {
@Override
public ThreadLocal<SimpleDateFormat> load(final TimezonedFormat format) throws Exception {
return new ThreadLocal<SimpleDateFormat>() {
@Override
public SimpleDateFormat initialValue() {
return format.toDateFormat();
}
};
}
});
public static SimpleDateFormat createFormat(String format, Optional<String> timezone) {
SimpleDateFormat sdf = new SimpleDateFormat(format);
if(timezone.isPresent()) {
sdf.setTimeZone(TimeZone.getTimeZone(timezone.get()));
}
return sdf;
}
public static long getEpochTime(String date, String format, Optional<String> timezone) throws ExecutionException, ParseException {
TimezonedFormat fmt;
if(timezone.isPresent()) {
fmt = new TimezonedFormat(format, timezone.get());
} else {
fmt = new TimezonedFormat(format);
}
SimpleDateFormat sdf = formatCache.get(fmt).get();
return sdf.parse(date).getTime();
}
public static String getDateFormat(String format, Optional<Long> epochTime, Optional<String> timezone) {
Long time = epochTime.orElseGet(System::currentTimeMillis);
TimezonedFormat fmt = timezone.map(s -> new TimezonedFormat(format, s)).orElseGet(() -> new TimezonedFormat(format));
SimpleDateFormat sdf = formatCache.get(fmt).get();
return sdf.format(new Date(time));
}
/**
* Stellar Function: TO_EPOCH_TIMESTAMP
*/
@Stellar( name="TO_EPOCH_TIMESTAMP"
, description="Returns the epoch timestamp of the dateTime in the specified format. " +
"If the format does not have a timestamp and you wish to assume a " +
"given timestamp, you may specify the timezone optionally."
, params = { "dateTime - DateTime in String format"
, "format - DateTime format as a String"
, "timezone - Optional timezone in String format"
}
, returns = "Epoch timestamp")
public static class ToTimestamp extends BaseStellarFunction {
@Override
public Object apply(List<Object> objects) {
Object dateObj = objects.get(0);
Object formatObj = objects.get(1);
Object tzObj = null;
if(objects.size() >= 3) {
tzObj = objects.get(2);
}
if(dateObj != null && formatObj != null) {
try {
Optional<String> tz = (tzObj == null) ? Optional.empty() : Optional.of(tzObj.toString());
return getEpochTime(dateObj.toString(), formatObj.toString(), tz);
} catch (ExecutionException | ParseException e) {
return null;
}
}
return null;
}
}
@Stellar( name="DATE_FORMAT",
description = "Takes an epoch timestamp and converts it to a date format.",
params = {"format - DateTime format as a String."
, "timestampField - Optional epoch time in Long format. Defaults to now."
, "timezone - Optional timezone in String format."},
returns="Formatted date."
)
public static class DateFormat extends BaseStellarFunction {
public Object apply(List<Object> objects) {
int size = objects.size();
Optional<Object> formatObj = Optional.ofNullable(objects.get(0));
Optional<Long> epochObj = Optional.empty();
Optional<String> tzObj = Optional.empty();
if (size > 1) {
if (size == 2) {
if (objects.get(1) == null) {
return null;
}
epochObj = objects.get(1) instanceof Long ? Optional.of((Long) objects.get(1)) : Optional.empty();
tzObj = objects.get(1) instanceof String ? Optional.of((String) objects.get(1)) : Optional.empty();
} else {
epochObj = Optional.ofNullable((Long) objects.get(1));
tzObj = Optional.ofNullable((String) objects.get(2));
}
}
if(formatObj.isPresent()) {
return getDateFormat(formatObj.get().toString(), epochObj, tzObj);
} else {
return null;
}
}
}
/**
* Gets the value from a list of arguments.
*
* If the argument at the specified position does not exist, a default value will be returned.
* If the argument at the specified position exists, but cannot be coerced to the right type, null is returned.
* Otherwise, the argument value is returned.
*
* @param args A list of arguments.
* @param position The position of the argument to get.
* @param clazz The type of class expected.
* @param defaultValue The default value.
* @param <T> The expected type of the argument.
*/
private static <T> T getOrDefault(List<Object> args, int position, Class<T> clazz, T defaultValue) {
T result = defaultValue;
if(args.size() > position) {
result = ConversionUtils.convert(args.get(position), clazz);
}
return result;
}
/**
* Stellar Function: DAY_OF_WEEK
*
* The numbered day within the week. The first day of the week, Sunday, has a value of 1.
*
* If no argument is supplied, returns the current day of week.
*/
@Stellar( name="DAY_OF_WEEK"
, description="The numbered day within the week. The first day of the week, Sunday, has a value of 1."
, params = { "dateTime - The datetime as a long representing the milliseconds since unix epoch"
}
, returns = "The numbered day within the week.")
public static class DayOfWeek extends BaseStellarFunction {
@Override
public Object apply(List<Object> args) {
// expects epoch millis, otherwise defaults to current time
Long epochMillis = getOrDefault(args, 0, Long.class, System.currentTimeMillis());
if(epochMillis == null) {
return null; // invalid argument
}
// create a calendar
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(epochMillis);
return calendar.get(Calendar.DAY_OF_WEEK);
}
}
/**
* Stellar Function: DAY_OF_MONTH
*
* The day within the month. The first day within the month has a value of 1.
*/
@Stellar( name="DAY_OF_MONTH"
, description="The numbered day within the month. The first day within the month has a value of 1."
, params = { "dateTime - The datetime as a long representing the milliseconds since unix epoch"
}
, returns = "The numbered day within the month.")
public static class DayOfMonth extends BaseStellarFunction {
@Override
public Object apply(List<Object> args) {
// expects epoch millis, otherwise defaults to current time
Long epochMillis = getOrDefault(args, 0, Long.class, System.currentTimeMillis());
if(epochMillis == null) {
return null; // invalid argument
}
// create a calendar
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(epochMillis);
return calendar.get(Calendar.DAY_OF_MONTH);
}
}
/**
* Stellar Function: WEEK_OF_MONTH
*
* The numbered week within the month. The first week has a value of 1.
*/
@Stellar( name="WEEK_OF_MONTH"
, description="The numbered week within the month. The first week within the month has a value of 1."
, params = { "dateTime - The datetime as a long representing the milliseconds since unix epoch"
}
, returns = "The numbered week within the month.")
public static class WeekOfMonth extends BaseStellarFunction {
@Override
public Object apply(List<Object> args) {
// expects epoch millis, otherwise defaults to current time
Long epochMillis = getOrDefault(args, 0, Long.class, System.currentTimeMillis());
if(epochMillis == null) {
return null; // invalid argument
}
// create a calendar
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(epochMillis);
return calendar.get(Calendar.WEEK_OF_MONTH);
}
}
/**
* Stellar Function: WEEK_OF_YEAR
*
* The numbered week within the year. The first week in the year has a value of 1.
*/
@Stellar( name="WEEK_OF_YEAR"
, description="The numbered week within the year. The first week in the year has a value of 1."
, params = { "dateTime - The datetime as a long representing the milliseconds since unix epoch"
}
, returns = "The numbered week within the year.")
public static class WeekOfYear extends BaseStellarFunction {
@Override
public Object apply(List<Object> args) {
// expects epoch millis, otherwise defaults to current time
Long epochMillis = getOrDefault(args, 0, Long.class, System.currentTimeMillis());
if(epochMillis == null) {
return null; // invalid argument
}
// create a calendar
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(epochMillis);
return calendar.get(Calendar.WEEK_OF_YEAR);
}
}
/**
* Stellar Function: MONTH
*
* A number representing the month. The first month, January, has a value of 0.
*/
@Stellar( name="MONTH"
, description="The number representing the month. The first month, January, has a value of 0."
, params = { "dateTime - The datetime as a long representing the milliseconds since unix epoch"
}
, returns = "The current month (0-based).")
public static class MonthOfYear extends BaseStellarFunction {
@Override
public Object apply(List<Object> args) {
// expects epoch millis, otherwise defaults to current time
Long epochMillis = getOrDefault(args, 0, Long.class, System.currentTimeMillis());
if(epochMillis == null) {
return null; // invalid argument
}
// create a calendar
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(epochMillis);
return calendar.get(Calendar.MONTH);
}
}
/**
* Stellar Function: YEAR
*
* The calendar year.
*/
@Stellar( name="YEAR"
, description="The number representing the year. "
, params = { "dateTime - The datetime as a long representing the milliseconds since unix epoch"
}
, returns = "The current year"
)
public static class Year extends BaseStellarFunction {
@Override
public Object apply(List<Object> args) {
// expects epoch millis, otherwise defaults to current time
Long epochMillis = getOrDefault(args, 0, Long.class, System.currentTimeMillis());
if(epochMillis == null) {
return null; // invalid argument
}
// create a calendar
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(epochMillis);
return calendar.get(Calendar.YEAR);
}
}
/**
* Stellar Function: DAY_OF_YEAR
*
* The day number within the year. The first day of the year has value of 1.
*/
@Stellar( name="DAY_OF_YEAR"
, description="The day number within the year. The first day of the year has value of 1."
, params = { "dateTime - The datetime as a long representing the milliseconds since unix epoch"
}
, returns = "The day number within the year."
)
public static class DayOfYear extends BaseStellarFunction {
@Override
public Object apply(List<Object> args) {
// expects epoch millis, otherwise defaults to current time
Long epochMillis = getOrDefault(args, 0, Long.class, System.currentTimeMillis());
if(epochMillis == null) {
return null; // invalid argument
}
// create a calendar
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(epochMillis);
return calendar.get(Calendar.DAY_OF_YEAR);
}
}
}