/[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 994 by torben, Wed Jul 14 19:22:23 2010 UTC revision 1332 by torben, Wed Apr 20 06:20:27 2011 UTC
# Line 11  import org.jsoup.nodes.Document; Line 11  import org.jsoup.nodes.Document;
11  import org.jsoup.nodes.Element;  import org.jsoup.nodes.Element;
12  import org.jsoup.select.Elements;  import org.jsoup.select.Elements;
13    
14    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  import dk.thoerup.circuitbreaker.CircuitBreaker;  import dk.thoerup.circuitbreaker.CircuitBreaker;
18  import dk.thoerup.circuitbreaker.CircuitBreakerManager;  import dk.thoerup.circuitbreaker.CircuitBreakerManager;
 import dk.thoerup.traininfoservice.StationBean;  
 import dk.thoerup.traininfoservice.StationDAO;  
19  import dk.thoerup.traininfoservice.Statistics;  import dk.thoerup.traininfoservice.Statistics;
20    import dk.thoerup.traininfoservice.TraininfoSettings;
21    import dk.thoerup.traininfoservice.db.StationDAO;
22    
23  public class DepartureFetcher {  public class DepartureFetcher {
24                    
# Line 24  public class DepartureFetcher { Line 27  public class DepartureFetcher {
27                  REGIONAL                  REGIONAL
28          }          }
29                    
30            enum FetchTrainType {
31                    STOG,
32                    REGIONAL,
33                    BOTH
34            }
35            
36          Logger logger = Logger.getLogger(DepartureFetcher.class.getName());          Logger logger = Logger.getLogger(DepartureFetcher.class.getName());
37                    
38          Map<String, DepartureBean> cache;          Map<String, DepartureBean> cache;
39                    
40          StationDAO stationDao = new StationDAO();          StationDAO stationDao = new StationDAO();
41                    
42          private boolean useTempSite;  
43            private TraininfoSettings settings;
44                    
45          public DepartureFetcher(boolean tempSite, int cacheTimeout) {          public DepartureFetcher(TraininfoSettings settings) {
46                  useTempSite = tempSite;                  this.settings = settings;
47                  cache = new TimeoutMap<String,DepartureBean>(cacheTimeout);                  cache = new TimeoutMap<String,DepartureBean>( settings.getCacheTimeout() );
48          }          }
49                    
50                    
51                                    
52                    
53          public DepartureBean cachedLookupDepartures(int stationID, boolean arrival) throws Exception {          public DepartureBean cachedLookupDepartures(int stationID, boolean arrival, FetchTrainType type) throws Exception {
54                  final String key = "" + stationID + ":" + arrival;                  
55                    final String key = "" + stationID + ":" + arrival + ":" + type.toString();
56                                    
57                  DepartureBean departureBean = cache.get(key);                  DepartureBean departureBean = cache.get(key);
58    
59                                    
60                  if (departureBean == null) {                  if (departureBean == null) {
61                          departureBean = lookupDepartures(stationID,arrival);                          departureBean = lookupDepartures(stationID, arrival, type);
62                          cache.put(key, departureBean);                          cache.put(key, departureBean);
63                  } else {                  } else {
64                          Statistics.getInstance().incrementDepartureCacheHits();                          Statistics.getInstance().incrementDepartureCacheHits();
# Line 57  public class DepartureFetcher { Line 68  public class DepartureFetcher {
68          }          }
69                                    
70    
71          public DepartureBean lookupDepartures(int stationID, boolean arrival) throws Exception {          public DepartureBean lookupDepartures(int stationID, boolean arrival, FetchTrainType type) throws Exception {
72                                    
73                  DepartureBean departureBean = new DepartureBean();                  DepartureBean departureBean = new DepartureBean();
74                                    
75                  StationBean station = stationDao.getById(stationID);                  StationEntry station = stationDao.getById(stationID);
76                                    
77                  if (station.getRegional() != null) {                  departureBean.stationName = station.getName();
78    
79                    if (station.getRegional() != null && (type == FetchTrainType.REGIONAL||type == FetchTrainType.BOTH) ) {
80                          DepartureBean tempBean = lookupDepartures(station.getRegional(), TrainType.REGIONAL, arrival);                          DepartureBean tempBean = lookupDepartures(station.getRegional(), TrainType.REGIONAL, arrival);
81                          departureBean.departureEntries.addAll( tempBean.departureEntries );                          departureBean.entries.addAll( tempBean.entries );
82                          departureBean.notifications.addAll(tempBean.notifications);                          departureBean.notifications.addAll(tempBean.notifications);
83                  }                  }
84                                    
85                  if (station.getStrain() != null) {                  if (station.getStrain() != null && (type == FetchTrainType.STOG||type == FetchTrainType.BOTH)) {
86                          DepartureBean tempBean = lookupDepartures(station.getStrain(), TrainType.STOG, arrival);                          DepartureBean tempBean = lookupDepartures(station.getStrain(), TrainType.STOG, arrival);
87                          departureBean.departureEntries.addAll( tempBean.departureEntries );                          departureBean.entries.addAll( tempBean.entries );
88                          departureBean.notifications.addAll(tempBean.notifications);                          departureBean.notifications.addAll(tempBean.notifications);
89                  }                                }              
90                                    
91                  Collections.sort( departureBean.departureEntries );                  if (departureBean.entries.size() == 0) {
92                            logger.info("No departures found for station " + stationID);
93                    }
94                    
95                    if (type == FetchTrainType.BOTH) { //if we have both S-tog and regional order by departure/arrival time
96                            Collections.sort( departureBean.entries );
97                    }
98    
99                                    
100                  return departureBean;                  return departureBean;
101          }          }
102                    
103          public DepartureBean lookupDepartures(String stationcode, TrainType type, boolean arrival) throws Exception {          public DepartureBean lookupDepartures(String stationcode, TrainType type, boolean arrival) throws Exception {
104                  if (useTempSite == false) {                  if ( settings.getUseAzureSite() == true) {
105                          return lookupDeparturesNormalSite(stationcode, type, arrival);                          return lookupDeparturesAzureSite(stationcode, type, arrival);
106                  } else {                  } else {
107                          //return lookupDeparturesFromTemporarySite(stationcode, type);                          return lookupDeparturesMobileSite(stationcode, type, arrival);
                         //TODO: find out what to to if they ever put a temp site up on trafikinfo.bane.dk  
                         return null;  
108                  }                  }
109          }          }
110                    
111          private String getTypeString(TrainType type) {          private String getTypeStringAzure(TrainType type) {
112                  switch (type) {                  switch (type) {
113                  case STOG:                  case STOG:
114                          return "S-Tog";                          return "S-Tog";
# Line 102  public class DepartureFetcher { Line 119  public class DepartureFetcher {
119                  }                  }
120          }          }
121                    
122          public DepartureBean lookupDeparturesNormalSite(String stationcode, TrainType type, boolean arrival) throws Exception {          private String getTypeStringWww(TrainType type) {
123                    switch (type) {
124                    case STOG:
125                            return "S2";
126                    case REGIONAL:
127                            return "FJRN";
128                    default:
129                            return ""; //Can not happen
130                    }
131            }
132            
133            public DepartureBean lookupDeparturesAzureSite(String stationcode, TrainType type, boolean arrival) throws Exception {
134                                    
135                  DepartureBean departureBean = new DepartureBean();                  DepartureBean departureBean = new DepartureBean();
136                                    
137                            
138              String typeString = getTypeString(type);              String typeString = getTypeStringAzure(type);
139              String arrivalDeparture = (arrival==false) ? "Afgang" : "Ankomst";              String arrivalDeparture = (arrival==false) ? "Afgang" : "Ankomst";
140                            
141              stationcode = URLEncoder.encode(stationcode,"ISO-8859-1");              stationcode = URLEncoder.encode(stationcode,"ISO-8859-1");
             //String uri = "http://www.bane.dk/visStation.asp?ArtikelID=4275&W=" + type + "&S=" + stationcode;  
             String uri = "http://trafikinfo.bane.dk/Trafikinformation/AfgangAnkomst/" + arrivalDeparture + "/" + stationcode + "/" + typeString + "/UdvidetVisning";  
142    
143                String uri = "http://trafikinfo.bane.dk/Trafikinformation/AfgangAnkomst/" + arrivalDeparture + "/" + stationcode + "/" + typeString + "/UdvidetVisning";        
144                            
145                            logger.fine("URI: " + uri);    
146              //logger.info("URI: " + uri);                        JsoupInvocation wrapper = new JsoupInvocation( new URL(uri), settings.getReplyTimeout() );
             JsoupInvocation wrapper = new JsoupInvocation( new URL(uri), 2500);  
147              CircuitBreaker breaker = CircuitBreakerManager.getManager().getCircuitBreaker("banedk");              CircuitBreaker breaker = CircuitBreakerManager.getManager().getCircuitBreaker("banedk");
148                            
149              Document page = (Document) breaker.invoke(wrapper);              Document page = (Document) breaker.invoke(wrapper);
# Line 128  public class DepartureFetcher { Line 154  public class DepartureFetcher {
154              if (table != null) {              if (table != null) {
155                      Elements tableRows =  table.getElementsByTag("tr");                      Elements tableRows =  table.getElementsByTag("tr");
156                                            
157                        //boolean tidsstregExists = (table.getElementsByAttributeValue("class", "Tidsstreg").size() > 0);
158                        //boolean passedTidsstreg = false;
159                        
160                      for (Element currentRow : tableRows) {                      for (Element currentRow : tableRows) {
161                          String rowClass = currentRow.attr("class");                          String rowClass = currentRow.attr("class");
162                            /*
163                            if (tidsstregExists == true && passedTidsstreg == false) {
164                                    if (currentRow.getElementsByAttributeValue("class", "Tidsstreg").size() > 0) {
165                                            passedTidsstreg = true;
166                                    } else {
167                                            continue;
168                                    }
169                            }*/
170                            
171                          if (rowClass != null && rowClass.toLowerCase().contains("station") ) {                          if (rowClass != null && rowClass.toLowerCase().contains("station") ) {
172                                    
173                                  Elements fields = currentRow.getElementsByTag("td");                                  Elements fields = currentRow.getElementsByTag("td");
174                    
175                                  DepartureEntry departure = new DepartureEntry();                                  DepartureEntry departure = new DepartureEntry();
# Line 145  public class DepartureFetcher { Line 184  public class DepartureFetcher {
184                                                                    
185                                  String trainNumber = fields.get(2).text();                                  String trainNumber = fields.get(2).text();
186                                  if (type == TrainType.STOG) //If it is S-train we need to extract the trainNumber                                  if (type == TrainType.STOG) //If it is S-train we need to extract the trainNumber
187                                          trainNumber = trainNumber + " " + extractTrainNumber(fields.get(2));                                          trainNumber = trainNumber + " " + extractTrainNumberAzure(fields.get(2));
188                                  departure.setTrainNumber(trainNumber);                                  departure.setTrainNumber(trainNumber);
189                                                                    
190                                  String destination = fields.get(3).text();                                  String destination = fields.get(3).text();
# Line 165  public class DepartureFetcher { Line 204  public class DepartureFetcher {
204                                                                    
205                                  departure.setType(typeString);                                  departure.setType(typeString);
206                                                                    
207                                  departureBean.departureEntries.add( departure );                                  departureBean.entries.add( departure );
208                          }                          }
209                      }                      }
210              } else {              } else {
# Line 190  public class DepartureFetcher { Line 229  public class DepartureFetcher {
229              return departureBean;              return departureBean;
230          }          }
231                    
232          /*          public DepartureBean lookupDeparturesMobileSite(String stationcode, TrainType traintype, boolean arrival) throws Exception {
         @Deprecated  
         public List<DepartureBean> lookupDeparturesFromTemporarySite(String stationcode, String type) throws Exception {  
233                                    
234                  List<DepartureBean> departureList = new ArrayList<DepartureBean>();                  DepartureBean departureBean = new DepartureBean();
235                                    
             final WebClient webClient = new WebClient(BrowserVersion.FIREFOX_3);  
             webClient.setTimeout(2500);  
             webClient.setJavaScriptEnabled(false);  
236                            
237                    String typeString = getTypeStringWww(traintype);
238              String uri = "http://bane.dk/lite/station.asp?w=" + type + "&s=" + stationcode;              String arrivalDeparture = (arrival==false) ? "afgang" : "ankomst";
239                            
240              HtmlunitInvocation wrapper = new HtmlunitInvocation(webClient, uri);              stationcode = URLEncoder.encode(stationcode,"ISO-8859-1");
241    
242                //String uri = "http://trafikinfo.bane.dk/Trafikinformation/AfgangAnkomst/" + arrivalDeparture + "/" + stationcode + "/" + typeString + "/UdvidetVisning";      
243                String uri = "http://mobil.bane.dk/mobilStation.asp?artikelID=5332&stat_kode=" + stationcode + "&webprofil=" + typeString  +"&beskrivelse=&mode=ankomstafgang&ankomstafgang=" + arrivalDeparture + "&gemstation=&fuldvisning=1";
244                logger.fine("URI: " + uri);    
245                JsoupInvocation wrapper = new JsoupInvocation( new URL(uri), settings.getReplyTimeout() );
246              CircuitBreaker breaker = CircuitBreakerManager.getManager().getCircuitBreaker("banedk");              CircuitBreaker breaker = CircuitBreakerManager.getManager().getCircuitBreaker("banedk");
247                            
248              HtmlPage page = (HtmlPage) breaker.invoke(wrapper);              Document page = (Document) breaker.invoke(wrapper);
249                            
             HtmlElement table = page.getElementById("traf_afgang");  
250                            
251              if (table != null) {                                      Element content = page.getElementsByClass("contentDiv").get(0);
252                      DomNodeList<HtmlElement> tableRows =  table.getElementsByTagName("tr");              
253                
254                if (content != null) {
255                        Elements tableRows =  content.child(0).children();
256                                            
257                      boolean isFirst = true;  
258                                            
259                      for (HtmlElement currentRow : tableRows) {                      for (Element currentRow : tableRows) {
260                          if (isFirst == true) { //skip table headers                          if (currentRow.tagName().equals("br") ) {
261                                  isFirst = false;                                  break;
                                 continue;  
262                          }                          }
263                                                    
264                          DomNodeList<HtmlElement> fields = currentRow.getElementsByTagName("td");                          
265                            Element link = currentRow.child(0);    
266                            System.out.println( currentRow.text() );;
267                            
268    
269                          DepartureBean departure = new DepartureBean();                          String parts[] = currentRow.text().split(",");
270                    
271    
272                          String time = fields.get(0).asText().trim();                          DepartureEntry departure = new DepartureEntry();
273    
274    /*
275    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
276    */
277                            int offset = 0;
278                            
279                            String time = parts[offset++];
280                          if (time.equals(""))                          if (time.equals(""))
281                                  time = "0:00"; //Bane.dk bug work-around                                  time = "0:00"; //Bane.dk bug work-around
282                          departure.setTime(time);                          departure.setTime(time);
283    
284                            int updated = 4; //does not exist on mobile
285                            departure.setUpdated(updated);
286    
287                          String trainNumber = fields.get(1).asText();                          String trainNumber = "-"; //extractTrainNumberAzure(fields.get(2));
288                            /*if (traintype == TrainType.STOG) //If it is S-train we need to extract the trainNumber
289                                    trainNumber = trainNumber + " " + extractTrainNumberAzure(fields.get(2));*/
290                          departure.setTrainNumber(trainNumber);                          departure.setTrainNumber(trainNumber);
291    
292                          String destination = fields.get(2).asText();                          String destination = parts[offset++];
293                          departure.setDestination(destination);                          departure.setDestination(destination);
294    
295                          String origin = fields.get(3).asText();                          String origin = "-"; // fields.get(4).text(); does not exist on mobile
296                          departure.setOrigin(origin);                          departure.setOrigin(origin);
297    
298                          String status = fields.get(4).asText();                          String location = ""; // fields.get(5).text(); does not exist on mobile
299                            departure.setLocation(location);
300    
301                            String status = ""; //fields.get(6).text().trim(); - extract from url
302                          departure.setStatus(status);                          departure.setStatus(status);
303    
304                          String note = fields.get(5).asText();                          String note = ""; //extractNote( fields.get(7) ); - extract from url
305                          departure.setNote(note);                          departure.setNote(note);
306    
307                          departureList.add(departure);                          departure.setType(typeString);
308    
309                            departureBean.entries.add( departure );
310    
311                      }                      }
312              } else {              } else {
313                  logger.warning("No departures found for station=" + stationcode + ", type=" + type);                  logger.warning("No departures found for station=" + stationcode + ", type=" + traintype);
314              }              }
             webClient.closeAllWindows();  
315                            
316                return departureBean;
317            }
318            
319            
320            
321            public static String cleanText(String input) {
322                    //apparently JSoup translates &nbsp; characters on www.bane.dk to 0xA0
323                    return input.replace((char) 0xA0, (char)0x20).trim();
324            }
325            
326            
327            // old www site is not available any more
328            @Deprecated
329            public DepartureBean lookupDeparturesWwwSite(String stationcode, TrainType trainType, boolean arrival) throws Exception {
330                    
331                    DepartureBean departureBean = new DepartureBean();
332                    
333                    String type = getTypeStringWww(trainType);
334                    
335                    stationcode = URLEncoder.encode(stationcode, "ISO-8859-1");
336                    
337                                                
338                String uri = "http://www.bane.dk/visStation.asp?ArtikelID=4275&W=" + type + "&S=" + stationcode;
339                logger.fine("URI:" + uri);
340                
341    
342                JsoupInvocation wrapper = new JsoupInvocation( new URL(uri), settings.getReplyTimeout() );
343                CircuitBreaker breaker = CircuitBreakerManager.getManager().getCircuitBreaker("banedk");
344                
345                Element page = (Element) breaker.invoke(wrapper);
346                
347                String tableName = arrival == false ? "afgangtabel" : "ankomsttabel";
348                Element table = page.getElementById(tableName);
349                            
             return departureList;  
         }*/  
