/[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 349 by torben, Mon Sep 28 19:14:18 2009 UTC revision 1021 by torben, Mon Aug 30 13:59:54 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;  import java.util.logging.Logger;
9    
10  import com.gargoylesoftware.htmlunit.ProxyConfig;  import org.jsoup.nodes.Document;
11  import com.gargoylesoftware.htmlunit.WebClient;  import org.jsoup.nodes.Element;
12  import com.gargoylesoftware.htmlunit.html.DomNodeList;  import org.jsoup.select.Elements;
 import com.gargoylesoftware.htmlunit.html.HtmlElement;  
 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());          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                  return departureList;  
60            public DepartureBean lookupDepartures(int stationID, boolean arrival) throws Exception {
61                    
62                    DepartureBean departureBean = new DepartureBean();
63                    
64                    StationBean station = stationDao.getById(stationID);
65                    
66                    departureBean.stationName = station.getName();
67                    
68                    if (station.getRegional() != null) {
69                            DepartureBean tempBean = lookupDepartures(station.getRegional(), TrainType.REGIONAL, arrival);
70                            departureBean.departureEntries.addAll( tempBean.departureEntries );
71                            departureBean.notifications.addAll(tempBean.notifications);
72                    }
73                    
74                    if (station.getStrain() != null) {
75                            DepartureBean tempBean = lookupDepartures(station.getStrain(), TrainType.STOG, arrival);
76                            departureBean.departureEntries.addAll( tempBean.departureEntries );
77                            departureBean.notifications.addAll(tempBean.notifications);
78                    }              
79                    
80                    Collections.sort( departureBean.departureEntries );
81    
82                    
83                    return departureBean;
84          }          }
85                    
86          public List<DepartureBean> lookupDepartures(String stationcode, String type) throws Exception {          public DepartureBean lookupDepartures(String stationcode, TrainType type, boolean arrival) throws Exception {
87                                    if (useTempSite == false) {
88                  List<DepartureBean> departureList = new ArrayList<DepartureBean>();                          return lookupDeparturesNormalSite(stationcode, type, arrival);
89                    } else {
90                            //return lookupDeparturesFromTemporarySite(stationcode, type);
91                            //TODO: find out what to to if they ever put a temp site up on trafikinfo.bane.dk
92                            return null;
93                    }
94            }
95            
96            private String getTypeString(TrainType type) {
97                    switch (type) {
98                    case STOG:
99                            return "S-Tog";
100                    case REGIONAL:
101                            return "Fjerntog";
102                    default:
103                            return ""; //Can not happen
104                    }
105            }
106            
107            public DepartureBean lookupDeparturesNormalSite(String stationcode, TrainType type, boolean arrival) throws Exception {
108                                    
109              final WebClient webClient = new WebClient();                  DepartureBean departureBean = new DepartureBean();
110              webClient.setTimeout(1000);                  
111              webClient.setJavaScriptEnabled(false);              
112                                            String typeString = getTypeString(type);
113                String arrivalDeparture = (arrival==false) ? "Afgang" : "Ankomst";
114                
115                stationcode = URLEncoder.encode(stationcode,"ISO-8859-1");
116                //String uri = "http://www.bane.dk/visStation.asp?ArtikelID=4275&W=" + type + "&S=" + stationcode;
117                String uri = "http://trafikinfo.bane.dk/Trafikinformation/AfgangAnkomst/" + arrivalDeparture + "/" + stationcode + "/" + typeString + "/UdvidetVisning";
118    
119                
120                            
121              final HtmlPage page = webClient.getPage("http://www.bane.dk/visStation.asp?ArtikelID=4275&W=" + type + "&S=" + stationcode);              //logger.info("URI: " + uri);          
122                JsoupInvocation wrapper = new JsoupInvocation( new URL(uri), 2500);
123                CircuitBreaker breaker = CircuitBreakerManager.getManager().getCircuitBreaker("banedk");
124                            
125              HtmlElement table = page.getElementById("afgangtabel");              Document page = (Document) breaker.invoke(wrapper);
126                
127                String tableName = arrival == false ? "afgangtabel" : "ankomsttabel";
128                Element table = page.getElementById(tableName);
129                            
130              if (table != null) {              if (table != null) {
131                      DomNodeList<HtmlElement> tableRows =  table.getElementsByTagName("tr");                      Elements tableRows =  table.getElementsByTag("tr");
132                                            
133                      for (HtmlElement currentRow : tableRows) {                      boolean tidsstregExists = (table.getElementsByAttributeValue("class", "Tidsstreg").size() > 0);
134                          String rowClass = currentRow.getAttribute("class");                      boolean passedTidsstreg = false;
135                        
136                        for (Element currentRow : tableRows) {
137                            String rowClass = currentRow.attr("class");
138                            
139                            if (tidsstregExists == true && passedTidsstreg == false) {
140                                    if (currentRow.getElementsByAttributeValue("class", "Tidsstreg").size() > 0) {
141                                            passedTidsstreg = true;
142                                    } else {
143                                            continue;
144                                    }
145                            }
146                            
147                          if (rowClass != null && rowClass.toLowerCase().contains("station") ) {                          if (rowClass != null && rowClass.toLowerCase().contains("station") ) {
148                                  DomNodeList<HtmlElement> fields = currentRow.getElementsByTagName("td");                                  
149                                    Elements fields = currentRow.getElementsByTag("td");
150                    
151                                  DepartureBean departure = new DepartureBean();                                  DepartureEntry departure = new DepartureEntry();
152                                                                    
153                                  String time = fields.get(0).asText();                                  String time = fields.get(0).text();
154                                    if (time.equals(""))
155                                            time = "0:00"; //Bane.dk bug work-around
156                                  departure.setTime(time);                                  departure.setTime(time);
157                                                                    
158                                  int updated = extractUpdated( fields.get(1) );                                  int updated = extractUpdated( fields.get(1) );
159                                  departure.setUpdated(updated);                                  departure.setUpdated(updated);
160                                                                    
161                                  String trainNumber = fields.get(2).asText();                                  String trainNumber = fields.get(2).text();
162                                  if (trainNumber.trim().length() == 1)                                  if (type == TrainType.STOG) //If it is S-train we need to extract the trainNumber
163                                          trainNumber = trainNumber + " " + extractTrainNumber(fields.get(2));                                          trainNumber = trainNumber + " " + extractTrainNumber(fields.get(2));
164                                  departure.setTrainNumber(trainNumber);                                  departure.setTrainNumber(trainNumber);
165                                                                    
166                                  String destination = fields.get(3).asText();                                  String destination = fields.get(3).text();
167                                  departure.setDestination(destination);                                  departure.setDestination(destination);
168                                                                    
169                                  String origin = fields.get(4).asText();                                  String origin = fields.get(4).text();
170                                  departure.setOrigin(origin);                                  departure.setOrigin(origin);
171                                                                    
172                                  String location = fields.get(5).asText();                                  String location = fields.get(5).text();
173                                  departure.setLocation(location);                                  departure.setLocation(location);
174                                                                    
175                                  String status = fields.get(6).asText();                                  String status = fields.get(6).text().trim();
176                                  departure.setStatus(status);                                  departure.setStatus(status);
177                                                                    
178                                  String note = extractNote( fields.get(7) );                                  String note = extractNote( fields.get(7) );
179                                  departure.setNote(note);                                  departure.setNote(note);
180                                                                    
181                                  departureList.add(departure);                                  departure.setType(typeString);
182                                    
183                                    departureBean.departureEntries.add( departure );
184                          }                          }
185                      }                      }
186              } else {              } else {
187                  logger.warning("No departures found for station=" + stationcode + ", type=" + type);                  logger.warning("No departures found for station=" + stationcode + ", type=" + type);
188              }              }
189                            
190              return departureList;              Element notifDiv = page.getElementById("station_planlagte_text");
191                if (notifDiv != null) {
192    
193                    Elements tables = notifDiv.getElementsByTag("table");
194                    for (Element tab : tables) {
195    
196                            Elements anchors = tab.getElementsByTag("a");          
197                            if (anchors.size() == 2) {
198                                    departureBean.notifications.add(  anchors.get(1).text() );
199                            }
200                    }
201                    
202                }
203                
204                
205                return departureBean;
206          }          }
207                    
208          private int extractUpdated(HtmlElement updatedTd) { //extract the digit (in this case: 4) from "media/trafikinfo/opdater4.gif"          /*
209            @Deprecated
210            public List<DepartureBean> lookupDeparturesFromTemporarySite(String stationcode, String type) throws Exception {
211                    
212                    List<DepartureBean> departureList = new ArrayList<DepartureBean>();
213                    
214                final WebClient webClient = new WebClient(BrowserVersion.FIREFOX_3);
215                webClient.setTimeout(2500);
216                webClient.setJavaScriptEnabled(false);
217                
218    
219                String uri = "http://bane.dk/lite/station.asp?w=" + type + "&s=" + stationcode;
220                
221                HtmlunitInvocation wrapper = new HtmlunitInvocation(webClient, uri);
222                CircuitBreaker breaker = CircuitBreakerManager.getManager().getCircuitBreaker("banedk");
223                
224                HtmlPage page = (HtmlPage) breaker.invoke(wrapper);
225                
226                HtmlElement table = page.getElementById("traf_afgang");
227                
228                if (table != null) {                        
229                        DomNodeList<HtmlElement> tableRows =  table.getElementsByTagName("tr");
230                        
231                        boolean isFirst = true;
232                        
233                        for (HtmlElement currentRow : tableRows) {
234                            if (isFirst == true) { //skip table headers
235                                    isFirst = false;
236                                    continue;
237                            }
238                            
239                            DomNodeList<HtmlElement> fields = currentRow.getElementsByTagName("td");
240    
241                            DepartureBean departure = new DepartureBean();
242    
243                            String time = fields.get(0).asText().trim();
244    
245                            if (time.equals(""))
246                                    time = "0:00"; //Bane.dk bug work-around
247                            departure.setTime(time);
248    
249    
250                            String trainNumber = fields.get(1).asText();
251                            departure.setTrainNumber(trainNumber);
252    
253                            String destination = fields.get(2).asText();
254                            departure.setDestination(destination);
255    
256                            String origin = fields.get(3).asText();
257                            departure.setOrigin(origin);
258    
259                            String status = fields.get(4).asText();
260                            departure.setStatus(status);
261    
262                            String note = fields.get(5).asText();
263                            departure.setNote(note);
264    
265                            departureList.add(departure);
266                        }
267                } else {
268                    logger.warning("No departures found for station=" + stationcode + ", type=" + type);
269                }
270                webClient.closeAllWindows();
271                
272                
273                return departureList;
274            }*/
275    
276            
277            private int extractUpdated(Element updatedTd) { //extract the digit (in this case: 4) from "media/trafikinfo/opdater4.gif"
278                  int updated = -1;                  int updated = -1;
279                                    
280                  DomNodeList<HtmlElement> updatedImgs = updatedTd.getElementsByTagName("img");                  Elements updatedImgs = updatedTd.getElementsByTag("img");
281                  String updatedStr = updatedImgs.get(0).getAttribute("src");                  String updatedStr = updatedImgs.get(0).attr("src");
282                                    
283                  if (updatedStr != null) {                  if (updatedStr != null) {
284                          for (int i=0; i<updatedStr.length(); i++) {                          for (int i=0; i<updatedStr.length(); i++) {
# Line 135  public class DepartureFetcher { Line 292  public class DepartureFetcher {
292                  return updated;                  return updated;
293          }          }
294                    
295          private String extractNote(HtmlElement noteTd) {          private String extractNote(Element noteTd) {
296                  String note = noteTd.asText().trim();                  String note = noteTd.text().trim();
297                    
298                                    
299                  List<HtmlElement> elems = noteTd.getElementsByAttribute("span", "class", "bemtype");                  Elements elems = noteTd.getElementsByClass("bemtype");
300                  if (elems.size() > 0 && note.charAt(note.length()-1) == 'i')                  if (elems.size() > 0 && note.charAt(note.length()-1) == 'i')
301                          note = note.substring(0,note.length() -1 );                          note = note.substring(0,note.length() -1 );
302    
303                  return note;                  return note;
304          }          }
305                    
306          private String extractTrainNumber(HtmlElement trainTd) {          private String extractTrainNumber(Element trainTd) {
307                  String number = "";                  Element anchorElement = trainTd.getElementsByTag("a").get(0);
308                  HtmlElement anchorElement = trainTd.getElementsByTagName("a").get(0);                  String href = anchorElement.attr("href");
                 String href = anchorElement.getAttribute("href");  
                 String argstring = href.substring( href.indexOf('?') + 1);  
                   
                 String args[] = argstring.split("&");  
                 for (String arg : args) {  
                         String pair[] = arg.split("="); // Key=pair[0], Value=pair[1]  
                           
                         if (pair[0].equalsIgnoreCase("TogNr"))  
                                 number = pair[1];  
                 }  
                   
309                                    
310                    int pos = href.lastIndexOf('/');
311                    String number = href.substring(pos+1);
312                                    
313                  return number;                  return number;
314          }          }
315                    
316          //test          //test
317          public static void main(String args[]) throws Exception{          /*
318            public static void main(String args[]) throws Exception {
319                  DepartureFetcher f = new DepartureFetcher();                  DepartureFetcher f = new DepartureFetcher();
320                  List<DepartureBean> deps = f.lookupDepartures("AR", "FJRN");                  List<DepartureBean> deps = f.lookupDepartures("AR", "FJRN");
321                  for(DepartureBean d : deps) {                  for(DepartureBean d : deps) {
# Line 174  public class DepartureFetcher { Line 324  public class DepartureFetcher {
324                  }                  }
325                                    
326                  System.out.println("--------------------------");                  System.out.println("--------------------------");
327          }          }*/
328  }  }

Legend:
Removed from v.349  
changed lines
  Added in v.1021

  ViewVC Help
Powered by ViewVC 1.1.20