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