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

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

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

android/TrainInfoService/src/dk/thoerup/traininfoservice/banedk/DepartureFetcher.java revision 971 by torben, Fri Jul 9 21:46:45 2010 UTC android/TrainInfoServiceGoogle/src/dk/thoerup/traininfoservice/banedk/DepartureFetcher.java revision 1105 by torben, Wed Sep 22 21:09:39 2010 UTC
# Line 1  Line 1 
1  package dk.thoerup.traininfoservice.banedk;  package dk.thoerup.traininfoservice.banedk;
2    
3  import java.util.ArrayList;  
4    import java.net.URL;
5    import java.net.URLEncoder;
6  import java.util.Collections;  import java.util.Collections;
7  import java.util.List;  import java.util.HashMap;
8  import java.util.Map;  import java.util.Map;
9    import java.util.logging.Level;
10  import java.util.logging.Logger;  import java.util.logging.Logger;
11    
12  import com.gargoylesoftware.htmlunit.BrowserVersion;  import net.sf.jsr107cache.Cache;
13  import com.gargoylesoftware.htmlunit.WebClient;  import net.sf.jsr107cache.CacheException;
14  import com.gargoylesoftware.htmlunit.html.DomNodeList;  import net.sf.jsr107cache.CacheManager;
15  import com.gargoylesoftware.htmlunit.html.HtmlElement;  
16  import com.gargoylesoftware.htmlunit.html.HtmlPage;  import org.jsoup.nodes.Document;
17    import org.jsoup.nodes.Element;
18    import org.jsoup.select.Elements;
19    
20    import com.google.appengine.api.memcache.jsr107cache.GCacheFactory;
21    
22    import dk.thoerup.android.traininfo.common.DepartureBean;
23    import dk.thoerup.android.traininfo.common.DepartureEntry;
24    import dk.thoerup.android.traininfo.common.StationBean.StationEntry;
25  import dk.thoerup.circuitbreaker.CircuitBreaker;  import dk.thoerup.circuitbreaker.CircuitBreaker;
26  import dk.thoerup.circuitbreaker.CircuitBreakerManager;  import dk.thoerup.circuitbreaker.CircuitBreakerManager;
 import dk.thoerup.traininfoservice.StationBean;  
