View Javadoc
1   package org.wikimedia.eventutilities.flink.stream;
2   
3   import java.time.Instant;
4   
5   import org.apache.flink.api.common.eventtime.SerializableTimestampAssigner;
6   import org.apache.flink.types.Row;
7   import org.wikimedia.eventutilities.core.event.JsonEventGenerator;
8   
9   /**
10   * Creates a flink TimestampAssigner that extracts the event time.
11   */
12  public final class EventTimeAssigner {
13      private EventTimeAssigner() {}
14  
15      /**
16       * A timestamp extractor that reads the event time field from Event Platform events.
17       */
18      public static SerializableTimestampAssigner<Row> create() {
19          return (element, recordTimestamp) -> {
20              // TODO: add a way to configure the field name instead of hardcoding EVENT_TIME_FIELD here
21              Object eventTime = element.getField(JsonEventGenerator.EVENT_TIME_FIELD);
22              // We have to support both String and Instant as currently the conversion from JSONSchema to data types
23              // does not support parsing dates.
24              if (eventTime == null) {
25                  throw new IllegalArgumentException("Event time field 'dt' not set");
26              }
27              if (eventTime instanceof String) {
28                  return Instant.parse((String) eventTime).toEpochMilli();
29              } else if (eventTime instanceof Instant) {
30                  return ((Instant) eventTime).toEpochMilli();
31              } else {
32                  throw new IllegalArgumentException("Row records must have a dt field set with " +
33                          "type String or Instant, [" + eventTime.getClass().getName() + "] found");
34              }
35          };
36      }
37  }