1 |
package dk.thoerup.traininfoservice.banedk; |
package dk.thoerup.traininfoservice.banedk; |
2 |
|
|
3 |
import java.sql.Connection; |
|
4 |
import java.sql.ResultSet; |
import java.net.URL; |
5 |
import java.sql.Statement; |
import java.net.URLEncoder; |
|
import java.util.ArrayList; |
|
6 |
import java.util.Collections; |
import java.util.Collections; |
|
import java.util.List; |
|
7 |
import java.util.Map; |
import java.util.Map; |
8 |
import java.util.logging.Logger; |
import java.util.logging.Logger; |
9 |
|
|
10 |
import com.gargoylesoftware.htmlunit.WebClient; |
import org.jsoup.nodes.Document; |
11 |
import com.gargoylesoftware.htmlunit.html.DomNodeList; |
import org.jsoup.nodes.Element; |
12 |
import com.gargoylesoftware.htmlunit.html.HtmlElement; |
import org.jsoup.select.Elements; |
13 |
import com.gargoylesoftware.htmlunit.html.HtmlPage; |
|
14 |
|
import dk.thoerup.android.traininfo.common.DepartureBean; |
15 |
import dk.thoerup.curcuitbreaker.CircuitBreaker; |
import dk.thoerup.android.traininfo.common.DepartureEntry; |
16 |
import dk.thoerup.curcuitbreaker.CircuitBreakerManager; |
import dk.thoerup.android.traininfo.common.StationBean.StationEntry; |
17 |
import dk.thoerup.traininfoservice.DBConnection; |
import dk.thoerup.circuitbreaker.CircuitBreaker; |
18 |
|
import dk.thoerup.circuitbreaker.CircuitBreakerManager; |
19 |
|
import dk.thoerup.traininfoservice.StationDAO; |
20 |
|
import dk.thoerup.traininfoservice.Statistics; |
21 |
|
|
22 |
public class DepartureFetcher { |
public class DepartureFetcher { |
23 |
|
|
24 |
|
enum TrainType{ |
25 |
|
STOG, |
26 |
|
REGIONAL |
27 |
|
} |
28 |
|
|
29 |
Logger logger = Logger.getLogger(DepartureFetcher.class.getName()); |
Logger logger = Logger.getLogger(DepartureFetcher.class.getName()); |
30 |
|
|
31 |
Map<Integer, List<DepartureBean>> cache = new TimeoutMap<Integer,List<DepartureBean>>(120 * 1000); |
Map<String, DepartureBean> cache; |
32 |
|
|
33 |
|
StationDAO stationDao = new StationDAO(); |
34 |
|
|
35 |
|
private boolean useAzureSite; |
36 |
|
private int replyTimeout; |
37 |
|
|
38 |
|
public DepartureFetcher(boolean azureSite, int cacheTimeout, int replyTimeout) { |
39 |
|
this.replyTimeout = replyTimeout; |
40 |
|
useAzureSite = azureSite; |
41 |
|
cache = new TimeoutMap<String,DepartureBean>(cacheTimeout); |
42 |
|
} |
43 |
|
|
44 |
|
|
45 |
|
|
46 |
|
|
47 |
public List<DepartureBean> cachedLookupDepartures(int stationID) throws Throwable { |
public DepartureBean cachedLookupDepartures(int stationID, boolean arrival) throws Exception { |
48 |
|
final String key = "" + stationID + ":" + arrival; |
49 |
|
|
50 |
|
DepartureBean departureBean = cache.get(key); |
51 |
|
|
|
List<DepartureBean> list = cache.get(stationID); |
|
52 |
|
|
53 |
if (list == null) { |
if (departureBean == null) { |
54 |
list = lookupDepartures(stationID); |
departureBean = lookupDepartures(stationID,arrival); |
55 |
cache.put(stationID, list); |
cache.put(key, departureBean); |
56 |
} else { |
} else { |
57 |
logger.info("Departure: Cache hit " + stationID); //remove before production |
Statistics.getInstance().incrementDepartureCacheHits(); |
58 |
|
logger.info("Departure: Cache hit " + key); //remove before production |
59 |
} |
} |
60 |
return list; |
return departureBean; |
61 |
} |
} |
62 |
|
|
63 |
|
|
64 |
public List<DepartureBean> lookupDepartures(int stationID) throws Throwable { |
public DepartureBean lookupDepartures(int stationID, boolean arrival) throws Exception { |
|
List<DepartureBean> departureList = new ArrayList<DepartureBean>(); |
|
65 |
|
|
66 |
Connection conn = null; |
DepartureBean departureBean = new DepartureBean(); |
|
try |
|
|
{ |
|
|
conn = DBConnection.getConnection(); |
|
67 |
|
|
68 |
String SQL = "SELECT stationcode_fjrn, stationcode_stog FROM trainstations WHERE id=" + stationID; |
StationEntry station = stationDao.getById(stationID); |
69 |
Statement stmt = conn.createStatement(); |
|
70 |
ResultSet rs = stmt.executeQuery(SQL); |
departureBean.stationName = station.getName(); |
71 |
|
|
72 |
if (rs.next()) { |
if (station.getRegional() != null) { |
73 |
String code = rs.getString( 1 ); |
DepartureBean tempBean = lookupDepartures(station.getRegional(), TrainType.REGIONAL, arrival); |
74 |
if (! rs.wasNull() ) { |
departureBean.departureEntries.addAll( tempBean.departureEntries ); |
75 |
List<DepartureBean> list = lookupDepartures(code, "FJRN"); |
departureBean.notifications.addAll(tempBean.notifications); |
76 |
departureList.addAll(list); |
} |
77 |
} |
|
78 |
|
if (station.getStrain() != null) { |
79 |
code = rs.getString(2); |
DepartureBean tempBean = lookupDepartures(station.getStrain(), TrainType.STOG, arrival); |
80 |
if (! rs.wasNull() ) { |
departureBean.departureEntries.addAll( tempBean.departureEntries ); |
81 |
List<DepartureBean> list = lookupDepartures(code, "S2"); |
departureBean.notifications.addAll(tempBean.notifications); |
82 |
departureList.addAll(list); |
} |
83 |
} |
|
84 |
Collections.sort( departureList ); |
if (departureBean.departureEntries.size() == 0) { |
85 |
|
logger.info("No departures found for station " + stationID); |
|
} |
|
|
|
|
|
} finally { |
|
|
if (conn != null && !conn.isClosed() ) { |
|
|
conn.close(); |
|
|
} |
|
86 |
} |
} |
87 |
|
|
88 |
return departureList; |
Collections.sort( departureBean.departureEntries ); |
89 |
|
|
90 |
|
|
91 |
|
return departureBean; |
92 |
|
} |
93 |
|
|
94 |
|
public DepartureBean lookupDepartures(String stationcode, TrainType type, boolean arrival) throws Exception { |
95 |
|
if (useAzureSite == true) { |
96 |
|
return lookupDeparturesAzureSite(stationcode, type, arrival); |
97 |
|
} else { |
98 |
|
return lookupDeparturesWwwSite(stationcode, type, arrival); |
99 |
|
} |
100 |
|
} |
101 |
|
|
102 |
|
private String getTypeStringAzure(TrainType type) { |
103 |
|
switch (type) { |
104 |
|
case STOG: |
105 |
|
return "S-Tog"; |
106 |
|
case REGIONAL: |
107 |
|
return "Fjerntog"; |
108 |
|
default: |
109 |
|
return ""; //Can not happen |
110 |
|
} |
111 |
|
} |
112 |
|
|
113 |
|
private String getTypeStringWww(TrainType type) { |
114 |
|
switch (type) { |
115 |
|
case STOG: |
116 |
|
return "S2"; |
117 |
|
case REGIONAL: |
118 |
|
return "FJRN"; |
119 |
|
default: |
120 |
|
return ""; //Can not happen |
121 |
|
} |
122 |
|
} |
123 |
|
|
124 |
|
public DepartureBean lookupDeparturesAzureSite(String stationcode, TrainType type, boolean arrival) throws Exception { |
125 |
|
|
126 |
|
DepartureBean departureBean = new DepartureBean(); |
127 |
|
|
128 |
|
|
129 |
|
String typeString = getTypeStringAzure(type); |
130 |
|
String arrivalDeparture = (arrival==false) ? "Afgang" : "Ankomst"; |
131 |
|
|
132 |
|
stationcode = URLEncoder.encode(stationcode,"ISO-8859-1"); |
133 |
|
|
134 |
|
String uri = "http://trafikinfo.bane.dk/Trafikinformation/AfgangAnkomst/" + arrivalDeparture + "/" + stationcode + "/" + typeString + "/UdvidetVisning"; |
135 |
|
|
136 |
|
logger.fine("URI: " + uri); |
137 |
|
JsoupInvocation wrapper = new JsoupInvocation( new URL(uri), replyTimeout); |
138 |
|
CircuitBreaker breaker = CircuitBreakerManager.getManager().getCircuitBreaker("banedk"); |
139 |
|
|
140 |
|
Document page = (Document) breaker.invoke(wrapper); |
141 |
|
|
142 |
|
String tableName = arrival == false ? "afgangtabel" : "ankomsttabel"; |
143 |
|
Element table = page.getElementById(tableName); |
144 |
|
|
145 |
|
if (table != null) { |
146 |
|
Elements tableRows = table.getElementsByTag("tr"); |
147 |
|
|
148 |
|
boolean tidsstregExists = (table.getElementsByAttributeValue("class", "Tidsstreg").size() > 0); |
149 |
|
boolean passedTidsstreg = false; |
150 |
|
|
151 |
|
for (Element currentRow : tableRows) { |
152 |
|
String rowClass = currentRow.attr("class"); |
153 |
|
|
154 |
|
if (tidsstregExists == true && passedTidsstreg == false) { |
155 |
|
if (currentRow.getElementsByAttributeValue("class", "Tidsstreg").size() > 0) { |
156 |
|
passedTidsstreg = true; |
157 |
|
} else { |
158 |
|
continue; |
159 |
|
} |
160 |
|
} |
161 |
|
|
162 |
|
if (rowClass != null && rowClass.toLowerCase().contains("station") ) { |
163 |
|
|
164 |
|
Elements fields = currentRow.getElementsByTag("td"); |
165 |
|
|
166 |
|
DepartureEntry departure = new DepartureEntry(); |
167 |
|
|
168 |
|
String time = fields.get(0).text(); |
169 |
|
if (time.equals("")) |
170 |
|
time = "0:00"; //Bane.dk bug work-around |
171 |
|
departure.setTime(time); |
172 |
|
|
173 |
|
int updated = extractUpdated( fields.get(1) ); |
174 |
|
departure.setUpdated(updated); |
175 |
|
|
176 |
|
String trainNumber = fields.get(2).text(); |
177 |
|
if (type == TrainType.STOG) //If it is S-train we need to extract the trainNumber |
178 |
|
trainNumber = trainNumber + " " + extractTrainNumberAzure(fields.get(2)); |
179 |
|
departure.setTrainNumber(trainNumber); |
180 |
|
|
181 |
|
String destination = fields.get(3).text(); |
182 |
|
departure.setDestination(destination); |
183 |
|
|
184 |
|
String origin = fields.get(4).text(); |
185 |
|
departure.setOrigin(origin); |
186 |
|
|
187 |
|
String location = fields.get(5).text(); |
188 |
|
departure.setLocation(location); |
189 |
|
|
190 |
|
String status = fields.get(6).text().trim(); |
191 |
|
departure.setStatus(status); |
192 |
|
|
193 |
|
String note = extractNote( fields.get(7) ); |
194 |
|
departure.setNote(note); |
195 |
|
|
196 |
|
departure.setType(typeString); |
197 |
|
|
198 |
|
departureBean.departureEntries.add( departure ); |
199 |
|
} |
200 |
|
} |
201 |
|
} else { |
202 |
|
logger.warning("No departures found for station=" + stationcode + ", type=" + type); |
203 |
|
} |
204 |
|
|
205 |
|
Element notifDiv = page.getElementById("station_planlagte_text"); |
206 |
|
if (notifDiv != null) { |
207 |
|
|
208 |
|
Elements tables = notifDiv.getElementsByTag("table"); |
209 |
|
for (Element tab : tables) { |
210 |
|
|
211 |
|
Elements anchors = tab.getElementsByTag("a"); |
212 |
|
if (anchors.size() == 2) { |
213 |
|
departureBean.notifications.add( anchors.get(1).text() ); |
214 |
|
} |
215 |
|
} |
216 |
|
|
217 |
|
} |
218 |
|
|
219 |
|
|
220 |
|
return departureBean; |
221 |
} |
} |
222 |
|
|
223 |
public List<DepartureBean> lookupDepartures(String stationcode, String type) throws Throwable { |
|
224 |
|
|
225 |
|
public static String cleanText(String input) { |
226 |
|
//apparently JSoup translates characters on www.bane.dk to 0xA0 |
227 |
|
return input.replace((char) 0xA0, (char)0x20).trim(); |
228 |
|
} |
229 |
|
|
230 |
|
public DepartureBean lookupDeparturesWwwSite(String stationcode, TrainType trainType, boolean arrival) throws Exception { |
231 |
|
|
232 |
|
DepartureBean departureBean = new DepartureBean(); |
233 |
|
|
234 |
List<DepartureBean> departureList = new ArrayList<DepartureBean>(); |
String type = getTypeStringWww(trainType); |
235 |
|
|
236 |
final WebClient webClient = new WebClient(); |
stationcode = URLEncoder.encode(stationcode, "ISO-8859-1"); |
237 |
webClient.setTimeout(2500); |
|
238 |
webClient.setJavaScriptEnabled(false); |
|
|
|
|
239 |
String uri = "http://www.bane.dk/visStation.asp?ArtikelID=4275&W=" + type + "&S=" + stationcode; |
String uri = "http://www.bane.dk/visStation.asp?ArtikelID=4275&W=" + type + "&S=" + stationcode; |
240 |
BanedkInvocation wrapper = new BanedkInvocation(webClient, uri); |
logger.fine("URI:" + uri); |
241 |
|
|
242 |
|
|
243 |
|
JsoupInvocation wrapper = new JsoupInvocation( new URL(uri), replyTimeout); |
244 |
CircuitBreaker breaker = CircuitBreakerManager.getManager().getCircuitBreaker("banedk"); |
CircuitBreaker breaker = CircuitBreakerManager.getManager().getCircuitBreaker("banedk"); |
245 |
|
|
246 |
HtmlPage page = (HtmlPage) breaker.invoke(wrapper); |
Element page = (Element) breaker.invoke(wrapper); |
247 |
|
|
248 |
HtmlElement table = page.getElementById("afgangtabel"); |
String tableName = arrival == false ? "afgangtabel" : "ankomsttabel"; |
249 |
|
Element table = page.getElementById(tableName); |
250 |
|
|
251 |
|
|
252 |
|
|
253 |
if (table != null) { |
if (table != null) { |
254 |
DomNodeList<HtmlElement> tableRows = table.getElementsByTagName("tr"); |
Elements tableRows = table.getElementsByTag("tr"); |
255 |
|
|
256 |
for (HtmlElement currentRow : tableRows) { |
boolean passedTidsstreg = false; |
257 |
String rowClass = currentRow.getAttribute("class"); |
boolean tidsstregExists = (table.getElementsByAttributeValue("class", "Tidsstreg").size() > 0); |
258 |
|
|
259 |
|
for (Element currentRow : tableRows) { |
260 |
|
String rowClass = currentRow.attr("class"); |
261 |
|
|
262 |
|
if (tidsstregExists == true && passedTidsstreg == false) { |
263 |
|
if (currentRow.getElementsByAttributeValue("class", "Tidsstreg").size() > 0) { |
264 |
|
passedTidsstreg = true; |
265 |
|
} else { |
266 |
|
continue; |
267 |
|
} |
268 |
|
} |
269 |
|
|
270 |
|
|
271 |
if (rowClass != null && rowClass.toLowerCase().contains("station") ) { |
if (rowClass != null && rowClass.toLowerCase().contains("station") ) { |
272 |
DomNodeList<HtmlElement> fields = currentRow.getElementsByTagName("td"); |
Elements fields = currentRow.getElementsByTag("td"); |
273 |
|
|
274 |
DepartureBean departure = new DepartureBean(); |
DepartureEntry departure = new DepartureEntry(); |
275 |
|
|
276 |
String time = fields.get(0).asText(); |
|
277 |
|
|
278 |
|
String time = cleanText( fields.get(0).getAllElements().get(2).text() ); |
279 |
if (time.equals("")) |
if (time.equals("")) |
280 |
time = "0:00"; //Bane.dk bug work-around |
time = "0:00"; //Bane.dk bug work-around |
281 |
departure.setTime(time); |
departure.setTime(time); |
283 |
int updated = extractUpdated( fields.get(1) ); |
int updated = extractUpdated( fields.get(1) ); |
284 |
departure.setUpdated(updated); |
departure.setUpdated(updated); |
285 |
|
|
286 |
String trainNumber = fields.get(2).asText(); |
String trainNumber = cleanText( fields.get(2).text() ); |
287 |
if (type.equalsIgnoreCase("S2")) //If it is S-train we need to extract the trainNumber |
if (type.equalsIgnoreCase("S2")) //If it is S-train we need to extract the trainNumber |
288 |
trainNumber = trainNumber + " " + extractTrainNumber(fields.get(2)); |
trainNumber = trainNumber + " " + extractTrainNumberWww(fields.get(2)); |
289 |
departure.setTrainNumber(trainNumber); |
departure.setTrainNumber(trainNumber); |
290 |
|
|
291 |
String destination = fields.get(3).asText(); |
String destination = cleanText( fields.get(3).text() ); |
292 |
departure.setDestination(destination); |
departure.setDestination(destination); |
293 |
|
|
294 |
String origin = fields.get(4).asText(); |
String origin = cleanText( fields.get(4).text() ); |
295 |
departure.setOrigin(origin); |
departure.setOrigin(origin); |
296 |
|
|
297 |
String location = fields.get(5).asText(); |
String location = cleanText( fields.get(5).text() ); |
298 |
departure.setLocation(location); |
departure.setLocation(location); |
299 |
|
|
300 |
String status = fields.get(6).asText(); |
String status = cleanText( fields.get(6).text() ); |
301 |
departure.setStatus(status); |
departure.setStatus(status); |
302 |
|
|
303 |
String note = extractNote( fields.get(7) ); |
String note = cleanText( extractNote( fields.get(7) ) ); |
304 |
departure.setNote(note); |
departure.setNote(note); |
305 |
|
|
306 |
departureList.add(departure); |
departure.setType(type); |
307 |
|
|
308 |
|
departureBean.departureEntries.add(departure); |
309 |
|
|
310 |
|
|
311 |
} |
} |
312 |
} |
} |
313 |
} else { |
} else { |
314 |
logger.warning("No departures found for station=" + stationcode + ", type=" + type); |
logger.warning("No departures found for station=" + stationcode + ", type=" + type); |
315 |
} |
} |
316 |
|
|
317 |
return departureList; |
|
318 |
|
return departureBean; |
319 |
} |
} |
320 |
|
|
321 |
|
|
322 |
private int extractUpdated(HtmlElement updatedTd) { //extract the digit (in this case: 4) from "media/trafikinfo/opdater4.gif" |
private int extractUpdated(Element updatedTd) { //extract the digit (in this case: 4) from "media/trafikinfo/opdater4.gif" |
323 |
int updated = -1; |
int updated = -1; |
324 |
|
|
325 |
DomNodeList<HtmlElement> updatedImgs = updatedTd.getElementsByTagName("img"); |
Elements updatedImgs = updatedTd.getElementsByTag("img"); |
326 |
String updatedStr = updatedImgs.get(0).getAttribute("src"); |
String updatedStr = updatedImgs.get(0).attr("src"); |
327 |
|
|
328 |
if (updatedStr != null) { |
if (updatedStr != null) { |
329 |
for (int i=0; i<updatedStr.length(); i++) { |
for (int i=0; i<updatedStr.length(); i++) { |
337 |
return updated; |
return updated; |
338 |
} |
} |
339 |
|
|
340 |
private String extractNote(HtmlElement noteTd) { |
private String extractNote(Element noteTd) { |
341 |
String note = noteTd.asText().trim(); |
String note = noteTd.text().trim(); |
342 |
|
|
343 |
|
|
344 |
List<HtmlElement> elems = noteTd.getElementsByAttribute("span", "class", "bemtype"); |
Elements elems = noteTd.getElementsByClass("bemtype"); |
345 |
if (elems.size() > 0 && note.charAt(note.length()-1) == 'i') |
if (elems.size() > 0 && note.charAt(note.length()-1) == 'i') |
346 |
note = note.substring(0,note.length() -1 ); |
note = note.substring(0,note.length() -1 ); |
347 |
|
|
348 |
return note; |
return note.trim(); |
349 |
|
} |
350 |
|
|
351 |
|
private String extractTrainNumberAzure(Element trainTd) { |
352 |
|
Element anchorElement = trainTd.getElementsByTag("a").get(0); |
353 |
|
String href = anchorElement.attr("href"); |
354 |
|
|
355 |
|
int pos = href.lastIndexOf('/'); |
356 |
|
String number = href.substring(pos+1); |
357 |
|
|
358 |
|
return number; |
359 |
} |
} |
360 |
|
|
361 |
private String extractTrainNumber(HtmlElement trainTd) { |
private String extractTrainNumberWww(Element trainTd) { |
362 |
String number = ""; |
String number = ""; |
363 |
HtmlElement anchorElement = trainTd.getElementsByTagName("a").get(0); |
Element anchorElement = trainTd.getElementsByTag("a").get(0); |
364 |
String href = anchorElement.getAttribute("href"); |
String href = anchorElement.attr("href"); |
365 |
String argstring = href.substring( href.indexOf('?') + 1); |
String argstring = href.substring( href.indexOf('?') + 1); |
366 |
|
|
367 |
String args[] = argstring.split("&"); |
String args[] = argstring.split("&"); |
373 |
} |
} |
374 |
|
|
375 |
|
|
|
|
|
376 |
return number; |
return number; |
377 |
} |
} |
378 |
|
|
379 |
|
|
380 |
//test |
//test |
381 |
public static void main(String args[]) throws Throwable { |
/* |
382 |
|
public static void main(String args[]) throws Exception { |
383 |
DepartureFetcher f = new DepartureFetcher(); |
DepartureFetcher f = new DepartureFetcher(); |
384 |
List<DepartureBean> deps = f.lookupDepartures("AR", "FJRN"); |
List<DepartureBean> deps = f.lookupDepartures("AR", "FJRN"); |
385 |
for(DepartureBean d : deps) { |
for(DepartureBean d : deps) { |
388 |
} |
} |
389 |
|
|
390 |
System.out.println("--------------------------"); |
System.out.println("--------------------------"); |
391 |
} |
}*/ |
392 |
} |
} |