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

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

Parent Directory Parent Directory | Revision Log Revision Log


Revision 1564 - (show 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 package dk.thoerup.traininfoservice.banedk;
2
3
4 import java.net.URL;
5 import java.net.URLEncoder;
6 import java.util.Collections;
7 import java.util.Comparator;
8 import java.util.HashMap;
9 import java.util.Map;
10 import java.util.logging.Level;
11 import java.util.logging.Logger;
12
13 import net.sf.jsr107cache.Cache;
14 import net.sf.jsr107cache.CacheException;
15 import net.sf.jsr107cache.CacheManager;
16
17 import org.jsoup.nodes.Document;
18 import org.jsoup.nodes.Element;
19 import org.jsoup.select.Elements;
20
21 import com.google.appengine.api.memcache.jsr107cache.GCacheFactory;
22
23 import dk.thoerup.android.traininfo.common.DepartureBean;
24 import dk.thoerup.android.traininfo.common.DepartureEntry;
25 import dk.thoerup.android.traininfo.common.StationEntry;
26 import dk.thoerup.circuitbreaker.CircuitBreaker;
27 import dk.thoerup.circuitbreaker.CircuitBreakerManager;
28 import dk.thoerup.traininfoservice.StationDAO;
29 import dk.thoerup.traininfoservice.Statistics;
30
31 public class DepartureFetcher {
32
33 enum TrainType{
34 STOG,
35 REGIONAL
36 }
37 Cache cache;
38
39 Logger logger = Logger.getLogger(DepartureFetcher.class.getName());
40
41 StationDAO stationDao = new StationDAO();
42
43 private boolean useAzureSite;
44 private int replyTimeout;
45
46 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 @SuppressWarnings("unchecked")
79 public DepartureFetcher(boolean azureSite, int cacheTimeout, int replyTimeout) {
80 this.replyTimeout = replyTimeout;
81 useAzureSite = azureSite;
82
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 }
93
94
95
96
97 public DepartureBean cachedLookupDepartures(int stationID, boolean arrival) throws Exception {
98 final String key = "departure:" + stationID + ":" + arrival;
99
100 DepartureBean departureBean = (DepartureBean) cache.get(key);
101
102 if (departureBean == null) {
103 departureBean = lookupDepartures(stationID,arrival);
104 cache.put(key, departureBean);
105 logger.info("Departure: Cache miss " + key + " !!! "); //remove before production
106 } else {
107 Statistics.getInstance().incrementDepartureCacheHits();
108 logger.info("Departure: Cache hit " + key);
109 }
110
111 return departureBean;
112 }
113
114
115 public DepartureBean lookupDepartures(int stationID, boolean arrival) throws Exception {
116
117 DepartureBean departureBean = new DepartureBean();
118
119 StationEntry station = stationDao.getById(stationID);
120
121
122 departureBean.stationName = station.getName();
123
124 if (station.getRegional() != null) {
125 DepartureBean tempBean = lookupDepartures(station.getRegional(), TrainType.REGIONAL, arrival);
126 departureBean.entries.addAll( tempBean.entries );
127 departureBean.notifications.addAll(tempBean.notifications);
128 }
129
130 if (station.getStrain() != null) {
131 DepartureBean tempBean = lookupDepartures(station.getStrain(), TrainType.STOG, arrival);
132 departureBean.entries.addAll( tempBean.entries );
133 departureBean.notifications.addAll(tempBean.notifications);
134 }
135
136 if (departureBean.entries.size() == 0) {
137 logger.info("No departures found for station " + stationID);
138 }
139
140 Collections.sort( departureBean.entries, departureTimeComparator );
141
142
143 return departureBean;
144 }
145
146 public DepartureBean lookupDepartures(String stationcode, TrainType type, boolean arrival) throws Exception {
147 if (useAzureSite == true) {
148 return lookupDeparturesAzureSite(stationcode, type, arrival);
149 } else {
150 return lookupDeparturesWwwSite(stationcode, type, arrival);
151 }
152 }
153
154 private String getTypeStringAzure(TrainType type) {
155 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 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
178 DepartureBean departureBean = new DepartureBean();
179
180
181 String typeString = getTypeStringAzure(type);
182 String arrivalDeparture = (arrival==false) ? "Afgang" : "Ankomst";
183
184 stationcode = URLEncoder.encode(stationcode,"ISO-8859-1");
185
186 String uri = "http://trafikinfo.bane.dk/Trafikinformation/AfgangAnkomst/" + arrivalDeparture + "/" + stationcode + "/" + typeString + "/UdvidetVisning";
187
188 logger.fine("URI: " + uri);
189 JsoupInvocation wrapper = new JsoupInvocation( new URL(uri), replyTimeout);
190 CircuitBreaker breaker = CircuitBreakerManager.getManager().getCircuitBreaker("banedk");
191
192 Document page = (Document) breaker.invoke(wrapper);
193
194 String tableName = arrival == false ? "afgangtabel" : "ankomsttabel";
195 Element table = page.getElementById(tableName);
196
197 if (table != null) {
198 Elements tableRows = table.getElementsByTag("tr");
199
200 boolean tidsstregExists = (table.getElementsByAttributeValue("class", "Tidsstreg").size() > 0);
201 boolean passedTidsstreg = false;
202
203 for (Element currentRow : tableRows) {
204 String rowClass = currentRow.attr("class");
205
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 if (rowClass != null && rowClass.toLowerCase().contains("station") ) {
215
216 Elements fields = currentRow.getElementsByTag("td");
217
218 DepartureEntry departure = new DepartureEntry();
219
220 String time = fields.get(0).text();
221 if (time.equals(""))
222 time = "0:00"; //Bane.dk bug work-around
223 departure.setTime(time);
224
225 int updated = extractUpdated( fields.get(1) );
226 departure.setUpdated(updated);
227
228 String trainNumber = fields.get(2).text();
229 if (type == TrainType.STOG) //If it is S-train we need to extract the trainNumber
230 trainNumber = trainNumber + " " + extractTrainNumberAzure(fields.get(2));
231 departure.setTrainNumber(trainNumber);
232
233 String destination = fields.get(3).text();
234 departure.setDestination(destination);
235
236 String origin = fields.get(4).text();
237 departure.setOrigin(origin);
238
239 String location = fields.get(5).text();
240 departure.setLocation(location);
241
242 String status = fields.get(6).text().trim();
243 departure.setStatus(status);
244
245 String note = extractNote( fields.get(7) );
246 departure.setNote(note);
247
248 departure.setType(typeString);
249
250 departureBean.entries.add( departure );
251 }
252 }
253 } else {
254 logger.warning("No departures found for station=" + stationcode + ", type=" + type);
255 }
256
257 Element notifDiv = page.getElementById("station_planlagte_text");
258 if (notifDiv != null) {
259
260 Elements tables = notifDiv.getElementsByTag("table");
261 for (Element tab : tables) {
262
263 Elements anchors = tab.getElementsByTag("a");
264 if (anchors.size() == 2) {
265 departureBean.notifications.add( anchors.get(1).text() );
266 }
267 }
268
269 }
270
271
272 return departureBean;
273 }
274
275
276
277 public static String cleanText(String input) {
278 //apparently JSoup translates &nbsp; characters on www.bane.dk to 0xA0
279 return input.replace((char) 0xA0, (char)0x20).trim();
280 }
281
282 public DepartureBean lookupDeparturesWwwSite(String stationcode, TrainType trainType, boolean arrival) throws Exception {
283
284 DepartureBean departureBean = new DepartureBean();
285
286 String type = getTypeStringWww(trainType);
287
288 stationcode = URLEncoder.encode(stationcode, "ISO-8859-1");
289
290
291 String uri = "http://www.bane.dk/visStation.asp?ArtikelID=4275&W=" + type + "&S=" + stationcode;
292 logger.fine("URI:" + uri);
293
294
295 JsoupInvocation wrapper = new JsoupInvocation( new URL(uri), replyTimeout);
296 CircuitBreaker breaker = CircuitBreakerManager.getManager().getCircuitBreaker("banedk");
297
298 Element page = (Element) breaker.invoke(wrapper);
299
300 String tableName = arrival == false ? "afgangtabel" : "ankomsttabel";
301 Element table = page.getElementById(tableName);
302
303
304
305 if (table != null) {
306 Elements tableRows = table.getElementsByTag("tr");
307
308 boolean passedTidsstreg = false;
309 boolean tidsstregExists = (table.getElementsByAttributeValue("class", "Tidsstreg").size() > 0);
310
311 for (Element currentRow : tableRows) {
312 String rowClass = currentRow.attr("class");
313
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 if (rowClass != null && rowClass.toLowerCase().contains("station") ) {
324 Elements fields = currentRow.getElementsByTag("td");
325
326 DepartureEntry departure = new DepartureEntry();
327
328
329
330 String time = cleanText( fields.get(0).getAllElements().get(2).text() );
331 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 String trainNumber = cleanText( fields.get(2).text() );
339 if (type.equalsIgnoreCase("S2")) //If it is S-train we need to extract the trainNumber
340 trainNumber = trainNumber + " " + extractTrainNumberWww(fields.get(2));
341 departure.setTrainNumber(trainNumber);
342
343 String destination = cleanText( fields.get(3).text() );
344 departure.setDestination(destination);
345
346 String origin = cleanText( fields.get(4).text() );
347 departure.setOrigin(origin);
348
349 String location = cleanText( fields.get(5).text() );
350 departure.setLocation(location);
351
352 String status = cleanText( fields.get(6).text() );
353 departure.setStatus(status);
354
355 String note = cleanText( extractNote( fields.get(7) ) );
356 departure.setNote(note);
357
358 departure.setType(type);
359
360 departureBean.entries.add(departure);
361
362
363 }
364 }
365 } else {
366 logger.warning("No departures found for station=" + stationcode + ", type=" + type);
367 }
368
369
370 return departureBean;
371 }
372
373
374 private int extractUpdated(Element updatedTd) { //extract the digit (in this case: 4) from "media/trafikinfo/opdater4.gif"
375 int updated = -1;
376
377 Elements updatedImgs = updatedTd.getElementsByTag("img");
378 String updatedStr = updatedImgs.get(0).attr("src");
379
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 private String extractNote(Element noteTd) {
393 String note = noteTd.text().trim();
394
395
396 Elements elems = noteTd.getElementsByClass("bemtype");
397 if (elems.size() > 0 && note.charAt(note.length()-1) == 'i')
398 note = note.substring(0,note.length() -1 );
399
400 return note.trim();
401 }
402
403 private String extractTrainNumberAzure(Element trainTd) {
404 Element anchorElement = trainTd.getElementsByTag("a").get(0);
405 String href = anchorElement.attr("href");
406
407 int pos = href.lastIndexOf('/');
408 String number = href.substring(pos+1);
409
410 return number;
411 }
412
413 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 //test
433 /*
434 public static void main(String args[]) throws Exception {
435 DepartureFetcher f = new DepartureFetcher();
436 List<DepartureBean> deps = f.lookupDepartures("AR", "FJRN");
437 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 }*/
444 }

  ViewVC Help
Powered by ViewVC 1.1.20