/[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 1021 by torben, Mon Aug 30 13:59:54 2010 UTC revision 1060 by torben, Thu Sep 16 13:32:10 2010 UTC
# Line 13  import org.jsoup.select.Elements; Line 13  import org.jsoup.select.Elements;
13    
14  import dk.thoerup.circuitbreaker.CircuitBreaker;  import dk.thoerup.circuitbreaker.CircuitBreaker;
15  import dk.thoerup.circuitbreaker.CircuitBreakerManager;  import dk.thoerup.circuitbreaker.CircuitBreakerManager;
 import dk.thoerup.traininfoservice.StationBean;  
16  import dk.thoerup.traininfoservice.StationDAO;  import dk.thoerup.traininfoservice.StationDAO;
17  import dk.thoerup.traininfoservice.Statistics;  import dk.thoerup.traininfoservice.Statistics;
18    import dk.thoerup.traininfoservice.StationBean.StationEntry;
19    
20  public class DepartureFetcher {  public class DepartureFetcher {
21                    
# Line 30  public class DepartureFetcher { Line 30  public class DepartureFetcher {
30                    
31          StationDAO stationDao = new StationDAO();          StationDAO stationDao = new StationDAO();
32                    
33          private boolean useTempSite;          private boolean useAzureSite;
34            private int replyTimeout;
35                    
36          public DepartureFetcher(boolean tempSite, int cacheTimeout) {          public DepartureFetcher(boolean azureSite, int cacheTimeout, int replyTimeout) {
37                  useTempSite = tempSite;                  this.replyTimeout = replyTimeout;
38                    useAzureSite = azureSite;
39                  cache = new TimeoutMap<String,DepartureBean>(cacheTimeout);                  cache = new TimeoutMap<String,DepartureBean>(cacheTimeout);
40          }          }
41                    
# Line 61  public class DepartureFetcher { Line 63  public class DepartureFetcher {
63                                    
64                  DepartureBean departureBean = new DepartureBean();                  DepartureBean departureBean = new DepartureBean();
65                                    
66                  StationBean station = stationDao.getById(stationID);                  StationEntry station = stationDao.getById(stationID);
67                                    
68                  departureBean.stationName = station.getName();                  departureBean.stationName = station.getName();
69                                    
# Line 77  public class DepartureFetcher { Line 79  public class DepartureFetcher {
79                          departureBean.notifications.addAll(tempBean.notifications);                          departureBean.notifications.addAll(tempBean.notifications);
80                  }                                }              
81                                    
82                    if (departureBean.departureEntries.size() == 0) {
83                            logger.info("No departures found for station " + stationID);
84                    }
85                    
86                  Collections.sort( departureBean.departureEntries );                  Collections.sort( departureBean.departureEntries );
87    
88                                    
# Line 84  public class DepartureFetcher { Line 90  public class DepartureFetcher {
90          }          }
91                    
92          public DepartureBean lookupDepartures(String stationcode, TrainType type, boolean arrival) throws Exception {          public DepartureBean lookupDepartures(String stationcode, TrainType type, boolean arrival) throws Exception {
93                  if (useTempSite == false) {                  if (useAzureSite == true) {
94                          return lookupDeparturesNormalSite(stationcode, type, arrival);                          return lookupDeparturesAzureSite(stationcode, type, arrival);
95                  } else {                  } else {
96                          //return lookupDeparturesFromTemporarySite(stationcode, type);                          return lookupDeparturesWwwSite(stationcode, type, arrival);
                         //TODO: find out what to to if they ever put a temp site up on trafikinfo.bane.dk  
                         return null;  
97                  }                  }
98          }          }
99                    
100          private String getTypeString(TrainType type) {          private String getTypeStringAzure(TrainType type) {
101                  switch (type) {                  switch (type) {
102                  case STOG:                  case STOG:
103                          return "S-Tog";                          return "S-Tog";
# Line 104  public class DepartureFetcher { Line 108  public class DepartureFetcher {
108                  }                  }
109          }          }
110                    
111          public DepartureBean lookupDeparturesNormalSite(String stationcode, TrainType type, boolean arrival) throws Exception {          private String getTypeStringWww(TrainType type) {
112                    switch (type) {
113                    case STOG:
114                            return "S2";
115                    case REGIONAL:
116                            return "FJRN";
117                    default:
118                            return ""; //Can not happen
119                    }
120            }
121            
122            public DepartureBean lookupDeparturesAzureSite(String stationcode, TrainType type, boolean arrival) throws Exception {
123                                    
124                  DepartureBean departureBean = new DepartureBean();                  DepartureBean departureBean = new DepartureBean();
125                                    
126                            
127              String typeString = getTypeString(type);              String typeString = getTypeStringAzure(type);
128              String arrivalDeparture = (arrival==false) ? "Afgang" : "Ankomst";              String arrivalDeparture = (arrival==false) ? "Afgang" : "Ankomst";
129                            
130              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";  
131    
132                String uri = "http://trafikinfo.bane.dk/Trafikinformation/AfgangAnkomst/" + arrivalDeparture + "/" + stationcode + "/" + typeString + "/UdvidetVisning";        
133                            
134                            logger.fine("URI: " + uri);    
135              //logger.info("URI: " + uri);                        JsoupInvocation wrapper = new JsoupInvocation( new URL(uri), replyTimeout);
             JsoupInvocation wrapper = new JsoupInvocation( new URL(uri), 2500);  
136              CircuitBreaker breaker = CircuitBreakerManager.getManager().getCircuitBreaker("banedk");              CircuitBreaker breaker = CircuitBreakerManager.getManager().getCircuitBreaker("banedk");
137                            
138              Document page = (Document) breaker.invoke(wrapper);              Document page = (Document) breaker.invoke(wrapper);
# Line 160  public class DepartureFetcher { Line 173  public class DepartureFetcher {
173                                                                    
174                                  String trainNumber = fields.get(2).text();                                  String trainNumber = fields.get(2).text();
175                                  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
176                                          trainNumber = trainNumber + " " + extractTrainNumber(fields.get(2));                                          trainNumber = trainNumber + " " + extractTrainNumberAzure(fields.get(2));
177                                  departure.setTrainNumber(trainNumber);                                  departure.setTrainNumber(trainNumber);
178                                                                    
179                                  String destination = fields.get(3).text();                                  String destination = fields.get(3).text();
# Line 205  public class DepartureFetcher { Line 218  public class DepartureFetcher {
218              return departureBean;              return departureBean;
219          }          }
220                    
221          /*          
222          @Deprecated          
223          public List<DepartureBean> lookupDeparturesFromTemporarySite(String stationcode, String type) throws Exception {          public static String cleanText(String input) {
224                    //apparently JSoup translates &nbsp; characters on www.bane.dk to 0xA0
225                    return input.replace((char) 0xA0, (char)0x20).trim();
226            }
227            
228            public DepartureBean lookupDeparturesWwwSite(String stationcode, TrainType trainType, boolean arrival) throws Exception {
229                                    
230                  List<DepartureBean> departureList = new ArrayList<DepartureBean>();                  DepartureBean departureBean = new DepartureBean();
231                                    
232              final WebClient webClient = new WebClient(BrowserVersion.FIREFOX_3);                  String type = getTypeStringWww(trainType);
233              webClient.setTimeout(2500);                  
234              webClient.setJavaScriptEnabled(false);                  stationcode = URLEncoder.encode(stationcode, "ISO-8859-1");
235                    
236                                                
237                String uri = "http://www.bane.dk/visStation.asp?ArtikelID=4275&W=" + type + "&S=" + stationcode;
238                logger.fine("URI:" + uri);
239                            
240    
241              String uri = "http://bane.dk/lite/station.asp?w=" + type + "&s=" + stationcode;              JsoupInvocation wrapper = new JsoupInvocation( new URL(uri), replyTimeout);
               
             HtmlunitInvocation wrapper = new HtmlunitInvocation(webClient, uri);  
242              CircuitBreaker breaker = CircuitBreakerManager.getManager().getCircuitBreaker("banedk");              CircuitBreaker breaker = CircuitBreakerManager.getManager().getCircuitBreaker("banedk");
243                            
244              HtmlPage page = (HtmlPage) breaker.invoke(wrapper);              Element page = (Element) breaker.invoke(wrapper);
245                            
246              HtmlElement table = page.getElementById("traf_afgang");              String tableName = arrival == false ? "afgangtabel" : "ankomsttabel";
247                Element table = page.getElementById(tableName);
248                            
249              if (table != null) {                          
250                      DomNodeList<HtmlElement> tableRows =  table.getElementsByTagName("tr");              
251                if (table != null) {
252                        Elements tableRows =  table.getElementsByTag("tr");
253                                            
254                      boolean isFirst = true;                      boolean passedTidsstreg = false;
255                        boolean tidsstregExists = (table.getElementsByAttributeValue("class", "Tidsstreg").size() > 0);
256                                            
257                      for (HtmlElement currentRow : tableRows) {                      for (Element currentRow : tableRows) {
258                          if (isFirst == true) { //skip table headers                          String rowClass = currentRow.attr("class");
259                                  isFirst = false;                          
260                                  continue;                          if (tidsstregExists == true && passedTidsstreg == false) {
261                                    if (currentRow.getElementsByAttributeValue("class", "Tidsstreg").size() > 0) {
262                                            passedTidsstreg = true;
263                                    } else {
264                                            continue;
265                                    }
266                          }                          }
267                                                    
268                          DomNodeList<HtmlElement> fields = currentRow.getElementsByTagName("td");                          
269                            if (rowClass != null && rowClass.toLowerCase().contains("station") ) {
270                          DepartureBean departure = new DepartureBean();                                  Elements fields = currentRow.getElementsByTag("td");
271            
272                          String time = fields.get(0).asText().trim();                                  DepartureEntry departure = new DepartureEntry();
273                                    
                         if (time.equals(""))  
                                 time = "0:00"; //Bane.dk bug work-around  
                         departure.setTime(time);  
   
   
                         String trainNumber = fields.get(1).asText();  
                         departure.setTrainNumber(trainNumber);  
   
                         String destination = fields.get(2).asText();  
                         departure.setDestination(destination);  
   
                         String origin = fields.get(3).asText();  
                         departure.setOrigin(origin);  
   
                         String status = fields.get(4).asText();  
                         departure.setStatus(status);  
   
                         String note = fields.get(5).asText();  
                         departure.setNote(note);  
274    
275                          departureList.add(departure);                                  
276                                    String time = cleanText( fields.get(0).getAllElements().get(2).text() );
277                                    if (time.equals(""))
278                                            time = "0:00"; //Bane.dk bug work-around
279                                    departure.setTime(time);
280                                    
281                                    int updated = extractUpdated( fields.get(1) );
282                                    departure.setUpdated(updated);
283                                    
284                                    String trainNumber = cleanText( fields.get(2).text() );
285                                    if (type.equalsIgnoreCase("S2")) //If it is S-train we need to extract the trainNumber
286                                            trainNumber = trainNumber + " " + extractTrainNumberWww(fields.get(2));
287                                    departure.setTrainNumber(trainNumber);
288                                    
289                                    String destination = cleanText( fields.get(3).text() );
290                                    departure.setDestination(destination);
291                                    
292                                    String origin = cleanText( fields.get(4).text() );
293                                    departure.setOrigin(origin);
294                                    
295                                    String location = cleanText( fields.get(5).text() );
296                                    departure.setLocation(location);
297                                    
298                                    String status = cleanText( fields.get(6).text() );
299                                    departure.setStatus(status);
300                                    
301                                    String note = cleanText( extractNote( fields.get(7) ) );
302                                    departure.setNote(note);
303                                    
304                                    departure.setType(type);
305                                    
306                                    departureBean.departureEntries.add(departure);
307                                    
308                                    
309                            }
310                      }                      }
311              } else {              } else {
312                  logger.warning("No departures found for station=" + stationcode + ", type=" + type);                  logger.warning("No departures found for station=" + stationcode + ", type=" + type);
313              }              }
             webClient.closeAllWindows();  
314                            
315                            
316              return departureList;              return departureBean;
317          }*/          }
318                    
319                    
320          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"
321                  int updated = -1;                  int updated = -1;
# Line 300  public class DepartureFetcher { Line 343  public class DepartureFetcher {
343                  if (elems.size() > 0 && note.charAt(note.length()-1) == 'i')                  if (elems.size() > 0 && note.charAt(note.length()-1) == 'i')
344                          note = note.substring(0,note.length() -1 );                          note = note.substring(0,note.length() -1 );
345    
346                  return note;                  return note.trim();
347          }          }
348                    
349          private String extractTrainNumber(Element trainTd) {          private String extractTrainNumberAzure(Element trainTd) {
350                  Element anchorElement = trainTd.getElementsByTag("a").get(0);                  Element anchorElement = trainTd.getElementsByTag("a").get(0);
351                  String href = anchorElement.attr("href");                  String href = anchorElement.attr("href");
352                                    
# Line 313  public class DepartureFetcher { Line 356  public class DepartureFetcher {
356                  return number;                  return number;
357          }          }
358                    
359            private String extractTrainNumberWww(Element trainTd) {
360                    String number = "";
361                    Element anchorElement = trainTd.getElementsByTag("a").get(0);
362                    String href = anchorElement.attr("href");
363                    String argstring = href.substring( href.indexOf('?') + 1);
364                    
365                    String args[] = argstring.split("&");
366                    for (String arg : args) {
367                            String pair[] = arg.split("="); // Key=pair[0], Value=pair[1]
368                            
369                            if (pair[0].equalsIgnoreCase("TogNr"))
370                                    number = pair[1];
371                    }
372                    
373                    
374                    return number;
375            }
376    
377            
378          //test          //test
379          /*          /*
380          public static void main(String args[]) throws Exception {          public static void main(String args[]) throws Exception {

Legend:
Removed from v.1021  
changed lines
  Added in v.1060

  ViewVC Help
Powered by ViewVC 1.1.20