/[projects]/android/TrainInfoService/src/dk/thoerup/traininfoservice/banedk/TimetableFetcher.java
ViewVC logotype

Diff of /android/TrainInfoService/src/dk/thoerup/traininfoservice/banedk/TimetableFetcher.java

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

revision 976 by torben, Sat Jul 10 09:10:50 2010 UTC revision 1417 by torben, Mon May 2 16:21:37 2011 UTC
# Line 1  Line 1 
1  package dk.thoerup.traininfoservice.banedk;  package dk.thoerup.traininfoservice.banedk;
2    
3    
4  import java.io.IOException;  
5  import java.net.URL;  import java.net.URL;
6  import java.sql.SQLException;  import java.sql.SQLException;
 import java.util.ArrayList;  
 import java.util.List;  
7  import java.util.Map;  import java.util.Map;
8  import java.util.logging.Level;  import java.util.logging.Level;
9  import java.util.logging.Logger;  import java.util.logging.Logger;
10    
11  import com.gargoylesoftware.htmlunit.BrowserVersion;  import org.jsoup.nodes.Document;
12  import com.gargoylesoftware.htmlunit.Page;  import org.jsoup.nodes.Element;
13  import com.gargoylesoftware.htmlunit.RefreshHandler;  import org.jsoup.select.Elements;
 import com.gargoylesoftware.htmlunit.WebClient;  
 import com.gargoylesoftware.htmlunit.html.DomNodeList;  
 import com.gargoylesoftware.htmlunit.html.HtmlElement;  
 import com.gargoylesoftware.htmlunit.html.HtmlPage;  