27  import dk.thoerup.traininfoservice.StationDAO;  import dk.thoerup.traininfoservice.StationDAO;
28  import dk.thoerup.traininfoservice.Statistics;  import dk.thoerup.traininfoservice.Statistics;
29    
30  public class DepartureFetcher {  public class DepartureFetcher {
31                    
32          Logger logger = Logger.getLogger(DepartureFetcher.class.getName());          enum TrainType{
33                    STOG,
34                    REGIONAL
35            }
36            Cache cache;
37                    
38          Map<String, List<DepartureBean>> cache;          Logger logger = Logger.getLogger(DepartureFetcher.class.getName());    
39                    
40          StationDAO stationDao = new StationDAO();          StationDAO stationDao = new StationDAO();
41                    
42          private boolean useTempSite;          private boolean useAzureSite;
43            private int replyTimeout;
44                    
45          public DepartureFetcher(boolean tempSite, int cacheTimeout) {          @SuppressWarnings("unchecked")
46                  useTempSite = tempSite;          public DepartureFetcher(boolean azureSite, int cacheTimeout, int replyTimeout) {
47                  cache = new TimeoutMap<String,List<DepartureBean>>(cacheTimeout);                  this.replyTimeout = replyTimeout;
48                    useAzureSite = azureSite;
49    
50            Map props = new HashMap();
51            props.put(GCacheFactory.EXPIRATION_DELTA_MILLIS, cacheTimeout);        
52                    
53                    try {
54                cache = CacheManager.getInstance().getCacheFactory().createCache(props);            
55            } catch (CacheException e) {
56                    logger.log(Level.WARNING, "error creating cache", e);
57            }
58    
59          }          }
60                    
61                    
62                                    
63                    
64          public List<DepartureBean> cachedLookupDepartures(int stationID, boolean arrival) throws Exception {          public DepartureBean cachedLookupDepartures(int stationID, boolean arrival) throws Exception {
65                  final String key = "" + stationID + ":" + arrival;                  final String key = "departure:" + stationID + ":" + arrival;
66                                    
67                  List<DepartureBean> list = cache.get(key);                  DepartureBean departureBean = (DepartureBean) cache.get(key);
   
68                                    
69                  if (list == null) {                  if (departureBean == null) {
70                          list = lookupDepartures(stationID,arrival);                          departureBean = lookupDepartures(stationID,arrival);
71                          cache.put(key, list);                          cache.put(key, departureBean);
72                            logger.info("Departure: Cache miss " + key + " !!! "); //remove before production
73                  } else {                  } else {
74                          Statistics.getInstance().incrementDepartureCacheHits();                          Statistics.getInstance().incrementDepartureCacheHits();
75                          logger.info("Departure: Cache hit " + key); //remove before production                          logger.info("Departure: Cache hit " + key);
76                  }                  }
77                  return list;                  
78                    return departureBean;
79          }          }
80                                    
81    
82          public List<DepartureBean> lookupDepartures(int stationID, boolean arrival) throws Exception {          public DepartureBean lookupDepartures(int stationID, boolean arrival) throws Exception {
                 List<DepartureBean> departureList = new ArrayList<DepartureBean>();  
83                                    
84                  StationBean station = stationDao.getById(stationID);                  DepartureBean departureBean = new DepartureBean();
85                    
86                    StationEntry station = stationDao.getById(stationID);
87    
88                    
89                    departureBean.stationName = station.getName();
90                                    
91                  if (station.getRegional() != null) {                  if (station.getRegional() != null) {
92                          List<DepartureBean> list = lookupDepartures(station.getRegional(), "Fjerntog", arrival);                          DepartureBean tempBean = lookupDepartures(station.getRegional(), TrainType.REGIONAL, arrival);
93                          departureList.addAll(list);                                              departureBean.entries.addAll( tempBean.entries );
94                            departureBean.notifications.addAll(tempBean.notifications);
95                  }                  }
96                                    
97                  if (station.getStrain() != null) {                  if (station.getStrain() != null) {
98                          List<DepartureBean> list = lookupDepartures(station.getStrain(), "S-Tog", arrival);                          DepartureBean tempBean = lookupDepartures(station.getStrain(), TrainType.STOG, arrival);
99                          departureList.addAll(list);                              departureBean.entries.addAll( tempBean.entries );
100                            departureBean.notifications.addAll(tempBean.notifications);
101                  }                                }              
102                                    
103                  Collections.sort( departureList );                  if (departureBean.entries.size() == 0) {
104                            logger.info("No departures found for station " + stationID);
105                    }
106                    
107                    Collections.sort( departureBean.entries );
108    
109                                    
110                  return departureList;                  return departureBean;
111          }          }
112                    
113          public List<DepartureBean> lookupDepartures(String stationcode, String type, boolean arrival) throws Exception {          public DepartureBean lookupDepartures(String stationcode, TrainType type, boolean arrival) throws Exception {
114                  if (useTempSite == false) {                  if (useAzureSite == true) {
115                          return lookupDeparturesNormalSite(stationcode, type, arrival);                          return lookupDeparturesAzureSite(stationcode, type, arrival);
116                  } else {                  } else {
117                          return lookupDeparturesFromTemporarySite(stationcode, type);                          return lookupDeparturesWwwSite(stationcode, type, arrival);
118                  }                  }
119          }          }
120                    
121          public List<DepartureBean> lookupDeparturesNormalSite(String stationcode, String type, boolean arrival) throws Exception {          private String getTypeStringAzure(TrainType type) {
122                                    switch (type) {
123                  List<DepartureBean> departureList = new ArrayList<DepartureBean>();                  case STOG:
124                            return "S-Tog";
125                    case REGIONAL:
126                            return "Fjerntog";
127                    default:
128                            return ""; //Can not happen
129                    }
130            }
131            
132            private String getTypeStringWww(TrainType type) {
133                    switch (type) {
134                    case STOG:
135                            return "S2";
136                    case REGIONAL:
137                            return "FJRN";
138                    default:
139                            return ""; //Can not happen
140                    }
141            }
142            
143            public DepartureBean lookupDeparturesAzureSite(String stationcode, TrainType type, boolean arrival) throws Exception {
144                                    
145              final WebClient webClient = new WebClient( BrowserVersion.FIREFOX_3 );                  DepartureBean departureBean = new DepartureBean();
146              webClient.setTimeout(2500);                  
             webClient.setJavaScriptEnabled(false);  
147                            
148                String typeString = getTypeStringAzure(type);
149              String arrivalDeparture = (arrival==false) ? "Afgang" : "Ankomst";              String arrivalDeparture = (arrival==false) ? "Afgang" : "Ankomst";
150                                            
151              //String uri = "http://www.bane.dk/visStation.asp?ArtikelID=4275&W=" + type + "&S=" + stationcode;              stationcode = URLEncoder.encode(stationcode,"ISO-8859-1");
             String uri = "http://trafikinfo.bane.dk/Trafikinformation/AfgangAnkomst/" + arrivalDeparture + "/" + stationcode + "/" +type + "/UdvidetVisning";  
152    
153              //logger.info("URI: " + uri);              String uri = "http://trafikinfo.bane.dk/Trafikinformation/AfgangAnkomst/" + arrivalDeparture + "/" + stationcode + "/" + typeString + "/UdvidetVisning";        
154              HtmlunitInvocation wrapper = new HtmlunitInvocation(webClient, uri);              
155                logger.fine("URI: " + uri);    
156                JsoupInvocation wrapper = new JsoupInvocation( new URL(uri), replyTimeout);
157              CircuitBreaker breaker = CircuitBreakerManager.getManager().getCircuitBreaker("banedk");              CircuitBreaker breaker = CircuitBreakerManager.getManager().getCircuitBreaker("banedk");
158                            
159              HtmlPage page = (HtmlPage) breaker.invoke(wrapper);              Document page = (Document) breaker.invoke(wrapper);
160                            
161              String tableName = arrival == false ? "afgangtabel" : "ankomsttabel";              String tableName = arrival == false ? "afgangtabel" : "ankomsttabel";
162              HtmlElement table = page.getElementById(tableName);              Element table = page.getElementById(tableName);
163                            
164              if (table != null) {              if (table != null) {
165                      DomNodeList<HtmlElement> tableRows =  table.getElementsByTagName("tr");                      Elements tableRows =  table.getElementsByTag("tr");
166                                            
167                      for (HtmlElement currentRow : tableRows) {                      boolean tidsstregExists = (table.getElementsByAttributeValue("class", "Tidsstreg").size() > 0);
168                          String rowClass = currentRow.getAttribute("class");                      boolean passedTidsstreg = false;
169                        
170                        for (Element currentRow : tableRows) {
171                            String rowClass = currentRow.attr("class");
172                            
173                            if (tidsstregExists == true && passedTidsstreg == false) {
174                                    if (currentRow.getElementsByAttributeValue("class", "Tidsstreg").size() > 0) {
175                                            passedTidsstreg = true;
176                                    } else {
177                                            continue;
178                                    }
179                            }
180                            
181                          if (rowClass != null && rowClass.toLowerCase().contains("station") ) {                          if (rowClass != null && rowClass.toLowerCase().contains("station") ) {
182                                  DomNodeList<HtmlElement> fields = currentRow.getElementsByTagName("td");                                  
183                                    Elements fields = currentRow.getElementsByTag("td");
184                    
185                                  DepartureBean departure = new DepartureBean();                                  DepartureEntry departure = new DepartureEntry();
186                                                                    
187                                  String time = fields.get(0).asText();                                  String time = fields.get(0).text();
188                                  if (time.equals(""))                                  if (time.equals(""))
189                                          time = "0:00"; //Bane.dk bug work-around                                          time = "0:00"; //Bane.dk bug work-around
190                                  departure.setTime(time);                                  departure.setTime(time);
# Line 122  public class DepartureFetcher { Line 192  public class DepartureFetcher {
192                                  int updated = extractUpdated( fields.get(1) );                                  int updated = extractUpdated( fields.get(1) );
193                                  departure.setUpdated(updated);                                  departure.setUpdated(updated);
194                                                                    
195                                  String trainNumber = fields.get(2).asText();                                  String trainNumber = fields.get(2).text();
196                                  if (type.equalsIgnoreCase("S-Tog")) //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
197                                          trainNumber = trainNumber + " " + extractTrainNumber(fields.get(2));                                          trainNumber = trainNumber + " " + extractTrainNumberAzure(fields.get(2));
198                                  departure.setTrainNumber(trainNumber);                                  departure.setTrainNumber(trainNumber);
199                                                                    
200                                  String destination = fields.get(3).asText();                                  String destination = fields.get(3).text();
201                                  departure.setDestination(destination);                                  departure.setDestination(destination);
202                                                                    
203                                  String origin = fields.get(4).asText();                                  String origin = fields.get(4).text();
204                                  departure.setOrigin(origin);                                  departure.setOrigin(origin);
205                                                                    
206                                  String location = fields.get(5).asText();                                  String location = fields.get(5).text();
207                                  departure.setLocation(location);                                  departure.setLocation(location);
208                                                                    
209                                  String status = fields.get(6).asText().trim();                                  String status = fields.get(6).text().trim();
210                                  departure.setStatus(status);                                  departure.setStatus(status);
211                                                                    
212                                  String note = extractNote( fields.get(7) );                                  String note = extractNote( fields.get(7) );
213                                  departure.setNote(note);                                  departure.setNote(note);
214                                                                    
215                                  departure.setType(type);                                  departure.setType(typeString);
216                                                                    
217                                  departureList.add(departure);                                  departureBean.entries.add( departure );
218                          }                          }
219                      }                      }
220              } else {              } else {
221                  logger.warning("No departures found for station=" + stationcode + ", type=" + type);                  logger.warning("No departures found for station=" + stationcode + ", type=" + type);
222              }              }
             webClient.closeAllWindows();  
223                            
224              return departureList;              Element notifDiv = page.getElementById("station_planlagte_text");
225                if (notifDiv != null) {
226    
227                    Elements tables = notifDiv.getElementsByTag("table");
228                    for (Element tab : tables) {
229    
230                            Elements anchors = tab.getElementsByTag("a");          
231                            if (anchors.size() == 2) {
232                                    departureBean.notifications.add(  anchors.get(1).text() );
233                            }
234                    }
235                    
236                }
237                
238                
239                return departureBean;
240            }
241            
242            
243            
244            public static String cleanText(String input) {
245                    //apparently JSoup translates &nbsp; characters on www.bane.dk to 0xA0
246                    return input.replace((char) 0xA0, (char)0x20).trim();
247          }          }
248                    
249          public List<DepartureBean> lookupDeparturesFromTemporarySite(String stationcode, String type) throws Exception {          public DepartureBean lookupDeparturesWwwSite(String stationcode, TrainType trainType, boolean arrival) throws Exception {
250                                    
251                  List<DepartureBean> departureList = new ArrayList<DepartureBean>();                  DepartureBean departureBean = new DepartureBean();
252                                    
253              final WebClient webClient = new WebClient(BrowserVersion.FIREFOX_3);                  String type = getTypeStringWww(trainType);
254              webClient.setTimeout(2500);                  
255              webClient.setJavaScriptEnabled(false);                  stationcode = URLEncoder.encode(stationcode, "ISO-8859-1");
256                    
257                                                
258                String uri = "http://www.bane.dk/visStation.asp?ArtikelID=4275&W=" + type + "&S=" + stationcode;
259                logger.fine("URI:" + uri);
260                            
261    
262              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);  
263              CircuitBreaker breaker = CircuitBreakerManager.getManager().getCircuitBreaker("banedk");              CircuitBreaker breaker = CircuitBreakerManager.getManager().getCircuitBreaker("banedk");
264                            
265              HtmlPage page = (HtmlPage) breaker.invoke(wrapper);              Element page = (Element) breaker.invoke(wrapper);
266                            
267              HtmlElement table = page.getElementById("traf_afgang");              String tableName = arrival == false ? "afgangtabel" : "ankomsttabel";
268                Element table = page.getElementById(tableName);
269                
270    
271                            
272              if (table != null) {                                      if (table != null) {
273                      DomNodeList<HtmlElement> tableRows =  table.getElementsByTagName("tr");                      Elements tableRows =  table.getElementsByTag("tr");
274                                            
275                      boolean isFirst = true;                      boolean passedTidsstreg = false;
276                        boolean tidsstregExists = (table.getElementsByAttributeValue("class", "Tidsstreg").size() > 0);
277                                            
278                      for (HtmlElement currentRow : tableRows) {                      for (Element currentRow : tableRows) {
279                          if (isFirst == true) { //skip table headers                          String rowClass = currentRow.attr("class");
280                                  isFirst = false;                          
281                                  continue;                          if (tidsstregExists == true && passedTidsstreg == false) {
282                                    if (currentRow.getElementsByAttributeValue("class", "Tidsstreg").size() > 0) {
283                                            passedTidsstreg = true;
284                                    } else {
285                                            continue;
286                                    }
287                          }                          }
288                                                    
289                          DomNodeList<HtmlElement> fields = currentRow.getElementsByTagName("td");                          
290                            if (rowClass != null && rowClass.toLowerCase().contains("station") ) {
291                          DepartureBean departure = new DepartureBean();                                  Elements fields = currentRow.getElementsByTag("td");
292            
293                          String time = fields.get(0).asText().trim();                                  DepartureEntry departure = new DepartureEntry();
294                                    
                         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);  
295    
296                          departureList.add(departure);                                  
297                                    String time = cleanText( fields.get(0).getAllElements().get(2).text() );
298                                    if (time.equals(""))
299                                            time = "0:00"; //Bane.dk bug work-around
300                                    departure.setTime(time);
301                                    
302                                    int updated = extractUpdated( fields.get(1) );
303                                    departure.setUpdated(updated);
304                                    
305                                    String trainNumber = cleanText( fields.get(2).text() );
306                                    if (type.equalsIgnoreCase("S2")) //If it is S-train we need to extract the trainNumber
307                                            trainNumber = trainNumber + " " + extractTrainNumberWww(fields.get(2));
308                                    departure.setTrainNumber(trainNumber);
309                                    
310                                    String destination = cleanText( fields.get(3).text() );
311                                    departure.setDestination(destination);
312                                    
313                                    String origin = cleanText( fields.get(4).text() );
314                                    departure.setOrigin(origin);
315                                    
316                                    String location = cleanText( fields.get(5).text() );
317                                    departure.setLocation(location);
318                                    
319                                    String status = cleanText( fields.get(6).text() );
320                                    departure.setStatus(status);
321                                    
322                                    String note = cleanText( extractNote( fields.get(7) ) );
323                                    departure.setNote(note);
324                                    
325                                    departure.setType(type);
326                                    
327                                    departureBean.entries.add(departure);
328                                    
329                                    
330                            }
331                      }                      }
332              } else {              } else {
333                  logger.warning("No departures found for station=" + stationcode + ", type=" + type);                  logger.warning("No departures found for station=" + stationcode + ", type=" + type);
334              }              }
             webClient.closeAllWindows();  
335                            
336                            
337              return departureList;              return departureBean;
338          }          }
339                    
340                    
341          private int extractUpdated(HtmlElement 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"
342                  int updated = -1;                  int updated = -1;
343                                    
344                  DomNodeList<HtmlElement> updatedImgs = updatedTd.getElementsByTagName("img");                  Elements updatedImgs = updatedTd.getElementsByTag("img");
345                  String updatedStr = updatedImgs.get(0).getAttribute("src");                  String updatedStr = updatedImgs.get(0).attr("src");
346                                    
347                  if (updatedStr != null) {                  if (updatedStr != null) {
348                          for (int i=0; i<updatedStr.length(); i++) {                          for (int i=0; i<updatedStr.length(); i++) {
# Line 240  public class DepartureFetcher { Line 356  public class DepartureFetcher {
356                  return updated;                  return updated;
357          }          }
358                    
359          private String extractNote(HtmlElement noteTd) {          private String extractNote(Element noteTd) {
360                  String note = noteTd.asText().trim();                  String note = noteTd.text().trim();
361                    
362                                    
363                  List<HtmlElement> elems = noteTd.getElementsByAttribute("span", "class", "bemtype");                  Elements elems = noteTd.getElementsByClass("bemtype");
364                  if (elems.size() > 0 && note.charAt(note.length()-1) == 'i')                  if (elems.size() > 0 && note.charAt(note.length()-1) == 'i')
365                          note = note.substring(0,note.length() -1 );                          note = note.substring(0,note.length() -1 );
366    
367                  return note;                  return note.trim();
368          }          }
369                    
370          private String extractTrainNumber(HtmlElement trainTd) {          private String extractTrainNumberAzure(Element trainTd) {
371                    Element anchorElement = trainTd.getElementsByTag("a").get(0);
372                    String href = anchorElement.attr("href");
373                    
374                    int pos = href.lastIndexOf('/');
375                    String number = href.substring(pos+1);
376                    
377                    return number;
378            }
379            
380            private String extractTrainNumberWww(Element trainTd) {
381                  String number = "";                  String number = "";
382                  HtmlElement anchorElement = trainTd.getElementsByTagName("a").get(0);                  Element anchorElement = trainTd.getElementsByTag("a").get(0);
383                  String href = anchorElement.getAttribute("href");                  String href = anchorElement.attr("href");
384                  String argstring = href.substring( href.indexOf('?') + 1);                  String argstring = href.substring( href.indexOf('?') + 1);
385                                    
386                  String args[] = argstring.split("/");                  String args[] = argstring.split("&");
387                  number = args[args.length-1];                  for (String arg : args) {
                   
                 /*for (String arg : args) {  
388                          String pair[] = arg.split("="); // Key=pair[0], Value=pair[1]                          String pair[] = arg.split("="); // Key=pair[0], Value=pair[1]
389                                                    
390                          if (pair[0].equalsIgnoreCase("TogNr"))                          if (pair[0].equalsIgnoreCase("TogNr"))
391                                  number = pair[1];                                  number = pair[1];
392                  }*/                  }
393                                    
394                                    
395                  return number;                  return number;
396          }          }
397    
398                    
399          //test          //test
400          /*          /*

Legend:
Removed from v.971  
changed lines
  Added in v.1105

  ViewVC Help
Powered by ViewVC 1.1.20