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

Legend:
Removed from v.468  
changed lines
  Added in v.1026

  ViewVC Help
Powered by ViewVC 1.1.20