/[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 1038 by torben, Sun Sep 12 18:41:17 2010 UTC android/TrainInfoServiceGoogle/src/dk/thoerup/traininfoservice/banedk/DepartureFetcher.java revision 1105 by torben, Wed Sep 22 21:09:39 2010 UTC
# Line 4  package dk.thoerup.traininfoservice.bane Line 4  package dk.thoerup.traininfoservice.bane
4  import java.net.URL;  import java.net.URL;
5  import java.net.URLEncoder;  import java.net.URLEncoder;
6  import java.util.Collections;  import java.util.Collections;
7    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 net.sf.jsr107cache.Cache;
13    import net.sf.jsr107cache.CacheException;
14    import net.sf.jsr107cache.CacheManager;
15    
16  import org.jsoup.nodes.Document;  import org.jsoup.nodes.Document;
17  import org.jsoup.nodes.Element;  import org.jsoup.nodes.Element;
18  import org.jsoup.select.Elements;  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    
# Line 23  public class DepartureFetcher { Line 33  public class DepartureFetcher {
33                  STOG,                  STOG,
34                  REGIONAL                  REGIONAL
35          }          }
36            Cache cache;
37                    
38          Logger logger = Logger.getLogger(DepartureFetcher.class.getName());          Logger logger = Logger.getLogger(DepartureFetcher.class.getName());    
           
         Map<String, DepartureBean> cache;  
