-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathPubtransConnector.java
More file actions
173 lines (144 loc) · 6.65 KB
/
PubtransConnector.java
File metadata and controls
173 lines (144 loc) · 6.65 KB
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
package fi.hsl.transitdata.pulsarpubtransconnect;
import com.typesafe.config.Config;
import fi.hsl.common.pulsar.PulsarApplicationContext;
import fi.hsl.common.transitdata.TransitdataProperties;
import org.apache.pulsar.client.api.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import redis.clients.jedis.Jedis;
import java.sql.*;
import java.time.Duration;
import java.time.OffsetDateTime;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.util.Collection;
import java.util.concurrent.TimeUnit;
public class PubtransConnector {
private static final Logger log = LoggerFactory.getLogger(PubtransConnector.class);
private Connection connection;
private long queryStartTime;
private String queryString;
private boolean enableCacheCheck;
private int cacheMaxAgeInMins;
private int queryTimeoutSecs;
private PubtransTableHandler handler;
private Jedis jedis;
private Producer<byte[]> producer;
private PubtransConnector() {}
public static PubtransConnector newInstance(Connection connection,
PulsarApplicationContext context,
PubtransTableType tableType) throws RuntimeException {
PubtransConnector connector = new PubtransConnector();
connector.connection = connection;
connector.jedis = context.getJedis();
connector.producer = context.getSingleProducer();
Config config = context.getConfig();
connector.queryString = queryString(config);
connector.enableCacheCheck = config.getBoolean("application.enableCacheTimestampCheck");
connector.cacheMaxAgeInMins = config.getInt("application.cacheMaxAgeInMinutes");
connector.queryTimeoutSecs = (int)config.getDuration("pubtrans.queryTimeout", TimeUnit.SECONDS);
log.info("Cache pre-condition enabled: {} with max age {}", connector.enableCacheCheck, connector.cacheMaxAgeInMins);
log.info("TableType: " + tableType);
switch (tableType) {
case ROI_ARRIVAL:
connector.handler = new ArrivalHandler(context);
break;
case ROI_DEPARTURE:
connector.handler = new DepartureHandler(context);
break;
default:
throw new IllegalArgumentException("Table type not supported");
}
return connector;
}
private static String queryString(Config config) {
String longName = config.getString("pubtrans.longName");
String shortName = config.getString("pubtrans.shortName");
return "SELECT * FROM " +
longName +
" AS " +
shortName +
" WHERE " +
shortName + ".LastModifiedUTCDateTime > ? " +
" ORDER BY " +
shortName + ".LastModifiedUTCDateTime, " +
shortName + ".IsOnDatedVehicleJourneyId, " +
shortName + ".JourneyPatternSequenceNumber DESC";
}
public boolean checkPrecondition() {
if (!enableCacheCheck)
return true;
synchronized (jedis) {
String lastUpdate = jedis.get(TransitdataProperties.KEY_LAST_CACHE_UPDATE_TIMESTAMP);
log.info("Cache last known update: {}", lastUpdate);
if (lastUpdate != null) {
OffsetDateTime dt = OffsetDateTime.parse(lastUpdate, DateTimeFormatter.ISO_DATE_TIME);
return isCacheValid(dt, cacheMaxAgeInMins);
}
else {
log.error("Could not find last cache update timestamp from redis");
return false;
}
}
}
static boolean isCacheValid(OffsetDateTime lastCacheUpdate, final int cacheMaxAgeInMins) {
OffsetDateTime now = OffsetDateTime.now();
//Java8 does not support getting duration as minutes directly.
final long secondsSinceUpdate = Duration.between(lastCacheUpdate, now).get(ChronoUnit.SECONDS);
final long minutesSinceUpdate = Math.floorDiv(secondsSinceUpdate, 60);
log.info("Minutes since last cache update: {}", minutesSinceUpdate);
log.info("Current time {}, last update {}} => mins from prev update: {}", now, lastCacheUpdate, minutesSinceUpdate);
return minutesSinceUpdate <= cacheMaxAgeInMins;
}
static void closeQuery(final ResultSet resultSet, final Statement statement) {
if (resultSet != null) {
try {
resultSet.close();
log.debug("ResultSet closed.");
} catch (SQLException e) {
log.error("Failed to close ResultSet", e);
}
}
if (statement != null) {
try {
statement.close();
log.debug("Statement closed.");
} catch (SQLException e) {
log.error("Failed to close Statement", e);
}
}
if (resultSet == null && statement == null) {
log.warn("ResultSet and Statement are null, nothing to close.");
}
}
public void queryAndProcessResults() throws SQLException, PulsarClientException {
queryStartTime = System.currentTimeMillis();
PreparedStatement statement = null;
ResultSet resultSet = null;
try {
statement = connection.prepareStatement(queryString);
statement.setTimestamp(1, new java.sql.Timestamp(handler.getLastModifiedTimeStamp()));
statement.setQueryTimeout(queryTimeoutSecs);
resultSet = statement.executeQuery();
produceMessages(handler.handleResultSet(resultSet, statement, queryStartTime));
} catch (PulsarClientException | SQLException e) {
closeQuery(resultSet, statement);
throw e;
}
}
private void produceMessages(Collection<TypedMessageBuilder<byte[]>> messages) throws PulsarClientException {
if (!producer.isConnected()) {
throw new PulsarClientException("Producer is not connected");
}
for (TypedMessageBuilder<byte[]> msg : messages) {
msg.sendAsync()
.exceptionally(throwable -> {
log.error("Failed to send Pulsar message", throwable);
return null;
});
}
//If we want to get Pulsar Exceptions to bubble up into this thread we need to do a sync flush for all pending messages.
producer.flush();
log.info("{} messages written. Latest timestamp: {} Total query and processing time: {} ms", messages.size(), handler.getLastModifiedTimeStamp(), System.currentTimeMillis() - this.queryStartTime);
}
}