/[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 308 by torben, Thu Sep 10 18:13:52 2009 UTC revision 994 by torben, Wed Jul 14 19:22:23 2010 UTC
# Line 1  Line 1 
1  package dk.thoerup.traininfoservice.banedk;  package dk.thoerup.traininfoservice.banedk;
2    
3  import java.sql.Connection;  
4  import java.sql.ResultSet;  import java.net.URL;
5  import java.sql.Statement;  import java.net.URLEncoder;
 import java.util.ArrayList;  
6  import java.util.Collections;  import java.util.Collections;
7  import java.util.List;  import java.util.Map;
8    import java.util.logging.Logger;
9    
10  import com.gargoylesoftware.htmlunit.WebClient;  import org.jsoup.nodes.Document;
11  import com.gargoylesoftware.htmlunit.html.DomNodeList;  import org.jsoup.nodes.Element;
12  import com.gargoylesoftware.htmlunit.html.HtmlElement;  import org.jsoup.select.Elements;
 import com.gargoylesoftware.htmlunit.html.HtmlPage;  
13    
14  import dk.thoerup.traininfoservice.DBConnection;  import dk.thoerup.circuitbreaker.CircuitBreaker;
15    import dk.thoerup.circuitbreaker.CircuitBreakerManager;
16    import dk.thoerup.traininfoservice.StationBean;
17    import dk.thoerup.traininfoservice.StationDAO;
18    import dk.thoerup.traininfoservice.Statistics;
19    
20  public class DepartureFetcher {  public class DepartureFetcher {
21            
22            enum TrainType{
23                    STOG,
24                    REGIONAL
25            }
26            
27            Logger logger = Logger.getLogger(DepartureFetcher.class.getName());
28            
29            Map<String, DepartureBean> cache;
30            
31            StationDAO stationDao = new StationDAO();
32            
33            private boolean useTempSite;
34            
35            public DepartureFetcher(boolean tempSite, int cacheTimeout) {
36                    useTempSite = tempSite;
37                    cache = new TimeoutMap<String,DepartureBean>(cacheTimeout);
38            }
39            
40            
41                                    
42            
43            public DepartureBean cachedLookupDepartures(int stationID, boolean arrival) throws Exception {
44                    final String key = "" + stationID + ":" + arrival;
45                    
46                    DepartureBean departureBean = cache.get(key);
47    
         public List<DepartureBean> lookupDepartures(int stationID) throws Exception {  
                 List<DepartureBean> departureList = new ArrayList<DepartureBean>();  
48                                    
49                  Connection conn = null;                  if (departureBean == null) {
50                  try                          departureBean = lookupDepartures(stationID,arrival);
51                  {                          cache.put(key, departureBean);
52                          conn = DBConnection.getConnection();                  } else {
53                                            Statistics.getInstance().incrementDepartureCacheHits();
54                          String SQL = "SELECT stationcode_fjrn, stationcode_stog FROM trainstations WHERE id=" + stationID;                          logger.info("Departure: Cache hit " + key); //remove before production
                         Statement stmt = conn.createStatement();  
                         ResultSet rs = stmt.executeQuery(SQL);  
                           
                         if (rs.next()) {  
                                 String code = rs.getString( 1 );  
                                 if (! rs.wasNull() ) {  
                                         List<DepartureBean> list = lookupDepartures(code, "FJRN");  
                                         departureList.addAll(list);  
                                 }  
                                   
                                 code = rs.getString(2);  
                                 if (! rs.wasNull() ) {  
                                         List<DepartureBean> list = lookupDepartures(code, "S2");  
                                         departureList.addAll(list);      
                                 }  
                                 Collections.sort( departureList );  
                           
                         }  
                           
                 } finally {  
                         if (conn != null && !conn.isClosed() ) {  
                                 conn.close();  
                         }  
55                  }                  }
56                    return departureBean;
57            }
58                    
59    
60            public DepartureBean lookupDepartures(int stationID, boolean arrival) throws Exception {
61                    
62                    DepartureBean departureBean = new DepartureBean();
63                                    
64                  return departureList;                  StationBean station = stationDao.getById(stationID);
65                    
66                    if (station.getRegional() != null) {
67                            DepartureBean tempBean = lookupDepartures(station.getRegional(), TrainType.REGIONAL, arrival);
68                            departureBean.departureEntries.addAll( tempBean.departureEntries );
69                            departureBean.notifications.addAll(tempBean.notifications);
70                    }
71                    
72                    if (station.getStrain() != null) {
73                            DepartureBean tempBean = lookupDepartures(station.getStrain(), TrainType.STOG, arrival);
74                            departureBean.departureEntries.addAll( tempBean.departureEntries );
75                            departureBean.notifications.addAll(tempBean.notifications);
76                    }              
77                    
78                    Collections.sort( departureBean.departureEntries );
79    
80                    
81                    return departureBean;
82          }          }
83                    
84          public List<DepartureBean> lookupDepartures(String stationcode, String type) throws Exception {          public DepartureBean lookupDepartures(String stationcode, TrainType type, boolean arrival) throws Exception {
85                    if (useTempSite == false) {
86                            return lookupDeparturesNormalSite(stationcode, type, arrival);
87                    } else {
88                            //return lookupDeparturesFromTemporarySite(stationcode, type);
89                            //TODO: find out what to to if they ever put a temp site up on trafikinfo.bane.dk
90                            return null;
91                    }
92            }
93            
94            private String getTypeString(TrainType type) {
95                    switch (type) {
96                    case STOG:
97                            return "S-Tog";
98                    case REGIONAL:
99                            return "Fjerntog";
100                    default:
101                            return ""; //Can not happen
102                    }
103            }
104            
105            public DepartureBean lookupDeparturesNormalSite(String stationcode, TrainType type, boolean arrival) throws Exception {
106                    
107                    DepartureBean departureBean = new DepartureBean();
108                    
109                
110                String typeString = getTypeString(type);
111                String arrivalDeparture = (arrival==false) ? "Afgang" : "Ankomst";
112                
113                stationcode = URLEncoder.encode(stationcode,"ISO-8859-1");
114                //String uri = "http://www.bane.dk/visStation.asp?ArtikelID=4275&W=" + type + "&S=" + stationcode;
115                String uri = "http://trafikinfo.bane.dk/Trafikinformation/AfgangAnkomst/" + arrivalDeparture + "/" + stationcode + "/" + typeString + "/UdvidetVisning";
116    
117                
118                
119                //logger.info("URI: " + uri);          
120                JsoupInvocation wrapper = new JsoupInvocation( new URL(uri), 2500);
121                CircuitBreaker breaker = CircuitBreakerManager.getManager().getCircuitBreaker("banedk");
122                
123                Document page = (Document) breaker.invoke(wrapper);
124                
125                String tableName = arrival == false ? "afgangtabel" : "ankomsttabel";
126                Element table = page.getElementById(tableName);
127                
128                if (table != null) {
129                        Elements tableRows =  table.getElementsByTag("tr");
130                        
131                        for (Element currentRow : tableRows) {
132                            String rowClass = currentRow.attr("class");
133                            if (rowClass != null && rowClass.toLowerCase().contains("station") ) {
134                                    Elements fields = currentRow.getElementsByTag("td");
135            
136                                    DepartureEntry departure = new DepartureEntry();
137                                    
138                                    String time = fields.get(0).text();
139                                    if (time.equals(""))
140                                            time = "0:00"; //Bane.dk bug work-around
141                                    departure.setTime(time);
142                                    
143                                    int updated = extractUpdated( fields.get(1) );
144                                    departure.setUpdated(updated);
145                                    
146                                    String trainNumber = fields.get(2).text();
147                                    if (type == TrainType.STOG) //If it is S-train we need to extract the trainNumber
148                                            trainNumber = trainNumber + " " + extractTrainNumber(fields.get(2));
149                                    departure.setTrainNumber(trainNumber);
150                                    
151                                    String destination = fields.get(3).text();
152                                    departure.setDestination(destination);
153                                    
154                                    String origin = fields.get(4).text();
155                                    departure.setOrigin(origin);
156                                    
157                                    String location = fields.get(5).text();
158                                    departure.setLocation(location);
159                                    
160                                    String status = fields.get(6).text().trim();
161                                    departure.setStatus(status);
162                                    
163                                    String note = extractNote( fields.get(7) );
164                                    departure.setNote(note);
165                                    
166                                    departure.setType(typeString);
167                                    
168                                    departureBean.departureEntries.add( departure );
169                            }
170                        }
171                } else {
172                    logger.warning("No departures found for station=" + stationcode + ", type=" + type);
173                }
174                
175                Element notifDiv = page.getElementById("station_planlagte_text");
176                if (notifDiv != null) {
177    
178                    Elements tables = notifDiv.getElementsByTag("table");
179                    for (Element tab : tables) {
180    
181                            Elements anchors = tab.getElementsByTag("a");          
182                            if (anchors.size() == 2) {
183                                    departureBean.notifications.add(  anchors.get(1).text() );
184                            }
185                    }
186                    
187                }
188                
189                
190                return departureBean;
191            }
192            
193            /*
194            @Deprecated
195            public List<DepartureBean> lookupDeparturesFromTemporarySite(String stationcode, String type) throws Exception {
196                                    
197                  List<DepartureBean> departureList = new ArrayList<DepartureBean>();                  List<DepartureBean> departureList = new ArrayList<DepartureBean>();
198                                    
199              final WebClient webClient = new WebClient();              final WebClient webClient = new WebClient(BrowserVersion.FIREFOX_3);
200              webClient.setTimeout(1000);              webClient.setTimeout(2500);
201              webClient.setJavaScriptEnabled(false);              webClient.setJavaScriptEnabled(false);
202                            
203              final HtmlPage page = webClient.getPage("http://www.bane.dk/visStation.asp?ArtikelID=4275&W=" + type + "&S=" + stationcode);  
204                            String uri = "http://bane.dk/lite/station.asp?w=" + type + "&s=" + stationcode;
205              HtmlElement table = page.getElementById("afgangtabel");              
206              DomNodeList<HtmlElement> tableRows =  table.getElementsByTagName("tr");              HtmlunitInvocation wrapper = new HtmlunitInvocation(webClient, uri);
207                            CircuitBreaker breaker = CircuitBreakerManager.getManager().getCircuitBreaker("banedk");
208              for (HtmlElement currentRow : tableRows) {              
209                  String rowClass = currentRow.getAttribute("class");              HtmlPage page = (HtmlPage) breaker.invoke(wrapper);
210                  if (rowClass != null && rowClass.toLowerCase().contains("station") ) {              
211                          DomNodeList<HtmlElement> fields = currentRow.getElementsByTagName("td");              HtmlElement table = page.getElementById("traf_afgang");
212                
213                          DepartureBean departure = new DepartureBean();              if (table != null) {                        
214                                                DomNodeList<HtmlElement> tableRows =  table.getElementsByTagName("tr");
215                          String time = fields.get(0).asText();                      
216                          departure.setTime(time);                      boolean isFirst = true;
217                                                
218                          int updated = extractUpdated( fields.get(1) );                      for (HtmlElement currentRow : tableRows) {
219                          departure.setUpdated(updated);                          if (isFirst == true) { //skip table headers
220                                                            isFirst = false;
221                          String trainNumber = fields.get(2).asText();                                  continue;
222                          departure.setTrainNumber(trainNumber);                          }
223                                                    
224                          String destination = fields.get(3).asText();                          DomNodeList<HtmlElement> fields = currentRow.getElementsByTagName("td");
225                          departure.setDestination(destination);  
226                                                    DepartureBean departure = new DepartureBean();
227                          String origin = fields.get(4).asText();  
228                          departure.setOrigin(origin);                          String time = fields.get(0).asText().trim();
229                            
230                          String location = fields.get(5).asText();                          if (time.equals(""))
231                          departure.setLocation(location);                                  time = "0:00"; //Bane.dk bug work-around
232                                                    departure.setTime(time);
233                          String status = fields.get(6).asText();  
234                          departure.setStatus(status);  
235                                                    String trainNumber = fields.get(1).asText();
236                          String note = fields.get(7).asText();                          departure.setTrainNumber(trainNumber);
237                          departure.setNote(note);  
238                                                    String destination = fields.get(2).asText();
239                          departureList.add(departure);                          departure.setDestination(destination);
240                  }  
241                            String origin = fields.get(3).asText();
242                            departure.setOrigin(origin);
243    
244                            String status = fields.get(4).asText();
245                            departure.setStatus(status);
246    
247                            String note = fields.get(5).asText();
248                            departure.setNote(note);
249    
250                            departureList.add(departure);
251                        }
252                } else {
253                    logger.warning("No departures found for station=" + stationcode + ", type=" + type);
254              }              }
255                webClient.closeAllWindows();
256                
257                            
258              return departureList;              return departureList;
259          }          }*/
260    
261                    
262          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"
263                  int updated = -1;                  int updated = -1;
264                                    
265                  DomNodeList<HtmlElement> updatedImgs = updatedTd.getElementsByTagName("img");                  Elements updatedImgs = updatedTd.getElementsByTag("img");
266                  String updatedStr = updatedImgs.get(0).getAttribute("src");                  String updatedStr = updatedImgs.get(0).attr("src");
267                                    
268                  if (updatedStr != null) {                  if (updatedStr != null) {
269                          for (int i=0; i<updatedStr.length(); i++) {                          for (int i=0; i<updatedStr.length(); i++) {
# Line 123  public class DepartureFetcher { Line 277  public class DepartureFetcher {
277                  return updated;                  return updated;
278          }          }
279                    
280            private String extractNote(Element noteTd) {
281                    String note = noteTd.text().trim();
282                    
283                    
284                    Elements elems = noteTd.getElementsByClass("bemtype");
285                    if (elems.size() > 0 && note.charAt(note.length()-1) == 'i')
286                            note = note.substring(0,note.length() -1 );
287    
288                    return note;
289            }
290            
291            private String extractTrainNumber(Element trainTd) {
292                    Element anchorElement = trainTd.getElementsByTag("a").get(0);
293                    String href = anchorElement.attr("href");
294                    
295                    int pos = href.lastIndexOf('/');
296                    String number = href.substring(pos+1);
297                    
298                    return number;
299            }
300            
301          //test          //test
302          public static void main(String args[]) throws Exception{          /*
303            public static void main(String args[]) throws Exception {
304                  DepartureFetcher f = new DepartureFetcher();                  DepartureFetcher f = new DepartureFetcher();
305                  List<DepartureBean> deps = f.lookupDepartures("AR", "FJRN");                  List<DepartureBean> deps = f.lookupDepartures("AR", "FJRN");
306                  for(DepartureBean d : deps) {                  for(DepartureBean d : deps) {
# Line 133  public class DepartureFetcher { Line 309  public class DepartureFetcher {
309                  }                  }
310                                    
311                  System.out.println("--------------------------");                  System.out.println("--------------------------");
312          }          }*/
313  }  }

Legend:
Removed from v.308  
changed lines
  Added in v.994

  ViewVC Help
Powered by ViewVC 1.1.20