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

  ViewVC Help
Powered by ViewVC 1.1.20