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

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

Parent Directory Parent Directory | Revision Log Revision Log | View Patch Patch

revision 1255 by torben, Mon Apr 4 10:56:44 2011 UTC revision 1424 by torben, Mon May 2 17:19:30 2011 UTC
# Line 13  import org.jsoup.select.Elements; Line 13  import org.jsoup.select.Elements;
13    
14  import dk.thoerup.android.traininfo.common.DepartureBean;  import dk.thoerup.android.traininfo.common.DepartureBean;
15  import dk.thoerup.android.traininfo.common.DepartureEntry;  import dk.thoerup.android.traininfo.common.DepartureEntry;
16  import dk.thoerup.android.traininfo.common.StationBean.StationEntry;  import dk.thoerup.android.traininfo.common.StationEntry;
17  import dk.thoerup.circuitbreaker.CircuitBreaker;  import dk.thoerup.circuitbreaker.CircuitBreaker;
18  import dk.thoerup.circuitbreaker.CircuitBreakerManager;  import dk.thoerup.circuitbreaker.CircuitBreakerManager;
19    import dk.thoerup.genericjavautils.HttpUtil;
20    import dk.thoerup.genericjavautils.TimeoutMap;
21  import dk.thoerup.traininfoservice.Statistics;  import dk.thoerup.traininfoservice.Statistics;
22    import dk.thoerup.traininfoservice.TraininfoSettings;
23  import dk.thoerup.traininfoservice.db.StationDAO;  import dk.thoerup.traininfoservice.db.StationDAO;
24    
25  public class DepartureFetcher {  public class DepartureFetcher {
# Line 38  public class DepartureFetcher { Line 41  public class DepartureFetcher {
41                    
42          StationDAO stationDao = new StationDAO();          StationDAO stationDao = new StationDAO();
43                    
44          private boolean useAzureSite;  
45          private int replyTimeout;          private TraininfoSettings settings;
46                    
47          public DepartureFetcher(boolean azureSite, int cacheTimeout, int replyTimeout) {          public DepartureFetcher(TraininfoSettings settings) {
48                  this.replyTimeout = replyTimeout;                  this.settings = settings;
49                  useAzureSite = azureSite;                  cache = new TimeoutMap<String,DepartureBean>( settings.getCacheTimeout() );
                 cache = new TimeoutMap<String,DepartureBean>(cacheTimeout);  
50          }          }
51                    
52                    
# Line 76  public class DepartureFetcher { Line 78  public class DepartureFetcher {
78                                    
79                  departureBean.stationName = station.getName();                  departureBean.stationName = station.getName();
80    
81                    //TODO: FetchTraintype.Both should be removed some time after 0.9.5 release
82                  if (station.getRegional() != null && (type == FetchTrainType.REGIONAL||type == FetchTrainType.BOTH) ) {                  if (station.getRegional() != null && (type == FetchTrainType.REGIONAL||type == FetchTrainType.BOTH) ) {
83                          DepartureBean tempBean = lookupDepartures(station.getRegional(), TrainType.REGIONAL, arrival);                          DepartureBean tempBean = lookupDepartures(station.getRegional(), TrainType.REGIONAL, arrival);
84                          departureBean.entries.addAll( tempBean.entries );                          departureBean.entries.addAll( tempBean.entries );
# Line 92  public class DepartureFetcher { Line 95  public class DepartureFetcher {
95                          logger.info("No departures found for station " + stationID);                          logger.info("No departures found for station " + stationID);
96                  }                  }
97                                    
98                    //TODO: FetchTraintype.Both should be removed some time after 0.9.5 release
99                  if (type == FetchTrainType.BOTH) { //if we have both S-tog and regional order by departure/arrival time                  if (type == FetchTrainType.BOTH) { //if we have both S-tog and regional order by departure/arrival time
100                          Collections.sort( departureBean.entries );                          Collections.sort( departureBean.entries );
101                  }                  }
# Line 101  public class DepartureFetcher { Line 105  public class DepartureFetcher {
105          }          }
106                    
107          public DepartureBean lookupDepartures(String stationcode, TrainType type, boolean arrival) throws Exception {          public DepartureBean lookupDepartures(String stationcode, TrainType type, boolean arrival) throws Exception {
108                  if (useAzureSite == true) {                  if ( settings.getBackend() == TraininfoSettings.Backend.Azure) {
109                          return lookupDeparturesAzureSite(stationcode, type, arrival);                          return lookupDeparturesAzureSite(stationcode, type, arrival);
110                  } else {                  } else {
111                          return lookupDeparturesWwwSite(stationcode, type, arrival);                          return lookupDeparturesMobileSite(stationcode, type, arrival);
112                  }                  }
113          }          }
114                    
# Line 143  public class DepartureFetcher { Line 147  public class DepartureFetcher {
147              String uri = "http://trafikinfo.bane.dk/Trafikinformation/AfgangAnkomst/" + arrivalDeparture + "/" + stationcode + "/" + typeString + "/UdvidetVisning";                      String uri = "http://trafikinfo.bane.dk/Trafikinformation/AfgangAnkomst/" + arrivalDeparture + "/" + stationcode + "/" + typeString + "/UdvidetVisning";        
148                            
149              logger.fine("URI: " + uri);                  logger.fine("URI: " + uri);    
150              JsoupInvocation wrapper = new JsoupInvocation( new URL(uri), replyTimeout);              JsoupInvocation wrapper = new JsoupInvocation( new URL(uri), settings.getReplyTimeout() );
151              CircuitBreaker breaker = CircuitBreakerManager.getManager().getCircuitBreaker("banedk");              CircuitBreaker breaker = CircuitBreakerManager.getManager().getCircuitBreaker("banedk");
152                            
153              Document page = (Document) breaker.invoke(wrapper);              Document page = (Document) breaker.invoke(wrapper);
# Line 229  public class DepartureFetcher { Line 233  public class DepartureFetcher {
233              return departureBean;              return departureBean;
234          }          }
235                    
236            public DepartureBean lookupDeparturesMobileSite(String stationcode, TrainType traintype, boolean arrival) throws Exception {
237                    
238                    DepartureBean departureBean = new DepartureBean();
239                    
240                
241                    String typeString = getTypeStringWww(traintype);
242                String arrivalDeparture = (arrival==false) ? "afgang" : "ankomst";
243                
244                stationcode = URLEncoder.encode(stationcode,"ISO-8859-1");
245    
246                
247                String uri = "http://mobil.bane.dk/mobilStation.asp?artikelID=5332&stat_kode=" + stationcode + "&webprofil=" + typeString  +"&beskrivelse=&mode=ankomstafgang&ankomstafgang=" + arrivalDeparture + "&gemstation=&fuldvisning=1";
248                logger.fine("URI: " + uri);    
249                JsoupInvocation wrapper = new JsoupInvocation( new URL(uri), settings.getReplyTimeout() );
250                CircuitBreaker breaker = CircuitBreakerManager.getManager().getCircuitBreaker("banedk");
251                
252                Document page = (Document) breaker.invoke(wrapper);
253                
254                
255                Element content = page.getElementsByClass("contentDiv").get(0);
256                
257                
258                if (content != null) {
259                        Elements tableRows =  content.child(0).children();
260                        
261    
262                        
263                        for (Element currentRow : tableRows) {
264                            if (currentRow.tagName().equals("br") ) {
265                                    break;
266                            }
267                            
268                            
269                            String link = currentRow.child(0).attr("href");
270                            
271                                    logger.fine( currentRow.text() );
272                                    logger.fine("Href: " + link);
273                            
274    
275                            String parts[] = currentRow.text().split(",");
276                    
277    
278                            DepartureEntry departure = new DepartureEntry();
279                            
280                            //if we do these things upfront, then we are allowed to use continue statement when row contains no more data
281                            departure.setType(typeString);
282                            departureBean.entries.add( departure );
283    
284    /*
285    http://mobil.bane.dk/mobilStation.asp?artikelID=5332&tognummer=111&webprofil=FJRN&mode=rute&strBemaerkning=Afg%E5r+fra+%C5rhus+H+kl%2E07%3A21++&strRefURL=%2FmobilStation%2Easp%3FartikelID%3D5332%26stat%5Fkode%3DAR%26webprofil%3DFJRN%26beskrivelse%3D%25C5rhus%2BH%26mode%3Dankomstafgang%26ankomstafgang%3Dafgang%26gemstation%3D
286    */
287                            int offset = 0;
288                            
289                            String time = parts[offset++];
290                            if (time.equals(""))
291                                    time = "0:00"; //Bane.dk bug work-around
292                            departure.setTime(time);
293    
294                            int updated = 4; //does not exist on mobile
295                            departure.setUpdated(updated);
296    
297                            String trainNumber = extractTrainNumberMobile(link);
298                            /*if (traintype == TrainType.STOG) //If it is S-train we need to extract the trainNumber
299                                    trainNumber = trainNumber + " " + extractTrainNumberAzure(fields.get(2));*/
300                            departure.setTrainNumber(trainNumber);
301    
302                                    if (traintype == TrainType.STOG) { //if it is stog the next vield is the "Line" code - this should be used somewhere, but skippint ahead for now
303                                            String stogLine = parts[offset++].trim();
304                                            departure.setTrainNumber(stogLine + " " + trainNumber);
305                                    }
306    
307                            String destination = parts[offset++].trim();;
308                            departure.setDestination(destination);
309    
310                            String origin = "-"; // fields.get(4).text(); does not exist on mobile
311                            departure.setOrigin(origin);
312    
313                            String location = ""; // fields.get(5).text(); does not exist on mobile
314                            departure.setLocation(location);
315                            
316                            if (offset == parts.length) {
317                                    continue;
318                            }
319                            
320                            if (parts[offset].trim().equalsIgnoreCase("NB!")) {
321                                    offset++;
322                            }
323                            
324                            if (offset == parts.length) {
325                                    continue;
326                            }
327    
328                            String status = parts[offset++].trim();; //fields.get(6).text().trim(); - extract from url
329                            departure.setStatus(status);
330    
331                            String note = ""; //extractNote( fields.get(7) ); - extract from url
332                            departure.setNote(note);
333    
334                        }
335                } else {
336                    logger.warning("No departures found for station=" + stationcode + ", type=" + traintype);
337                }
338                
339                return departureBean;
340            }
341            
342                    
343                    
344          public static String cleanText(String input) {          public static String cleanText(String input) {
# Line 236  public class DepartureFetcher { Line 346  public class DepartureFetcher {
346                  return input.replace((char) 0xA0, (char)0x20).trim();                  return input.replace((char) 0xA0, (char)0x20).trim();
347          }          }
348                    
349            
350            // old www site is not available any more
351            @Deprecated
352          public DepartureBean lookupDeparturesWwwSite(String stationcode, TrainType trainType, boolean arrival) throws Exception {          public DepartureBean lookupDeparturesWwwSite(String stationcode, TrainType trainType, boolean arrival) throws Exception {
353                                    
354                  DepartureBean departureBean = new DepartureBean();                  DepartureBean departureBean = new DepartureBean();
# Line 249  public class DepartureFetcher { Line 362  public class DepartureFetcher {
362              logger.fine("URI:" + uri);              logger.fine("URI:" + uri);
363                            
364    
365              JsoupInvocation wrapper = new JsoupInvocation( new URL(uri), replyTimeout);              JsoupInvocation wrapper = new JsoupInvocation( new URL(uri), settings.getReplyTimeout() );
366              CircuitBreaker breaker = CircuitBreakerManager.getManager().getCircuitBreaker("banedk");              CircuitBreaker breaker = CircuitBreakerManager.getManager().getCircuitBreaker("banedk");
367                            
368              Element page = (Element) breaker.invoke(wrapper);              Element page = (Element) breaker.invoke(wrapper);
# Line 367  public class DepartureFetcher { Line 480  public class DepartureFetcher {
480                  return number;                  return number;
481          }          }
482                    
483            private String extractTrainNumberMobile(String link) {
484                    Map<String,String> elements = HttpUtil.decodeParams(link);
485                    
486                    return elements.get("tognummer");
487            }
488            
489          private String extractTrainNumberWww(Element trainTd) {          private String extractTrainNumberWww(Element trainTd) {
490                  String number = "";                  String number = "";
491                  Element anchorElement = trainTd.getElementsByTag("a").get(0);                  Element anchorElement = trainTd.getElementsByTag("a").get(0);
492                  String href = anchorElement.attr("href");                  String href = anchorElement.attr("href");
493                  String argstring = href.substring( href.indexOf('?') + 1);  
494                    String argstring = href.split("?")[1];
495                    Map<String,String> elements = HttpUtil.decodeParams(argstring);
496                    number = elements.get("TogNr");        
497                                    
498                    
499                    /*String argstring = href.substring( href.indexOf('?') + 1);
500                  String args[] = argstring.split("&");                  String args[] = argstring.split("&");
501                  for (String arg : args) {                  for (String arg : args) {
502                          String pair[] = arg.split("="); // Key=pair[0], Value=pair[1]                          String pair[] = arg.split("="); // Key=pair[0], Value=pair[1]
503                                                    
504                          if (pair[0].equalsIgnoreCase("TogNr"))                          if (pair[0].equalsIgnoreCase("TogNr"))
505                                  number = pair[1];                                  number = pair[1];
506                  }                  }*/
507                                                                    
508                                    
509                  return number;                  return number;
510          }          }

Legend:
Removed from v.1255  
changed lines
  Added in v.1424

  ViewVC Help
Powered by ViewVC 1.1.20