/[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 1255 by torben, Mon Apr 4 10:56:44 2011 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.android.traininfo.common.DepartureBean;
15    import dk.thoerup.android.traininfo.common.DepartureEntry;
16    import dk.thoerup.android.traininfo.common.StationBean.StationEntry;
17    import dk.thoerup.circuitbreaker.CircuitBreaker;
18    import dk.thoerup.circuitbreaker.CircuitBreakerManager;
19    import dk.thoerup.traininfoservice.Statistics;
20    import dk.thoerup.traininfoservice.db.StationDAO;
21    
22  public class DepartureFetcher {  public class DepartureFetcher {
23                    
24            enum TrainType{
25                    STOG,
26                    REGIONAL
27            }
28            
29            enum FetchTrainType {
30                    STOG,
31                    REGIONAL,
32                    BOTH
33            }
34            
35          Logger logger = Logger.getLogger(DepartureFetcher.class.getName());          Logger logger = Logger.getLogger(DepartureFetcher.class.getName());
36            
37            Map<String, DepartureBean> cache;
38            
39            StationDAO stationDao = new StationDAO();
40            
41            private boolean useAzureSite;
42            private int replyTimeout;
43            
44            public DepartureFetcher(boolean azureSite, int cacheTimeout, int replyTimeout) {
45                    this.replyTimeout = replyTimeout;
46                    useAzureSite = azureSite;
47                    cache = new TimeoutMap<String,DepartureBean>(cacheTimeout);
48            }
49            
50            
51                                    
52            
53            public DepartureBean cachedLookupDepartures(int stationID, boolean arrival, FetchTrainType type) throws Exception {
54                    
55                    final String key = "" + stationID + ":" + arrival + ":" + type.toString();
56                    
57                    DepartureBean departureBean = cache.get(key);
58    
         public List<DepartureBean> lookupDepartures(int stationID) throws Exception {  
                 List<DepartureBean> departureList = new ArrayList<DepartureBean>();  
59                                    
60                  Connection conn = null;                  if (departureBean == null) {
61                  try                          departureBean = lookupDepartures(stationID, arrival, type);
62                  {                          cache.put(key, departureBean);
63                          conn = DBConnection.getConnection();                  } else {
64                                            Statistics.getInstance().incrementDepartureCacheHits();
65                          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();  
                         }  
66                  }                  }
67                    return departureBean;
68            }
69                                    
70                  return departureList;  
71            public DepartureBean lookupDepartures(int stationID, boolean arrival, FetchTrainType type) throws Exception {
72                    
73                    DepartureBean departureBean = new DepartureBean();
74                    
75                    StationEntry station = stationDao.getById(stationID);
76                    
77                    departureBean.stationName = station.getName();
78    
79                    if (station.getRegional() != null && (type == FetchTrainType.REGIONAL||type == FetchTrainType.BOTH) ) {
80                            DepartureBean tempBean = lookupDepartures(station.getRegional(), TrainType.REGIONAL, arrival);
81                            departureBean.entries.addAll( tempBean.entries );
82                            departureBean.notifications.addAll(tempBean.notifications);
83                    }
84                    
85                    if (station.getStrain() != null && (type == FetchTrainType.STOG||type == FetchTrainType.BOTH)) {
86                            DepartureBean tempBean = lookupDepartures(station.getStrain(), TrainType.STOG, arrival);
87                            departureBean.entries.addAll( tempBean.entries );
88                            departureBean.notifications.addAll(tempBean.notifications);
89                    }              
90                    
91                    if (departureBean.entries.size() == 0) {
92                            logger.info("No departures found for station " + stationID);
93                    }
94                    
95                    if (type == FetchTrainType.BOTH) { //if we have both S-tog and regional order by departure/arrival time
96                            Collections.sort( departureBean.entries );
97                    }
98    
99                    
100                    return departureBean;
101          }          }
102                    
103          public List<DepartureBean> lookupDepartures(String stationcode, String type) throws Exception {          public DepartureBean lookupDepartures(String stationcode, TrainType type, boolean arrival) throws Exception {
104                                    if (useAzureSite == true) {
105                  List<DepartureBean> departureList = new ArrayList<DepartureBean>();                          return lookupDeparturesAzureSite(stationcode, type, arrival);
106                    } else {
107                            return lookupDeparturesWwwSite(stationcode, type, arrival);
108                    }
109            }
110            
111            private String getTypeStringAzure(TrainType type) {
112                    switch (type) {
113                    case STOG:
114                            return "S-Tog";
115                    case REGIONAL:
116                            return "Fjerntog";
117                    default:
118                            return ""; //Can not happen
119                    }
120            }
121            
122            private String getTypeStringWww(TrainType type) {
123                    switch (type) {
124                    case STOG:
125                            return "S2";
126                    case REGIONAL:
127                            return "FJRN";
128                    default:
129                            return ""; //Can not happen
130                    }
131            }
132            
133            public DepartureBean lookupDeparturesAzureSite(String stationcode, TrainType type, boolean arrival) throws Exception {
134                                    
135              final WebClient webClient = new WebClient();                  DepartureBean departureBean = new DepartureBean();
136              webClient.setTimeout(1000);                  
137              webClient.setJavaScriptEnabled(false);              
138                                            String typeString = getTypeStringAzure(type);
139                String arrivalDeparture = (arrival==false) ? "Afgang" : "Ankomst";
140                
141                stationcode = URLEncoder.encode(stationcode,"ISO-8859-1");
142    
143                String uri = "http://trafikinfo.bane.dk/Trafikinformation/AfgangAnkomst/" + arrivalDeparture + "/" + stationcode + "/" + typeString + "/UdvidetVisning";        
144                            
145              final HtmlPage page = webClient.getPage("http://www.bane.dk/visStation.asp?ArtikelID=4275&W=" + type + "&S=" + stationcode);              logger.fine("URI: " + uri);    
146                JsoupInvocation wrapper = new JsoupInvocation( new URL(uri), replyTimeout);
147                CircuitBreaker breaker = CircuitBreakerManager.getManager().getCircuitBreaker("banedk");
148                            
149              HtmlElement table = page.getElementById("afgangtabel");              Document page = (Document) breaker.invoke(wrapper);
150                
151                String tableName = arrival == false ? "afgangtabel" : "ankomsttabel";
152                Element table = page.getElementById(tableName);
153                            
154              if (table != null) {              if (table != null) {
155                      DomNodeList<HtmlElement> tableRows =  table.getElementsByTagName("tr");                      Elements tableRows =  table.getElementsByTag("tr");
156                        
157                        //boolean tidsstregExists = (table.getElementsByAttributeValue("class", "Tidsstreg").size() > 0);
158                        //boolean passedTidsstreg = false;
159                                            
160                      for (HtmlElement currentRow : tableRows) {                      for (Element currentRow : tableRows) {
161                          String rowClass = currentRow.getAttribute("class");                          String rowClass = currentRow.attr("class");
162                            /*
163                            if (tidsstregExists == true && passedTidsstreg == false) {
164                                    if (currentRow.getElementsByAttributeValue("class", "Tidsstreg").size() > 0) {
165                                            passedTidsstreg = true;
166                                    } else {
167                                            continue;
168                                    }
169                            }*/
170                            
171                          if (rowClass != null && rowClass.toLowerCase().contains("station") ) {                          if (rowClass != null && rowClass.toLowerCase().contains("station") ) {
172                                  DomNodeList<HtmlElement> fields = currentRow.getElementsByTagName("td");                                  
173                                    Elements fields = currentRow.getElementsByTag("td");
174                    
175                                  DepartureBean departure = new DepartureBean();                                  DepartureEntry departure = new DepartureEntry();
176                                                                    
177                                  String time = fields.get(0).asText();                                  String time = fields.get(0).text();
178                                    if (time.equals(""))
179                                            time = "0:00"; //Bane.dk bug work-around
180                                  departure.setTime(time);                                  departure.setTime(time);
181                                                                    
182                                  int updated = extractUpdated( fields.get(1) );                                  int updated = extractUpdated( fields.get(1) );
183                                  departure.setUpdated(updated);                                  departure.setUpdated(updated);
184                                                                    
185                                  String trainNumber = fields.get(2).asText();                                  String trainNumber = fields.get(2).text();
186                                  if (trainNumber.trim().length() == 1)                                  if (type == TrainType.STOG) //If it is S-train we need to extract the trainNumber
187                                          trainNumber = trainNumber + " " + extractTrainNumber(fields.get(2));                                          trainNumber = trainNumber + " " + extractTrainNumberAzure(fields.get(2));
188                                  departure.setTrainNumber(trainNumber);                                  departure.setTrainNumber(trainNumber);
189                                                                    
190                                  String destination = fields.get(3).asText();                                  String destination = fields.get(3).text();
191                                  departure.setDestination(destination);                                  departure.setDestination(destination);
192                                                                    
193                                  String origin = fields.get(4).asText();                                  String origin = fields.get(4).text();
194                                  departure.setOrigin(origin);                                  departure.setOrigin(origin);
195                                                                    
196                                  String location = fields.get(5).asText();                                  String location = fields.get(5).text();
197                                  departure.setLocation(location);                                  departure.setLocation(location);
198                                                                    
199                                  String status = fields.get(6).asText();                                  String status = fields.get(6).text().trim();
200                                  departure.setStatus(status);                                  departure.setStatus(status);
201                                                                    
202                                  String note = extractNote( fields.get(7) );                                  String note = extractNote( fields.get(7) );
203                                  departure.setNote(note);                                  departure.setNote(note);
204                                                                    
205                                  departureList.add(departure);                                  departure.setType(typeString);
206                                    
207                                    departureBean.entries.add( departure );
208                          }                          }
209                      }                      }
210              } else {              } else {
211                  logger.warning("No departures found for station=" + stationcode + ", type=" + type);                  logger.warning("No departures found for station=" + stationcode + ", type=" + type);
212              }              }
213                            
214              return departureList;              Element notifDiv = page.getElementById("station_planlagte_text");
215                if (notifDiv != null) {
216    
217                    Elements tables = notifDiv.getElementsByTag("table");
218                    for (Element tab : tables) {
219    
220                            Elements anchors = tab.getElementsByTag("a");          
221                            if (anchors.size() == 2) {
222                                    departureBean.notifications.add(  anchors.get(1).text() );
223                            }
224                    }
225                    
226                }
227                
228                
229                return departureBean;
230          }          }
231                    
232          private int extractUpdated(HtmlElement updatedTd) { //extract the digit (in this case: 4) from "media/trafikinfo/opdater4.gif"          
233            
234            public static String cleanText(String input) {
235                    //apparently JSoup translates &nbsp; characters on www.bane.dk to 0xA0
236                    return input.replace((char) 0xA0, (char)0x20).trim();
237            }
238            
239            public DepartureBean lookupDeparturesWwwSite(String stationcode, TrainType trainType, boolean arrival) throws Exception {
240                    
241                    DepartureBean departureBean = new DepartureBean();
242                    
243                    String type = getTypeStringWww(trainType);
244                    
245                    stationcode = URLEncoder.encode(stationcode, "ISO-8859-1");
246                    
247                                                
248                String uri = "http://www.bane.dk/visStation.asp?ArtikelID=4275&W=" + type + "&S=" + stationcode;
249                logger.fine("URI:" + uri);
250                
251    
252                JsoupInvocation wrapper = new JsoupInvocation( new URL(uri), replyTimeout);
253                CircuitBreaker breaker = CircuitBreakerManager.getManager().getCircuitBreaker("banedk");
254                
255                Element page = (Element) breaker.invoke(wrapper);
256                
257                String tableName = arrival == false ? "afgangtabel" : "ankomsttabel";
258                Element table = page.getElementById(tableName);
259                
260    
261                
262                if (table != null) {
263                        Elements tableRows =  table.getElementsByTag("tr");
264                        
265                        //boolean passedTidsstreg = false;
266                        //boolean tidsstregExists = (table.getElementsByAttributeValue("class", "Tidsstreg").size() > 0);
267                        
268                        for (Element currentRow : tableRows) {
269                            String rowClass = currentRow.attr("class");
270                            /*
271                            if (tidsstregExists == true && passedTidsstreg == false) {
272                                    if (currentRow.getElementsByAttributeValue("class", "Tidsstreg").size() > 0) {
273                                            passedTidsstreg = true;
274                                    } else {
275                                            continue;
276                                    }
277                            }*/
278                            
279                            
280                            if (rowClass != null && rowClass.toLowerCase().contains("station") ) {
281                                    Elements fields = currentRow.getElementsByTag("td");
282            
283                                    DepartureEntry departure = new DepartureEntry();
284                                    
285    
286                                    
287                                    String time = cleanText( fields.get(0).getAllElements().get(2).text() );
288                                    if (time.equals(""))
289                                            time = "0:00"; //Bane.dk bug work-around
290                                    departure.setTime(time);
291                                    
292                                    int updated = extractUpdated( fields.get(1) );
293                                    departure.setUpdated(updated);
294                                    
295                                    String trainNumber = cleanText( fields.get(2).text() );
296                                    if (type.equalsIgnoreCase("S2")) //If it is S-train we need to extract the trainNumber
297                                            trainNumber = trainNumber + " " + extractTrainNumberWww(fields.get(2));
298                                    departure.setTrainNumber(trainNumber);
299                                    
300                                    String destination = cleanText( fields.get(3).text() );
301                                    departure.setDestination(destination);
302                                    
303                                    String origin = cleanText( fields.get(4).text() );
304                                    departure.setOrigin(origin);
305                                    
306                                    String location = cleanText( fields.get(5).text() );
307                                    departure.setLocation(location);
308                                    
309                                    String status = cleanText( fields.get(6).text() );
310                                    departure.setStatus(status);
311                                    
312                                    String note = cleanText( extractNote( fields.get(7) ) );
313                                    departure.setNote(note);
314                                    
315                                    departure.setType(type);
316                                    
317                                    departureBean.entries.add(departure);
318                                    
319                                    
320                            }
321                        }
322                } else {
323                    logger.warning("No departures found for station=" + stationcode + ", type=" + type);
324                }
325                
326                
327                return departureBean;
328            }
329                    
330            
331            private int extractUpdated(Element updatedTd) { //extract the digit (in this case: 4) from "media/trafikinfo/opdater4.gif"
332                  int updated = -1;                  int updated = -1;
333                                    
334                  DomNodeList<HtmlElement> updatedImgs = updatedTd.getElementsByTagName("img");                  Elements updatedImgs = updatedTd.getElementsByTag("img");
335                  String updatedStr = updatedImgs.get(0).getAttribute("src");                  String updatedStr = updatedImgs.get(0).attr("src");
336                                    
337                  if (updatedStr != null) {                  if (updatedStr != null) {
338                          for (int i=0; i<updatedStr.length(); i++) {                          for (int i=0; i<updatedStr.length(); i++) {
# Line 135  public class DepartureFetcher { Line 346  public class DepartureFetcher {
346                  return updated;                  return updated;
347          }          }
348                    
349          private String extractNote(HtmlElement noteTd) {          private String extractNote(Element noteTd) {
350                  String note = noteTd.asText().trim();                  String note = noteTd.text().trim();
351                                    
352                  List<HtmlElement> elems = noteTd.getElementsByAttribute("span", "class", "bemtype");                  
353                    Elements elems = noteTd.getElementsByClass("bemtype");
354                  if (elems.size() > 0 && note.charAt(note.length()-1) == 'i')                  if (elems.size() > 0 && note.charAt(note.length()-1) == 'i')
355                          note = note.substring(0,note.length() -1 );                          note = note.substring(0,note.length() -1 );
356    
357                  return note;                  return note.trim();
358          }          }
359                    
360          private String extractTrainNumber(HtmlElement trainTd) {          private String extractTrainNumberAzure(Element trainTd) {
361                    Element anchorElement = trainTd.getElementsByTag("a").get(0);
362                    String href = anchorElement.attr("href");
363                    
364                    int pos = href.lastIndexOf('/');
365                    String number = href.substring(pos+1);
366                    
367                    return number;
368            }
369            
370            private String extractTrainNumberWww(Element trainTd) {
371                  String number = "";                  String number = "";
372                  HtmlElement anchorElement = trainTd.getElementsByTagName("a").get(0);                  Element anchorElement = trainTd.getElementsByTag("a").get(0);
373                  String href = anchorElement.getAttribute("href");                  String href = anchorElement.attr("href");
374                  String argstring = href.substring( href.indexOf('?') + 1);                  String argstring = href.substring( href.indexOf('?') + 1);
375                                    
376                  String args[] = argstring.split("&");                  String args[] = argstring.split("&");
# Line 160  public class DepartureFetcher { Line 382  public class DepartureFetcher {
382                  }                  }
383                                    
384                                    
                   
385                  return number;                  return number;
386          }          }
387    
388                    
389          //test          //test
390          public static void main(String args[]) throws Exception{          /*
391            public static void main(String args[]) throws Exception {
392                  DepartureFetcher f = new DepartureFetcher();                  DepartureFetcher f = new DepartureFetcher();
393                  List<DepartureBean> deps = f.lookupDepartures("AR", "FJRN");                  List<DepartureBean> deps = f.lookupDepartures("AR", "FJRN");
394                  for(DepartureBean d : deps) {                  for(DepartureBean d : deps) {
# Line 174  public class DepartureFetcher { Line 397  public class DepartureFetcher {
397                  }                  }
398                                    
399                  System.out.println("--------------------------");                  System.out.println("--------------------------");
400          }          }*/
401  }  }

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

  ViewVC Help
Powered by ViewVC 1.1.20