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

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

Parent Directory Parent Directory | Revision Log Revision Log


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

  ViewVC Help
Powered by ViewVC 1.1.20