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

Legend:
Removed from v.307  
changed lines
  Added in v.1248

  ViewVC Help
Powered by ViewVC 1.1.20