/[projects]/android/TrainInfoService/src/dk/thoerup/traininfoservice/banedk/DepartureFetcher.java
ViewVC logotype

Diff of /android/TrainInfoService/src/dk/thoerup/traininfoservice/banedk/DepartureFetcher.java

Parent Directory Parent Directory | Revision Log Revision Log | View Patch Patch

revision 308 by torben, Thu Sep 10 18:13:52 2009 UTC revision 1424 by torben, Mon May 2 17:19:30 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.StationEntry;
17    import dk.thoerup.circuitbreaker.CircuitBreaker;
18    import dk.thoerup.circuitbreaker.CircuitBreakerManager;
19    import dk.thoerup.genericjavautils.HttpUtil;
20    import dk.thoerup.genericjavautils.TimeoutMap;
21    import dk.thoerup.traininfoservice.Statistics;
22    import dk.thoerup.traininfoservice.TraininfoSettings;
23    import dk.thoerup.traininfoservice.db.StationDAO;
24    
25  public class DepartureFetcher {  public class DepartureFetcher {
26            
27            enum TrainType{
28                    STOG,
29                    REGIONAL
30            }
31            
32            enum FetchTrainType {
33                    STOG,
34                    REGIONAL,
35                    BOTH
36            }
37            
38            Logger logger = Logger.getLogger(DepartureFetcher.class.getName());
39            
40            Map<String, DepartureBean> cache;
41            
42            StationDAO stationDao = new StationDAO();
43            
44    
45            private TraininfoSettings settings;
46            
47            public DepartureFetcher(TraininfoSettings settings) {
48                    this.settings = settings;
49                    cache = new TimeoutMap<String,DepartureBean>( settings.getCacheTimeout() );
50            }
51            
52            
53                    
54            
55            public DepartureBean cachedLookupDepartures(int stationID, boolean arrival, FetchTrainType type) throws Exception {
56                    
57                    final String key = "" + stationID + ":" + arrival + ":" + type.toString();
58                                    
59                    DepartureBean departureBean = cache.get(key);
60    
         public List<DepartureBean> lookupDepartures(int stationID) throws Exception {  
                 List<DepartureBean> departureList = new ArrayList<DepartureBean>();  
61                                    
62                  Connection conn = null;                  if (departureBean == null) {
63                  try                          departureBean = lookupDepartures(stationID, arrival, type);
64                  {                          cache.put(key, departureBean);
65                          conn = DBConnection.getConnection();                  } else {
66                                            Statistics.getInstance().incrementDepartureCacheHits();
67                          String SQL = "SELECT stationcode_fjrn, stationcode_stog FROM trainstations WHERE id=" + stationID;                          logger.info("Departure: Cache hit " + key); //remove before production
68                          Statement stmt = conn.createStatement();                  }
69                          ResultSet rs = stmt.executeQuery(SQL);                  return departureBean;
70                                    }
71                          if (rs.next()) {                  
72                                  String code = rs.getString( 1 );  
73                                  if (! rs.wasNull() ) {          public DepartureBean lookupDepartures(int stationID, boolean arrival, FetchTrainType type) throws Exception {
74                                          List<DepartureBean> list = lookupDepartures(code, "FJRN");                  
75                                          departureList.addAll(list);                  DepartureBean departureBean = new DepartureBean();
76                                  }                  
77                                                    StationEntry station = stationDao.getById(stationID);
78                                  code = rs.getString(2);                  
79                                  if (! rs.wasNull() ) {                  departureBean.stationName = station.getName();
80                                          List<DepartureBean> list = lookupDepartures(code, "S2");  
81                                          departureList.addAll(list);                      //TODO: FetchTraintype.Both should be removed some time after 0.9.5 release
82                                  }                  if (station.getRegional() != null && (type == FetchTrainType.REGIONAL||type == FetchTrainType.BOTH) ) {
83                                  Collections.sort( departureList );                          DepartureBean tempBean = lookupDepartures(station.getRegional(), TrainType.REGIONAL, arrival);
84                                                    departureBean.entries.addAll( tempBean.entries );
85                          }                          departureBean.notifications.addAll(tempBean.notifications);
86                                            }
87                  } finally {                  
88                          if (conn != null && !conn.isClosed() ) {                  if (station.getStrain() != null && (type == FetchTrainType.STOG||type == FetchTrainType.BOTH)) {
89                                  conn.close();                          DepartureBean tempBean = lookupDepartures(station.getStrain(), TrainType.STOG, arrival);
90                          }                          departureBean.entries.addAll( tempBean.entries );
91                            departureBean.notifications.addAll(tempBean.notifications);
92                    }              
93                    
94                    if (departureBean.entries.size() == 0) {
95                            logger.info("No departures found for station " + stationID);
96                  }                  }
97                                    
98                  return departureList;                  //TODO: FetchTraintype.Both should be removed some time after 0.9.5 release
99                    if (type == FetchTrainType.BOTH) { //if we have both S-tog and regional order by departure/arrival time
100                            Collections.sort( departureBean.entries );
101                    }
102    
103                    
104                    return departureBean;
105          }          }
106                    
107          public List<DepartureBean> lookupDepartures(String stationcode, String type) throws Exception {          public DepartureBean lookupDepartures(String stationcode, TrainType type, boolean arrival) throws Exception {
108                                    if ( settings.getBackend() == TraininfoSettings.Backend.Azure) {
109                  List<DepartureBean> departureList = new ArrayList<DepartureBean>();                          return lookupDeparturesAzureSite(stationcode, type, arrival);
110                    } else {
111                            return lookupDeparturesMobileSite(stationcode, type, arrival);
112                    }
113            }
114            
115            private String getTypeStringAzure(TrainType type) {
116                    switch (type) {
117                    case STOG:
118                            return "S-Tog";
119                    case REGIONAL:
120                            return "Fjerntog";
121                    default:
122                            return ""; //Can not happen
123                    }
124            }
125            
126            private String getTypeStringWww(TrainType type) {
127                    switch (type) {
128                    case STOG:
129                            return "S2";
130                    case REGIONAL:
131                            return "FJRN";
132                    default:
133                            return ""; //Can not happen
134                    }
135            }
136            
137            public DepartureBean lookupDeparturesAzureSite(String stationcode, TrainType type, boolean arrival) throws Exception {
138                                    
139              final WebClient webClient = new WebClient();                  DepartureBean departureBean = new DepartureBean();
140              webClient.setTimeout(1000);                  
141              webClient.setJavaScriptEnabled(false);              
142                            String typeString = getTypeStringAzure(type);
143              final HtmlPage page = webClient.getPage("http://www.bane.dk/visStation.asp?ArtikelID=4275&W=" + type + "&S=" + stationcode);              String arrivalDeparture = (arrival==false) ? "Afgang" : "Ankomst";
144                            
145              HtmlElement table = page.getElementById("afgangtabel");              stationcode = URLEncoder.encode(stationcode,"ISO-8859-1");
146              DomNodeList<HtmlElement> tableRows =  table.getElementsByTagName("tr");  
147                            String uri = "http://trafikinfo.bane.dk/Trafikinformation/AfgangAnkomst/" + arrivalDeparture + "/" + stationcode + "/" + typeString + "/UdvidetVisning";        
148              for (HtmlElement currentRow : tableRows) {              
149                  String rowClass = currentRow.getAttribute("class");              logger.fine("URI: " + uri);    
150                  if (rowClass != null && rowClass.toLowerCase().contains("station") ) {              JsoupInvocation wrapper = new JsoupInvocation( new URL(uri), settings.getReplyTimeout() );
151                          DomNodeList<HtmlElement> fields = currentRow.getElementsByTagName("td");              CircuitBreaker breaker = CircuitBreakerManager.getManager().getCircuitBreaker("banedk");
152                
153                          DepartureBean departure = new DepartureBean();              Document page = (Document) breaker.invoke(wrapper);
154                                        
155                          String time = fields.get(0).asText();              String tableName = arrival == false ? "afgangtabel" : "ankomsttabel";
156                          departure.setTime(time);              Element table = page.getElementById(tableName);
157                                        
158                          int updated = extractUpdated( fields.get(1) );              if (table != null) {
159                          departure.setUpdated(updated);                      Elements tableRows =  table.getElementsByTag("tr");
160                                                
161                          String trainNumber = fields.get(2).asText();                      //boolean tidsstregExists = (table.getElementsByAttributeValue("class", "Tidsstreg").size() > 0);
162                          departure.setTrainNumber(trainNumber);                      //boolean passedTidsstreg = false;
163                                                
164                          String destination = fields.get(3).asText();                      for (Element currentRow : tableRows) {
165                          departure.setDestination(destination);                          String rowClass = currentRow.attr("class");
166                                                    /*
167                          String origin = fields.get(4).asText();                          if (tidsstregExists == true && passedTidsstreg == false) {
168                          departure.setOrigin(origin);                                  if (currentRow.getElementsByAttributeValue("class", "Tidsstreg").size() > 0) {
169                                                                    passedTidsstreg = true;
170                          String location = fields.get(5).asText();                                  } else {
171                          departure.setLocation(location);                                          continue;
172                                                            }
173                          String status = fields.get(6).asText();                          }*/
174                          departure.setStatus(status);                          
175                                                    if (rowClass != null && rowClass.toLowerCase().contains("station") ) {
176                          String note = fields.get(7).asText();                                  
177                          departure.setNote(note);                                  Elements fields = currentRow.getElementsByTag("td");
178                                    
179                          departureList.add(departure);                                  DepartureEntry departure = new DepartureEntry();
180                                    
181                                    String time = fields.get(0).text();
182                                    if (time.equals(""))
183                                            time = "0:00"; //Bane.dk bug work-around
184                                    departure.setTime(time);
185                                    
186                                    int updated = extractUpdated( fields.get(1) );
187                                    departure.setUpdated(updated);
188                                    
189                                    String trainNumber = fields.get(2).text();
190                                    if (type == TrainType.STOG) //If it is S-train we need to extract the trainNumber
191                                            trainNumber = trainNumber + " " + extractTrainNumberAzure(fields.get(2));
192                                    departure.setTrainNumber(trainNumber);
193                                    
194                                    String destination = fields.get(3).text();
195                                    departure.setDestination(destination);
196                                    
197                                    String origin = fields.get(4).text();
198                                    departure.setOrigin(origin);
199                                    
200                                    String location = fields.get(5).text();
201                                    departure.setLocation(location);
202                                    
203                                    String status = fields.get(6).text().trim();
204                                    departure.setStatus(status);
205                                    
206                                    String note = extractNote( fields.get(7) );
207                                    departure.setNote(note);
208                                    
209                                    departure.setType(typeString);
210                                    
211                                    departureBean.entries.add( departure );
212                            }
213                        }
214                } else {
215                    logger.warning("No departures found for station=" + stationcode + ", type=" + type);
216                }
217                
218                Element notifDiv = page.getElementById("station_planlagte_text");
219                if (notifDiv != null) {
220    
221                    Elements tables = notifDiv.getElementsByTag("table");
222                    for (Element tab : tables) {
223    
224                            Elements anchors = tab.getElementsByTag("a");          
225                            if (anchors.size() == 2) {
226                                    departureBean.notifications.add(  anchors.get(1).text() );
227                            }
228                  }                  }
229                    
230              }              }
231                            
232              return departureList;              
233                return departureBean;
234          }          }
235                    
236          private int extractUpdated(HtmlElement updatedTd) { //extract the digit (in this case: 4) from "media/trafikinfo/opdater4.gif"          public DepartureBean lookupDeparturesMobileSite(String stationcode, TrainType traintype, boolean arrival) throws Exception {
237                    
238                    DepartureBean departureBean = new DepartureBean();
239                    
240                
241                    String typeString = getTypeStringWww(traintype);
242                String arrivalDeparture = (arrival==false) ? "afgang" : "ankomst";
243                
244                stationcode = URLEncoder.encode(stationcode,"ISO-8859-1");
245    
246                
247                String uri = "http://mobil.bane.dk/mobilStation.asp?artikelID=5332&stat_kode=" + stationcode + "&webprofil=" + typeString  +"&beskrivelse=&mode=ankomstafgang&ankomstafgang=" + arrivalDeparture + "&gemstation=&fuldvisning=1";
248                logger.fine("URI: " + uri);    
249                JsoupInvocation wrapper = new JsoupInvocation( new URL(uri), settings.getReplyTimeout() );
250                CircuitBreaker breaker = CircuitBreakerManager.getManager().getCircuitBreaker("banedk");
251                
252                Document page = (Document) breaker.invoke(wrapper);
253                
254                
255                Element content = page.getElementsByClass("contentDiv").get(0);
256                
257                
258                if (content != null) {
259                        Elements tableRows =  content.child(0).children();
260                        
261    
262                        
263                        for (Element currentRow : tableRows) {
264                            if (currentRow.tagName().equals("br") ) {
265                                    break;
266                            }
267                            
268                            
269                            String link = currentRow.child(0).attr("href");
270                            
271                                    logger.fine( currentRow.text() );
272                                    logger.fine("Href: " + link);
273                            
274    
275                            String parts[] = currentRow.text().split(",");
276                    
277    
278                            DepartureEntry departure = new DepartureEntry();
279                            
280                            //if we do these things upfront, then we are allowed to use continue statement when row contains no more data
281                            departure.setType(typeString);
282                            departureBean.entries.add( departure );
283    
284    /*
285    http://mobil.bane.dk/mobilStation.asp?artikelID=5332&tognummer=111&webprofil=FJRN&mode=rute&strBemaerkning=Afg%E5r+fra+%C5rhus+H+kl%2E07%3A21++&strRefURL=%2FmobilStation%2Easp%3FartikelID%3D5332%26stat%5Fkode%3DAR%26webprofil%3DFJRN%26beskrivelse%3D%25C5rhus%2BH%26mode%3Dankomstafgang%26ankomstafgang%3Dafgang%26gemstation%3D
286    */
287                            int offset = 0;
288                            
289                            String time = parts[offset++];
290                            if (time.equals(""))
291                                    time = "0:00"; //Bane.dk bug work-around
292                            departure.setTime(time);
293    
294                            int updated = 4; //does not exist on mobile
295                            departure.setUpdated(updated);
296    
297                            String trainNumber = extractTrainNumberMobile(link);
298                            /*if (traintype == TrainType.STOG) //If it is S-train we need to extract the trainNumber
299                                    trainNumber = trainNumber + " " + extractTrainNumberAzure(fields.get(2));*/
300                            departure.setTrainNumber(trainNumber);
301    
302                                    if (traintype == TrainType.STOG) { //if it is stog the next vield is the "Line" code - this should be used somewhere, but skippint ahead for now
303                                            String stogLine = parts[offset++].trim();
304                                            departure.setTrainNumber(stogLine + " " + trainNumber);
305                                    }
306    
307                            String destination = parts[offset++].trim();;
308                            departure.setDestination(destination);
309    
310                            String origin = "-"; // fields.get(4).text(); does not exist on mobile
311                            departure.setOrigin(origin);
312    
313                            String location = ""; // fields.get(5).text(); does not exist on mobile
314                            departure.setLocation(location);
315                            
316                            if (offset == parts.length) {
317                                    continue;
318                            }
319                            
320                            if (parts[offset].trim().equalsIgnoreCase("NB!")) {
321                                    offset++;
322                            }
323                            
324                            if (offset == parts.length) {
325                                    continue;
326                            }
327    
328                            String status = parts[offset++].trim();; //fields.get(6).text().trim(); - extract from url
329                            departure.setStatus(status);
330    
331                            String note = ""; //extractNote( fields.get(7) ); - extract from url
332                            departure.setNote(note);
333    
334                        }
335                } else {
336                    logger.warning("No departures found for station=" + stationcode + ", type=" + traintype);
337                }
338                
339                return departureBean;
340            }
341            
342            
343            
344            public static String cleanText(String input) {
345                    //apparently JSoup translates &nbsp; characters on www.bane.dk to 0xA0
346                    return input.replace((char) 0xA0, (char)0x20).trim();
347            }
348            
349            
350            // old www site is not available any more
351            @Deprecated
352            public DepartureBean lookupDeparturesWwwSite(String stationcode, TrainType trainType, boolean arrival) throws Exception {
353                    
354                    DepartureBean departureBean = new DepartureBean();
355                    
356                    String type = getTypeStringWww(trainType);
357                    
358                    stationcode = URLEncoder.encode(stationcode, "ISO-8859-1");
359                    
360                                                
361                String uri = "http://www.bane.dk/visStation.asp?ArtikelID=4275&W=" + type + "&S=" + stationcode;
362                logger.fine("URI:" + uri);
363                
364    
365                JsoupInvocation wrapper = new JsoupInvocation( new URL(uri), settings.getReplyTimeout() );
366                CircuitBreaker breaker = CircuitBreakerManager.getManager().getCircuitBreaker("banedk");
367                
368                Element page = (Element) breaker.invoke(wrapper);
369                
370                String tableName = arrival == false ? "afgangtabel" : "ankomsttabel";
371                Element table = page.getElementById(tableName);
372                
373    
374                
375                if (table != null) {
376                        Elements tableRows =  table.getElementsByTag("tr");
377                        
378                        //boolean passedTidsstreg = false;
379                        //boolean tidsstregExists = (table.getElementsByAttributeValue("class", "Tidsstreg").size() > 0);
380                        
381                        for (Element currentRow : tableRows) {
382                            String rowClass = currentRow.attr("class");
383                            /*
384                            if (tidsstregExists == true && passedTidsstreg == false) {
385                                    if (currentRow.getElementsByAttributeValue("class", "Tidsstreg").size() > 0) {
386                                            passedTidsstreg = true;
387                                    } else {
388                                            continue;
389                                    }
390                            }*/
391                            
392                            
393                            if (rowClass != null && rowClass.toLowerCase().contains("station") ) {
394                                    Elements fields = currentRow.getElementsByTag("td");
395            
396                                    DepartureEntry departure = new DepartureEntry();
397                                    
398    
399                                    
400                                    String time = cleanText( fields.get(0).getAllElements().get(2).text() );
401                                    if (time.equals(""))
402                                            time = "0:00"; //Bane.dk bug work-around
403                                    departure.setTime(time);
404                                    
405                                    int updated = extractUpdated( fields.get(1) );
406                                    departure.setUpdated(updated);
407                                    
408                                    String trainNumber = cleanText( fields.get(2).text() );
409                                    if (type.equalsIgnoreCase("S2")) //If it is S-train we need to extract the trainNumber
410                                            trainNumber = trainNumber + " " + extractTrainNumberWww(fields.get(2));
411                                    departure.setTrainNumber(trainNumber);
412                                    
413                                    String destination = cleanText( fields.get(3).text() );
414                                    departure.setDestination(destination);
415                                    
416                                    String origin = cleanText( fields.get(4).text() );
417                                    departure.setOrigin(origin);
418                                    
419                                    String location = cleanText( fields.get(5).text() );
420                                    departure.setLocation(location);
421                                    
422                                    String status = cleanText( fields.get(6).text() );
423                                    departure.setStatus(status);
424                                    
425                                    String note = cleanText( extractNote( fields.get(7) ) );
426                                    departure.setNote(note);
427                                    
428                                    departure.setType(type);
429                                    
430                                    departureBean.entries.add(departure);
431                                    
432                                    
433                            }
434                        }
435                } else {
436                    logger.warning("No departures found for station=" + stationcode + ", type=" + type);
437                }
438                
439                
440                return departureBean;
441            }
442                    
443            
444            private int extractUpdated(Element updatedTd) { //extract the digit (in this case: 4) from "media/trafikinfo/opdater4.gif"
445                  int updated = -1;                  int updated = -1;
446                                    
447                  DomNodeList<HtmlElement> updatedImgs = updatedTd.getElementsByTagName("img");                  Elements updatedImgs = updatedTd.getElementsByTag("img");
448                  String updatedStr = updatedImgs.get(0).getAttribute("src");                  String updatedStr = updatedImgs.get(0).attr("src");
449                                    
450                  if (updatedStr != null) {                  if (updatedStr != null) {
451                          for (int i=0; i<updatedStr.length(); i++) {                          for (int i=0; i<updatedStr.length(); i++) {
# Line 123  public class DepartureFetcher { Line 459  public class DepartureFetcher {
459                  return updated;                  return updated;
460          }          }
461                    
462            private String extractNote(Element noteTd) {
463                    String note = noteTd.text().trim();
464                    
465                    
466                    Elements elems = noteTd.getElementsByClass("bemtype");
467                    if (elems.size() > 0 && note.charAt(note.length()-1) == 'i')
468                            note = note.substring(0,note.length() -1 );
469    
470                    return note.trim();
471            }
472            
473            private String extractTrainNumberAzure(Element trainTd) {
474                    Element anchorElement = trainTd.getElementsByTag("a").get(0);
475                    String href = anchorElement.attr("href");
476                    
477                    int pos = href.lastIndexOf('/');
478                    String number = href.substring(pos+1);
479                    
480                    return number;
481            }
482            
483            private String extractTrainNumberMobile(String link) {
484                    Map<String,String> elements = HttpUtil.decodeParams(link);
485                    
486                    return elements.get("tognummer");
487            }
488            
489            private String extractTrainNumberWww(Element trainTd) {
490                    String number = "";
491                    Element anchorElement = trainTd.getElementsByTag("a").get(0);
492                    String href = anchorElement.attr("href");
493    
494                    String argstring = href.split("?")[1];
495                    Map<String,String> elements = HttpUtil.decodeParams(argstring);
496                    number = elements.get("TogNr");        
497                    
498                    
499                    /*String argstring = href.substring( href.indexOf('?') + 1);
500                    String args[] = argstring.split("&");
501                    for (String arg : args) {
502                            String pair[] = arg.split("="); // Key=pair[0], Value=pair[1]
503                            
504                            if (pair[0].equalsIgnoreCase("TogNr"))
505                                    number = pair[1];
506                    }*/
507                                                    
508                    
509                    return number;
510            }
511    
512            
513          //test          //test
514          public static void main(String args[]) throws Exception{          /*
515            public static void main(String args[]) throws Exception {
516                  DepartureFetcher f = new DepartureFetcher();                  DepartureFetcher f = new DepartureFetcher();
517                  List<DepartureBean> deps = f.lookupDepartures("AR", "FJRN");                  List<DepartureBean> deps = f.lookupDepartures("AR", "FJRN");
518                  for(DepartureBean d : deps) {                  for(DepartureBean d : deps) {
# Line 133  public class DepartureFetcher { Line 521  public class DepartureFetcher {
521                  }                  }
522                                    
523                  System.out.println("--------------------------");                  System.out.println("--------------------------");
524          }          }*/
525  }  }

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

  ViewVC Help
Powered by ViewVC 1.1.20