39                    
40          StationDAO stationDao = new StationDAO();          StationDAO stationDao = new StationDAO();
41                    
42          private boolean useAzureSite;          private boolean useAzureSite;
43          private int replyTimeout;          private int replyTimeout;
44                    
45            @SuppressWarnings("unchecked")
46          public DepartureFetcher(boolean azureSite, int cacheTimeout, int replyTimeout) {          public DepartureFetcher(boolean azureSite, int cacheTimeout, int replyTimeout) {
47                  this.replyTimeout = replyTimeout;                  this.replyTimeout = replyTimeout;
48                  useAzureSite = azureSite;                  useAzureSite = azureSite;
49                  cache = new TimeoutMap<String,DepartureBean>(cacheTimeout);  
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 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                  DepartureBean departureBean = cache.get(key);                  DepartureBean departureBean = (DepartureBean) cache.get(key);
   
68                                    
69                  if (departureBean == null) {                  if (departureBean == null) {
70                          departureBean = lookupDepartures(stationID,arrival);                          departureBean = lookupDepartures(stationID,arrival);
71                          cache.put(key, departureBean);                          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                    
78                  return departureBean;                  return departureBean;
79          }          }
80                                    
# Line 63  public class DepartureFetcher { Line 83  public class DepartureFetcher {
83                                    
84                  DepartureBean departureBean = new DepartureBean();                  DepartureBean departureBean = new DepartureBean();
85                                    
86                  StationBean station = stationDao.getById(stationID);                  StationEntry station = stationDao.getById(stationID);
87    
88                                    
89                  departureBean.stationName = station.getName();                  departureBean.stationName = station.getName();
90                                    
91                  if (station.getRegional() != null) {                  if (station.getRegional() != null) {
92                          DepartureBean tempBean = lookupDepartures(station.getRegional(), TrainType.REGIONAL, arrival);                          DepartureBean tempBean = lookupDepartures(station.getRegional(), TrainType.REGIONAL, arrival);
93                          departureBean.departureEntries.addAll( tempBean.departureEntries );                          departureBean.entries.addAll( tempBean.entries );
94                          departureBean.notifications.addAll(tempBean.notifications);                          departureBean.notifications.addAll(tempBean.notifications);
95                  }                  }
96                                    
97                  if (station.getStrain() != null) {                  if (station.getStrain() != null) {
98                          DepartureBean tempBean = lookupDepartures(station.getStrain(), TrainType.STOG, arrival);                          DepartureBean tempBean = lookupDepartures(station.getStrain(), TrainType.STOG, arrival);
99                          departureBean.departureEntries.addAll( tempBean.departureEntries );                          departureBean.entries.addAll( tempBean.entries );
100                          departureBean.notifications.addAll(tempBean.notifications);                          departureBean.notifications.addAll(tempBean.notifications);
101                  }                                }              
102                                    
103                  if (departureBean.departureEntries.size() == 0) {                  if (departureBean.entries.size() == 0) {
104                          logger.info("No departures found for station " + stationID);                          logger.info("No departures found for station " + stationID);
105                  }                  }
106                                    
107                  Collections.sort( departureBean.departureEntries );                  Collections.sort( departureBean.entries );
108    
109                                    
110                  return departureBean;                  return departureBean;
# Line 131  public class DepartureFetcher { Line 152  public class DepartureFetcher {
152    
153              String uri = "http://trafikinfo.bane.dk/Trafikinformation/AfgangAnkomst/" + arrivalDeparture + "/" + stationcode + "/" + typeString + "/UdvidetVisning";                      String uri = "http://trafikinfo.bane.dk/Trafikinformation/AfgangAnkomst/" + arrivalDeparture + "/" + stationcode + "/" + typeString + "/UdvidetVisning";        
154                            
155              //logger.info("URI: " + uri);                        logger.fine("URI: " + uri);    
156              JsoupInvocation wrapper = new JsoupInvocation( new URL(uri), replyTimeout);              JsoupInvocation wrapper = new JsoupInvocation( new URL(uri), replyTimeout);
157              CircuitBreaker breaker = CircuitBreakerManager.getManager().getCircuitBreaker("banedk");              CircuitBreaker breaker = CircuitBreakerManager.getManager().getCircuitBreaker("banedk");
158                            
# Line 173  public class DepartureFetcher { Line 194  public class DepartureFetcher {
194                                                                    
195                                  String trainNumber = fields.get(2).text();                                  String trainNumber = fields.get(2).text();
196                                  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
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).text();                                  String destination = fields.get(3).text();
# Line 193  public class DepartureFetcher { Line 214  public class DepartureFetcher {
214                                                                    
215                                  departure.setType(typeString);                                  departure.setType(typeString);
216                                                                    
217                                  departureBean.departureEntries.add( departure );                                  departureBean.entries.add( departure );
218                          }                          }
219                      }                      }
220              } else {              } else {
# Line 220  public class DepartureFetcher { Line 241  public class DepartureFetcher {
241                    
242                    
243                    
244          String cleanText(String input) {          public static String cleanText(String input) {
245                  //apparently JSoup interprets some of space characters on www.bane.dk as 0xA0                  //apparently JSoup translates &nbsp; characters on www.bane.dk to 0xA0
246                  return input.replace((char) 0xA0, (char)0x20).trim();                  return input.replace((char) 0xA0, (char)0x20).trim();
247          }          }
248                    
# Line 231  public class DepartureFetcher { Line 252  public class DepartureFetcher {
252                                    
253                  String type = getTypeStringWww(trainType);                  String type = getTypeStringWww(trainType);
254                                    
255                    stationcode = URLEncoder.encode(stationcode, "ISO-8859-1");
256                    
257                                                                                            
258              String uri = "http://www.bane.dk/visStation.asp?ArtikelID=4275&W=" + type + "&S=" + stationcode;              String uri = "http://www.bane.dk/visStation.asp?ArtikelID=4275&W=" + type + "&S=" + stationcode;
259                logger.fine("URI:" + uri);
260                
261    
262              JsoupInvocation wrapper = new JsoupInvocation( new URL(uri), replyTimeout);              JsoupInvocation wrapper = new JsoupInvocation( new URL(uri), replyTimeout);
263              CircuitBreaker breaker = CircuitBreakerManager.getManager().getCircuitBreaker("banedk");              CircuitBreaker breaker = CircuitBreakerManager.getManager().getCircuitBreaker("banedk");
264                            
# Line 241  public class DepartureFetcher { Line 267  public class DepartureFetcher {
267              String tableName = arrival == false ? "afgangtabel" : "ankomsttabel";              String tableName = arrival == false ? "afgangtabel" : "ankomsttabel";
268              Element table = page.getElementById(tableName);              Element table = page.getElementById(tableName);
269                            
270    
271                
272              if (table != null) {              if (table != null) {
273                      Elements tableRows =  table.getElementsByTag("tr");                      Elements tableRows =  table.getElementsByTag("tr");
274                                            
275                        boolean passedTidsstreg = false;
276                        boolean tidsstregExists = (table.getElementsByAttributeValue("class", "Tidsstreg").size() > 0);
277                        
278                      for (Element currentRow : tableRows) {                      for (Element currentRow : tableRows) {
279                          String rowClass = currentRow.attr("class");                          String rowClass = currentRow.attr("class");
280                            
281                            if (tidsstregExists == true && passedTidsstreg == false) {
282                                    if (currentRow.getElementsByAttributeValue("class", "Tidsstreg").size() > 0) {
283                                            passedTidsstreg = true;
284                                    } else {
285                                            continue;
286                                    }
287                            }
288                            
289                            
290                          if (rowClass != null && rowClass.toLowerCase().contains("station") ) {                          if (rowClass != null && rowClass.toLowerCase().contains("station") ) {
291                                  Elements fields = currentRow.getElementsByTag("td");                                  Elements fields = currentRow.getElementsByTag("td");
292                    
# Line 263  public class DepartureFetcher { Line 304  public class DepartureFetcher {
304                                                                    
305                                  String trainNumber = cleanText( fields.get(2).text() );                                  String trainNumber = cleanText( fields.get(2).text() );
306                                  if (type.equalsIgnoreCase("S2")) //If it is S-train we need to extract the trainNumber                                  if (type.equalsIgnoreCase("S2")) //If it is S-train we need to extract the trainNumber
307                                          trainNumber = trainNumber + " " + extractTrainNumber(fields.get(2));                                          trainNumber = trainNumber + " " + extractTrainNumberWww(fields.get(2));
308                                  departure.setTrainNumber(trainNumber);                                  departure.setTrainNumber(trainNumber);
309                                                                    
310                                  String destination = cleanText( fields.get(3).text() );                                  String destination = cleanText( fields.get(3).text() );
# Line 283  public class DepartureFetcher { Line 324  public class DepartureFetcher {
324                                                                    
325                                  departure.setType(type);                                  departure.setType(type);
326                                                                    
327                                  departureBean.departureEntries.add(departure);                                  departureBean.entries.add(departure);
328                                                                    
329                                                                    
330                          }                          }
# Line 326  public class DepartureFetcher { Line 367  public class DepartureFetcher {
367                  return note.trim();                  return note.trim();
368          }          }
369                    
370          private String extractTrainNumber(Element trainTd) {          private String extractTrainNumberAzure(Element trainTd) {
371                  Element anchorElement = trainTd.getElementsByTag("a").get(0);                  Element anchorElement = trainTd.getElementsByTag("a").get(0);
372                  String href = anchorElement.attr("href");                  String href = anchorElement.attr("href");
373                                    
# Line 336  public class DepartureFetcher { Line 377  public class DepartureFetcher {
377                  return number;                  return number;
378          }          }
379                    
380            private String extractTrainNumberWww(Element trainTd) {
381                    String number = "";
382                    Element anchorElement = trainTd.getElementsByTag("a").get(0);
383                    String href = anchorElement.attr("href");
384                    String argstring = href.substring( href.indexOf('?') + 1);
385                    
386                    String args[] = argstring.split("&");
387                    for (String arg : args) {
388                            String pair[] = arg.split("="); // Key=pair[0], Value=pair[1]
389                            
390                            if (pair[0].equalsIgnoreCase("TogNr"))
391                                    number = pair[1];
392                    }
393                    
394                    
395                    return number;
396            }
397    
398            
399          //test          //test
400          /*          /*
401          public static void main(String args[]) throws Exception {          public static void main(String args[]) throws Exception {

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

  ViewVC Help
Powered by ViewVC 1.1.20