/[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 350 by torben, Mon Sep 28 21:33:24 2009 UTC revision 1355 by torben, Wed Apr 20 19:01:33 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.util.ArrayList;  import java.sql.SQLException;
7  import java.util.List;  import java.util.Map;
8    import java.util.logging.Level;
9  import java.util.logging.Logger;  import java.util.logging.Logger;
10    
11  import com.gargoylesoftware.htmlunit.*;  import org.jsoup.nodes.Document;
12  import com.gargoylesoftware.htmlunit.html.*;  import org.jsoup.nodes.Element;
13    import org.jsoup.select.Elements;
14    
15    import dk.thoerup.android.traininfo.common.TimetableBean;
16    import dk.thoerup.android.traininfo.common.TimetableEntry;
17    import dk.thoerup.circuitbreaker.CircuitBreaker;
18    import dk.thoerup.circuitbreaker.CircuitBreakerManager;
19    import dk.thoerup.genericjavautils.TimeoutMap;
20    import dk.thoerup.traininfoservice.Statistics;
21    import dk.thoerup.traininfoservice.TraininfoSettings;
22    import dk.thoerup.traininfoservice.db.StationDAO;
23    
24  public class TimetableFetcher {  public class TimetableFetcher {
25    
26                    
27            Map<String, TimetableBean> cache;
28            Map<String, Integer> stationCache;
29    
30            StationDAO stationDao = new StationDAO();
31                    
32          class NullRefreshHandler implements RefreshHandler {          
33                  public void handleRefresh(Page arg0, URL arg1, int arg2) throws IOException {                            Logger logger = Logger.getLogger(TimetableFetcher.class.getName());
34                  }  
35            TraininfoSettings settings;    
36            
37            public TimetableFetcher(TraininfoSettings settings) {
38                    this.settings = settings;
39                                    
40                    cache = new TimeoutMap<String,TimetableBean>( settings.getCacheTimeout() );
41                    stationCache = new TimeoutMap<String,Integer>( 3*60*60*1000 );
42          }          }
43                    
44          Logger logger = Logger.getLogger(TimetableFetcher.class.getName());          
45            TimetableBean cachedLookupTimetable(String trainID, String type) throws Exception {
46                    String key = trainID+type;
47                    TimetableBean list = cache.get(key);
48                    
49                    if (list == null) {
50                            list = lookupTimetable(trainID,type);
51                            cache.put(key, list);
52                    } else {
53                            Statistics.getInstance().incrementTimetableCacheHits();
54                            logger.info("Timetable: Cache hit " + trainID);
55                    }
56                    return list;
57            }
58            
59            TimetableBean lookupTimetable(String trainID, String type) throws Exception {
60                    if (settings.getUseAzureSite() == true ){
61                            return lookupTimetableAzureSite(trainID, type);
62                            
63                    } else {
64                            return lookupTimetableMobileSite(trainID, type);
65                    }
66            }
67            
68            int getStationId(String name) {
69                    Integer id = stationCache.get(name);
70                    
71                    if (id == null) {
72                            try {
73                                    id = stationDao.getIdByName(name);
74                                    stationCache.put(name, id);
75                            } catch (SQLException e) {
76                                    logger.log(Level.SEVERE, "getStationId failed", e);
77                                    id = -1;
78                            }
79                    }
80    
81                    return id;
82            }
83    
84          List<TimetableBean> lookupTimetable(String trainID, String type) throws Exception {          TimetableBean lookupTimetableAzureSite(String trainID, String type) throws Exception {          
85                  List<TimetableBean> timetableList = new ArrayList<TimetableBean>();                  TimetableBean timetableBean = new TimetableBean();
86                                    
                 String url = "http://www.bane.dk/visRute.asp?W=" + type + "&TogNr=" + trainID + "&artikelId=4276";  
                                   
                 logger.warning(url);  
87    
88              final WebClient webClient = new WebClient();                  String url = "http://trafikinfo.bane.dk/TrafikInformation/Ruteplan/" + trainID;                
89              webClient.setTimeout(1000);                  logger.fine("URL:" + url);
             webClient.setJavaScriptEnabled(false);          
             webClient.setRefreshHandler( new NullRefreshHandler() );  
             webClient.setCssEnabled(false);  
               
90                            
91              final HtmlPage page = webClient.getPage(url);              JsoupInvocation wrapper = new JsoupInvocation( new URL(url) , settings.getReplyTimeout() );
92                CircuitBreaker breaker = CircuitBreakerManager.getManager().getCircuitBreaker("banedk");
93                            
94                Document doc = (Document) breaker.invoke(wrapper);
95                        
96                            
97              boolean currentStation = false;              boolean currentStation = false;
98              boolean currentStationSaved = false;              boolean currentStationSaved = false;
99                            
100              List<HtmlElement> tables = page.getDocumentElement().getElementsByAttribute("table", "class", "Rute");              Elements tables = doc.getElementsByClass("Rute");
101                
102              if (tables.size() == 1) {              if (tables.size() == 1) {
103                  HtmlElement timetable = tables.get(0);                  Element timetable = tables.get(0);
104                  DomNodeList<HtmlElement> rows = timetable.getElementsByTagName("tr");                  Elements rows = timetable.getElementsByTag("tr");
105                                    
106                  for (int i=0; i<rows.size(); i++) {                  for (int i=0; i<rows.size(); i++) {
107                          if (i==0) //First row is column headers                          if (i==0) //First row is column headers
108                                  continue;                                  continue;
109                                                    
110                                                    
111                          HtmlElement row = rows.get(i);                          Element row = rows.get(i);
112                          DomNodeList<HtmlElement> fields = row.getElementsByTagName("td");                          Elements fields = row.getElementsByTag("td");
113    
114                                                    
115                          if (currentStationSaved == false && fields.get(0).getAttribute("class").equalsIgnoreCase("Tidsstreg")) {                          if (currentStationSaved == false && fields.get(0).attr("class").equalsIgnoreCase("Tidsstreg")) {
116                                  currentStation = true;                                  currentStation = true;
117                                  continue;                                  continue;
118                          }                          }
119                                                    
120                          TimetableBean bean = new TimetableBean();                          TimetableEntry entry = new TimetableEntry();
121                          bean.setStation( fields.get(0).asText() );                          
122                          bean.setArrival( fields.get(1).asText() );                          String station = fields.get(0).text() ;
123                          bean.setDeparture( fields.get(2).asText() );                          if (station.equals("København"))
124                                    station = "København H"; //correct inconsistency in naming
125                            
126                            entry.setStation( station );
127                            entry.setArrival( fields.get(1).text() );
128                            entry.setDeparture( fields.get(2).text() );
129                            
130                            boolean cancelled = fields.get(3).text().equalsIgnoreCase("aflyst");
131                            entry.setCancelled(cancelled);
132                                                    
133                          if (currentStation == true && currentStationSaved == false ) {                          if (currentStation == true && currentStationSaved == false ) {
134                                  bean.setCurrent(currentStation);                                  entry.setCurrent(currentStation);
135                                  currentStationSaved = true;                                  currentStationSaved = true;
136                          }                          }
137                                                    
138                          timetableList.add(bean);                          entry.setStationId( getStationId( station ));
139                            
140                            timetableBean.entries.add(entry);
141                    }
142                    
143                    //TODO: There is an off-by-one error in this cancelled parser thingie
144                    final String cancelledString = "Aflyst";
145                    for (int i=0;i<timetableBean.entries.size(); i++) { //handle cancelled labels
146                            final int lastIdx = (timetableBean.entries.size() - 1);
147                            
148                            TimetableEntry current = timetableBean.entries.get(i);
149                            if (current.isCancelled()) {
150                                    if (i == 0) {
151                                            current.setDeparture(cancelledString);
152                                    } else if (i == lastIdx) {
153                                            current.setArrival(cancelledString);
154                                    } else if (i>0 && i<lastIdx) {
155                                            TimetableEntry next = timetableBean.entries.get(i+1);
156                                            TimetableEntry prev = timetableBean.entries.get(i-1);
157                                            
158                                            if (next.isCancelled())
159                                                    current.setDeparture(cancelledString);
160                                            if (prev.isCancelled())
161                                                    current.setArrival(cancelledString);
162                                    }
163                            }
164                  }                  }
165                                    
166              } else {              } else {
167                  logger.warning("No time table found, trainID=" + trainID + " type=" + type);                  logger.warning("No time table found, trainID=" + trainID + " type=" + type);
168              }              }
169                
170                                    
171                  return timetableList;                  return timetableBean;
172            }
173    
174            TimetableBean lookupTimetableMobileSite(String trainID, String type) throws Exception {
175                    return new TimetableBean(); //dummy skeleton method
176          }          }
177                    
178            @Deprecated
179            TimetableBean lookupTimetableWwwSite(String trainID, String type) throws Exception {            
180                    TimetableBean timetableBean = new TimetableBean();
181                    
182                    String url = "http://www.bane.dk/visRute.asp?W=" + type + "&TogNr=" + trainID + "&artikelId=4276";
183                    logger.fine("URL:" + url);
184    
185                
186                JsoupInvocation wrapper = new JsoupInvocation( new URL(url) , settings.getReplyTimeout() );
187                CircuitBreaker breaker = CircuitBreakerManager.getManager().getCircuitBreaker("banedk");
188                
189                Document doc = (Document) breaker.invoke(wrapper);
190                        
191                
192                boolean currentStation = false;
193                boolean currentStationSaved = false;
194                
195                Elements tables = doc.getElementsByClass("Rute");
196                
197                if (tables.size() == 1) {
198                    Element timetable = tables.get(0);
199                    Elements rows = timetable.getElementsByTag("tr");
200                    
201                    for (int i=0; i<rows.size(); i++) {
202                            if (i==0) //First row is column headers
203                                    continue;
204                            
205                            
206                            Element row = rows.get(i);
207                            Elements fields = row.getElementsByTag("td");
208    
209                            
210                            if (currentStationSaved == false && fields.get(0).attr("class").equalsIgnoreCase("Tidsstreg")) {
211                                    currentStation = true;
212                                    continue;
213                            }
214                            
215                            TimetableEntry entry = new TimetableEntry();
216                            
217                            String station = DepartureFetcher.cleanText( fields.get(0).text() ) ;
218                            if (station.equals("København"))
219                                    station = "København H"; //correct inconsistency in naming
220                            
221                            String arrival = DepartureFetcher.cleanText( fields.get(1).text() );
222                            String departure = DepartureFetcher.cleanText( fields.get(2).text() );
223                            
224                            entry.setStation( station );
225                            entry.setArrival( arrival );
226                            entry.setDeparture( departure );
227                    
228                            
229                            if (currentStation == true && currentStationSaved == false ) {
230                                    entry.setCurrent(currentStation);
231                                    currentStationSaved = true;
232                            }
233                            
234                            entry.setStationId( getStationId( station ));
235                            
236                            timetableBean.entries.add(entry);
237                    }              
238                    
239                } else {
240                    logger.warning("No time table found, trainID=" + trainID + " type=" + type);
241                }
242                
243                    
244                    return timetableBean;
245            }      
246            
247  }  }

Legend:
Removed from v.350  
changed lines
  Added in v.1355

  ViewVC Help
Powered by ViewVC 1.1.20