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

  ViewVC Help
Powered by ViewVC 1.1.20