14    
15    import dk.thoerup.android.traininfo.common.StationBean;
16    import dk.thoerup.android.traininfo.common.StationEntry;
17    import dk.thoerup.android.traininfo.common.TimetableBean;
18    import dk.thoerup.android.traininfo.common.TimetableEntry;
19  import dk.thoerup.circuitbreaker.CircuitBreaker;  import dk.thoerup.circuitbreaker.CircuitBreaker;
20  import dk.thoerup.circuitbreaker.CircuitBreakerManager;  import dk.thoerup.circuitbreaker.CircuitBreakerManager;
21  import dk.thoerup.traininfoservice.StationDAO;  import dk.thoerup.genericjavautils.TimeoutMap;
22  import dk.thoerup.traininfoservice.Statistics;  import dk.thoerup.traininfoservice.Statistics;
23    import dk.thoerup.traininfoservice.TraininfoSettings;
24    import dk.thoerup.traininfoservice.db.StationDAO;
25    
26  public class TimetableFetcher {  public class TimetableFetcher {
27            
         class NullRefreshHandler implements RefreshHandler {  
                 public void handleRefresh(Page arg0, URL arg1, int arg2) throws IOException {                    
                 }  
                   
         }  
28                                    
29          Map<String, List<TimetableBean>> cache;          Map<String, TimetableBean> cache;
30          Map<String, Integer> stationCache;          Map<String, StationEntry> stationCache;
31    
32          StationDAO stationDao = new StationDAO();          StationDAO stationDao = new StationDAO();
33                    
34                    
35          Logger logger = Logger.getLogger(TimetableFetcher.class.getName());          Logger logger = Logger.getLogger(TimetableFetcher.class.getName());
36    
37            TraininfoSettings settings;    
38                    
39          private boolean useTempSite;          public TimetableFetcher(TraininfoSettings settings) {
40                            this.settings = settings;
         public TimetableFetcher(boolean tmpSite, int cacheTimeout) {  
                 useTempSite = tmpSite;  
41                                    
42                  cache = new TimeoutMap<String,List<TimetableBean>>(cacheTimeout);                  cache = new TimeoutMap<String,TimetableBean>( settings.getCacheTimeout() );
43                  stationCache = new TimeoutMap<String,Integer>( 3*60*60*1000 );                  stationCache = new TimeoutMap<String,StationEntry>( 3*60*60*1000 );
44          }          }
45                    
46                    
47          List<TimetableBean> cachedLookupTimetable(String trainID, String type) throws Exception {          TimetableBean cachedLookupTimetable(String trainID, String type) throws Exception {
48                  String key = trainID+type;                  String key = trainID+type;
49                  List<TimetableBean> list = cache.get(key);                  TimetableBean list = cache.get(key);
50                                    
51                  if (list == null) {                  if (list == null) {
52                          list = lookupTimetable(trainID,type);                          list = lookupTimetable(trainID,type);
# Line 63  public class TimetableFetcher { Line 58  public class TimetableFetcher {
58                  return list;                  return list;
59          }          }
60                    
61          List<TimetableBean> lookupTimetable(String trainID, String type) throws Exception {          TimetableBean lookupTimetable(String trainID, String type) throws Exception {
62                  if (useTempSite == false ){                  if (settings.getBackend() == TraininfoSettings.Backend.Azure ){
63                          return lookupTimetableRealSite(trainID, type);                          return lookupTimetableAzureSite(trainID, type);
64                            
65                  } else {                  } else {
66                          return new ArrayList<TimetableBean>(); // no timetable data on temp site                          return lookupTimetableMobileSite(trainID, type);
67                  }                  }
68          }          }
69                    
70          int getStationId(String name) {          StationEntry getStation(String name) {
71                  Integer id = stationCache.get(name);                  StationEntry station = stationCache.get(name);
72                                    
73                  if (id == null) {                  if (station == null) {
74                          try {                          try {
75                                  id = stationDao.getIdByName(name);                                  station = stationDao.getSimpleByName(name);
76                                  stationCache.put(name, id);                                  if (station != null) {
77                                            stationCache.put(name,station);
78                                    }
79                          } catch (SQLException e) {                          } catch (SQLException e) {
80                                  logger.log(Level.SEVERE, "getStationId failed", e);                                  logger.log(Level.SEVERE, "getStationId failed", e);
                                 id = -1;  
81                          }                          }
82                  }                  }
83    
84                  return id;                  return station;
85            }
86            
87            String correctStationName(String name) {
88                    if (name.equals("København"))
89                            name = "København H"; //correct inconsistency in naming
90                    
91                    return name;            
92          }          }
93    
94          List<TimetableBean> lookupTimetableRealSite(String trainID, String type) throws Exception {                      TimetableBean lookupTimetableAzureSite(String trainID, String type) throws Exception {          
95                  List<TimetableBean> timetableList = new ArrayList<TimetableBean>();                  TimetableBean timetableBean = new TimetableBean();
96                                    
                 //String url = "http://www.bane.dk/visRute.asp?W=" + type + "&TogNr=" + trainID + "&artikelId=4276";  
                 String url = "http://trafikinfo.bane.dk/TrafikInformation/Ruteplan/" + trainID;                  
97    
98              final WebClient webClient = new WebClient(BrowserVersion.FIREFOX_3);                  String url = "http://trafikinfo.bane.dk/TrafikInformation/Ruteplan/" + trainID;                
99              webClient.setTimeout(2500);                  logger.fine("URL:" + url);
             webClient.setJavaScriptEnabled(false);          
             webClient.setRefreshHandler( new NullRefreshHandler() );  
             webClient.setCssEnabled(false);  
               
100                            
101              HtmlunitInvocation wrapper = new HtmlunitInvocation(webClient, url);              JsoupInvocation wrapper = new JsoupInvocation( new URL(url) , settings.getReplyTimeout() );
102              CircuitBreaker breaker = CircuitBreakerManager.getManager().getCircuitBreaker("banedk");              CircuitBreaker breaker = CircuitBreakerManager.getManager().getCircuitBreaker("banedk");
103                            
104              HtmlPage page = (HtmlPage) breaker.invoke(wrapper);              Document doc = (Document) breaker.invoke(wrapper);
105                                            
106                            
107              boolean currentStation = false;              boolean currentStation = false;
108              boolean currentStationSaved = false;              boolean currentStationSaved = false;
109                            
110              List<HtmlElement> tables = page.getDocumentElement().getElementsByAttribute("table", "class", "Rute");              Elements tables = doc.getElementsByClass("Rute");
111                
112              if (tables.size() == 1) {              if (tables.size() == 1) {
113                  HtmlElement timetable = tables.get(0);                  Element timetable = tables.get(0);
114                  DomNodeList<HtmlElement> rows = timetable.getElementsByTagName("tr");                  Elements rows = timetable.getElementsByTag("tr");
115                                    
116                  for (int i=0; i<rows.size(); i++) {                  for (int i=0; i<rows.size(); i++) {
117                          if (i==0) //First row is column headers                          if (i==0) //First row is column headers
118                                  continue;                                  continue;
119                                                    
120                                                    
121                          HtmlElement row = rows.get(i);                          Element row = rows.get(i);
122                          DomNodeList<HtmlElement> fields = row.getElementsByTagName("td");                          Elements fields = row.getElementsByTag("td");
123    
124                                                    
125                          if (currentStationSaved == false && fields.get(0).getAttribute("class").equalsIgnoreCase("Tidsstreg")) {                          if (currentStationSaved == false && fields.get(0).attr("class").equalsIgnoreCase("Tidsstreg")) {
126                                  currentStation = true;                                  currentStation = true;
127                                  continue;                                  continue;
128                          }                          }
129                                                    
130                          TimetableBean bean = new TimetableBean();                          TimetableEntry entry = new TimetableEntry();
131                                                    
132                          String station = fields.get(0).asText() ;                          String station = correctStationName( fields.get(0).text() );
                         if (station.equals("København"))  
                                 station = "København H"; //correct inconsistency in naming  
                           
                         bean.setStation( station );  
                         bean.setArrival( fields.get(1).asText() );  
                         bean.setDeparture( fields.get(2).asText() );  
133                                                    
134                          boolean cancelled = fields.get(3).asText().equalsIgnoreCase("aflyst");                          entry.setStation( station );
135                          bean.setCancelled(cancelled);                          entry.setArrival( fields.get(1).text() );
136                            entry.setDeparture( fields.get(2).text() );
137                            
138                            boolean cancelled = fields.get(3).text().equalsIgnoreCase("aflyst");
139                            entry.setCancelled(cancelled);
140                                                    
141                          if (currentStation == true && currentStationSaved == false ) {                          if (currentStation == true && currentStationSaved == false ) {
142                                  bean.setCurrent(currentStation);                                  entry.setCurrent(currentStation);
143                                  currentStationSaved = true;                                  currentStationSaved = true;
144                          }                          }
145                                                    
146                          bean.setStationId( getStationId( station ));                          entry.setStationEntry( getStation( station ));
147                                                    
148                          timetableList.add(bean);                          timetableBean.entries.add(entry);
149                  }                  }
150                                    
151                    //TODO: There is an off-by-one error in this cancelled parser thingie
152                  final String cancelledString = "Aflyst";                  final String cancelledString = "Aflyst";
153                  for (int i=0;i<timetableList.size(); i++) { //handle cancelled labels                  for (int i=0;i<timetableBean.entries.size(); i++) { //handle cancelled labels
154                          final int lastIdx = (timetableList.size() - 1);                          final int lastIdx = (timetableBean.entries.size() - 1);
155                                                    
156                          TimetableBean current = timetableList.get(i);                          TimetableEntry current = timetableBean.entries.get(i);
157                          if (current.isCancelled()) {                          if (current.isCancelled()) {
158                                  if (i == 0) {                                  if (i == 0) {
159                                          current.setDeparture(cancelledString);                                          current.setDeparture(cancelledString);
160                                  } else if (i == lastIdx) {                                  } else if (i == lastIdx) {
161                                          current.setArrival(cancelledString);                                          current.setArrival(cancelledString);
162                                  } else if (i>0 && i<lastIdx) {                                  } else if (i>0 && i<lastIdx) {
163                                          TimetableBean next = timetableList.get(i+1);                                          TimetableEntry next = timetableBean.entries.get(i+1);
164                                          TimetableBean prev = timetableList.get(i-1);                                          TimetableEntry prev = timetableBean.entries.get(i-1);
165                                                                                    
166                                          if (next.isCancelled())                                          if (next.isCancelled())
167                                                  current.setDeparture(cancelledString);                                                  current.setDeparture(cancelledString);
# Line 175  public class TimetableFetcher { Line 174  public class TimetableFetcher {
174              } else {              } else {
175                  logger.warning("No time table found, trainID=" + trainID + " type=" + type);                  logger.warning("No time table found, trainID=" + trainID + " type=" + type);
176              }              }
177              webClient.closeAllWindows();              
178                    
179                    return timetableBean;
180            }
181    
182            TimetableBean lookupTimetableMobileSite(String trainID, String type) throws Exception {
183                    TimetableBean timetableBean = new TimetableBean();
184                                    
185                  return timetableList;                  String url = "http://mobil.bane.dk/mobilStation.asp?artikelID=5332&tognummer=" + trainID + "&webprofil=" + type + "&mode=rute";
186                    logger.fine("URL:" + url);
187    
188                
189                JsoupInvocation wrapper = new JsoupInvocation( new URL(url) , settings.getReplyTimeout() );
190                CircuitBreaker breaker = CircuitBreakerManager.getManager().getCircuitBreaker("banedk");
191                
192                Document doc = (Document) breaker.invoke(wrapper);
193    
194                Element content = doc.getElementsByClass("contentDiv").get(1);
195                Element dlist = content.child(0);
196    
197                
198                Elements rows = dlist.getElementsByTag("dt");
199    
200                for (int i=0; i<rows.size(); i++) {
201    
202                    Element row = rows.get(i);
203                    
204                    logger.fine( row.text() );
205                    
206                    String parts[] = row.text().split(",");
207                    
208                    TimetableEntry entry = new TimetableEntry();
209    
210                    String station = DepartureFetcher.cleanText( parts[0] ) ;
211                    station = correctStationName(station);
212    
213    
214                    String arrival = DepartureFetcher.cleanText( parts[1] );
215                    String departure = DepartureFetcher.cleanText( "" );
216    
217                    entry.setStation( station );
218                    entry.setArrival( arrival );
219                    entry.setDeparture( departure );
220    
221    
222                    entry.setStationEntry( getStation( station ));
223    
224                    timetableBean.entries.add(entry);
225                }          
226    
227    
228                return timetableBean;
229    
230          }          }
231                    
232            @Deprecated
233            TimetableBean lookupTimetableWwwSite(String trainID, String type) throws Exception {            
234                    TimetableBean timetableBean = new TimetableBean();
235                    
236                    String url = "http://www.bane.dk/visRute.asp?W=" + type + "&TogNr=" + trainID + "&artikelId=4276";
237                    logger.fine("URL:" + url);
238    
239                
240                JsoupInvocation wrapper = new JsoupInvocation( new URL(url) , settings.getReplyTimeout() );
241                CircuitBreaker breaker = CircuitBreakerManager.getManager().getCircuitBreaker("banedk");
242                
243                Document doc = (Document) breaker.invoke(wrapper);
244                        
245                
246                boolean currentStation = false;
247                boolean currentStationSaved = false;
248                
249                Elements tables = doc.getElementsByClass("Rute");
250                
251                if (tables.size() == 1) {
252                    Element timetable = tables.get(0);
253                    Elements rows = timetable.getElementsByTag("tr");
254                    
255                    for (int i=0; i<rows.size(); i++) {
256                            if (i==0) //First row is column headers
257                                    continue;
258                            
259                            
260                            Element row = rows.get(i);
261                            Elements fields = row.getElementsByTag("td");
262    
263                            
264                            if (currentStationSaved == false && fields.get(0).attr("class").equalsIgnoreCase("Tidsstreg")) {
265                                    currentStation = true;
266                                    continue;
267                            }
268                            
269                            TimetableEntry entry = new TimetableEntry();
270                            
271                            String station = DepartureFetcher.cleanText( fields.get(0).text() ) ;
272                            station = correctStationName(station);
273    
274                            
275                            String arrival = DepartureFetcher.cleanText( fields.get(1).text() );
276                            String departure = DepartureFetcher.cleanText( fields.get(2).text() );
277                            
278                            entry.setStation( station );
279                            entry.setArrival( arrival );
280                            entry.setDeparture( departure );
281                    
282                            
283                            if (currentStation == true && currentStationSaved == false ) {
284                                    entry.setCurrent(currentStation);
285                                    currentStationSaved = true;
286                            }
287                            
288                            entry.setStationEntry( getStation( station ));
289                            
290                            timetableBean.entries.add(entry);
291                    }              
292                    
293                } else {
294                    logger.warning("No time table found, trainID=" + trainID + " type=" + type);
295                }
296                
297                    
298                    return timetableBean;
299            }      
300            
301  }  }

Legend:
Removed from v.976  
changed lines
  Added in v.1417

  ViewVC Help
Powered by ViewVC 1.1.20