/[projects]/android/TrainInfoService/src/dk/thoerup/traininfoservice/banedk/DepartureFetcher.java
ViewVC logotype

Annotation of /android/TrainInfoService/src/dk/thoerup/traininfoservice/banedk/DepartureFetcher.java

Parent Directory Parent Directory | Revision Log Revision Log


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

  ViewVC Help
Powered by ViewVC 1.1.20