350    
351                
352                if (table != null) {
353                        Elements tableRows =  table.getElementsByTag("tr");
354                        
355                        //boolean passedTidsstreg = false;
356                        //boolean tidsstregExists = (table.getElementsByAttributeValue("class", "Tidsstreg").size() > 0);
357                        
358                        for (Element currentRow : tableRows) {
359                            String rowClass = currentRow.attr("class");
360                            /*
361                            if (tidsstregExists == true && passedTidsstreg == false) {
362                                    if (currentRow.getElementsByAttributeValue("class", "Tidsstreg").size() > 0) {
363                                            passedTidsstreg = true;
364                                    } else {
365                                            continue;
366                                    }
367                            }*/
368                            
369                            
370                            if (rowClass != null && rowClass.toLowerCase().contains("station") ) {
371                                    Elements fields = currentRow.getElementsByTag("td");
372            
373                                    DepartureEntry departure = new DepartureEntry();
374                                    
375    
376                                    
377                                    String time = cleanText( fields.get(0).getAllElements().get(2).text() );
378                                    if (time.equals(""))
379                                            time = "0:00"; //Bane.dk bug work-around
380                                    departure.setTime(time);
381                                    
382                                    int updated = extractUpdated( fields.get(1) );
383                                    departure.setUpdated(updated);
384                                    
385                                    String trainNumber = cleanText( fields.get(2).text() );
386                                    if (type.equalsIgnoreCase("S2")) //If it is S-train we need to extract the trainNumber
387                                            trainNumber = trainNumber + " " + extractTrainNumberWww(fields.get(2));
388                                    departure.setTrainNumber(trainNumber);
389                                    
390                                    String destination = cleanText( fields.get(3).text() );
391                                    departure.setDestination(destination);
392                                    
393                                    String origin = cleanText( fields.get(4).text() );
394                                    departure.setOrigin(origin);
395                                    
396                                    String location = cleanText( fields.get(5).text() );
397                                    departure.setLocation(location);
398                                    
399                                    String status = cleanText( fields.get(6).text() );
400                                    departure.setStatus(status);
401                                    
402                                    String note = cleanText( extractNote( fields.get(7) ) );
403                                    departure.setNote(note);
404                                    
405                                    departure.setType(type);
406                                    
407                                    departureBean.entries.add(departure);
408                                    
409                                    
410                            }
411                        }
412                } else {
413                    logger.warning("No departures found for station=" + stationcode + ", type=" + type);
414                }
415                
416                
417                return departureBean;
418            }
419                    
420                    
421          private int extractUpdated(Element updatedTd) { //extract the digit (in this case: 4) from "media/trafikinfo/opdater4.gif"          private int extractUpdated(Element updatedTd) { //extract the digit (in this case: 4) from "media/trafikinfo/opdater4.gif"
422                  int updated = -1;                  int updated = -1;
# Line 285  public class DepartureFetcher { Line 444  public class DepartureFetcher {
444                  if (elems.size() > 0 && note.charAt(note.length()-1) == 'i')                  if (elems.size() > 0 && note.charAt(note.length()-1) == 'i')
445                          note = note.substring(0,note.length() -1 );                          note = note.substring(0,note.length() -1 );
446    
447                  return note;                  return note.trim();
448          }          }
449                    
450          private String extractTrainNumber(Element trainTd) {          private String extractTrainNumberAzure(Element trainTd) {
451                  Element anchorElement = trainTd.getElementsByTag("a").get(0);                  Element anchorElement = trainTd.getElementsByTag("a").get(0);
452                  String href = anchorElement.attr("href");                  String href = anchorElement.attr("href");
453                                    
# Line 298  public class DepartureFetcher { Line 457  public class DepartureFetcher {
457                  return number;                  return number;
458          }          }
459                    
460            private String extractTrainNumberWww(Element trainTd) {
461                    String number = "";
462                    Element anchorElement = trainTd.getElementsByTag("a").get(0);
463                    String href = anchorElement.attr("href");
464                    String argstring = href.substring( href.indexOf('?') + 1);
465                    
466                    String args[] = argstring.split("&");
467                    for (String arg : args) {
468                            String pair[] = arg.split("="); // Key=pair[0], Value=pair[1]
469                            
470                            if (pair[0].equalsIgnoreCase("TogNr"))
471                                    number = pair[1];
472                    }
473                    
474                    
475                    return number;
476            }
477    
478            
479          //test          //test
480          /*          /*
481          public static void main(String args[]) throws Exception {          public static void main(String args[]) throws Exception {

Legend:
Removed from v.994  
changed lines
  Added in v.1332

  ViewVC Help
Powered by ViewVC 1.1.20