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

  ViewVC Help
Powered by ViewVC 1.1.20