/[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 1035 by torben, Wed Sep 8 12:38:26 2010 UTC revision 1252 by torben, Mon Apr 4 08:27:24 2011 UTC
# Line 11  import org.jsoup.nodes.Document; Line 11  import org.jsoup.nodes.Document;
11  import org.jsoup.nodes.Element;  import org.jsoup.nodes.Element;
12  import org.jsoup.select.Elements;  import org.jsoup.select.Elements;
13    
14    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;  import dk.thoerup.circuitbreaker.CircuitBreaker;
18  import dk.thoerup.circuitbreaker.CircuitBreakerManager;  import dk.thoerup.circuitbreaker.CircuitBreakerManager;
 import dk.thoerup.traininfoservice.StationBean;  
19  import dk.thoerup.traininfoservice.StationDAO;  import dk.thoerup.traininfoservice.StationDAO;
20  import dk.thoerup.traininfoservice.Statistics;  import dk.thoerup.traininfoservice.Statistics;
21    
# Line 24  public class DepartureFetcher { Line 26  public class DepartureFetcher {
26                  REGIONAL                  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;          Map<String, DepartureBean> cache;
# Line 42  public class DepartureFetcher { Line 50  public class DepartureFetcher {
50                    
51                                    
52                    
53          public DepartureBean cachedLookupDepartures(int stationID, boolean arrival) throws Exception {          public DepartureBean cachedLookupDepartures(int stationID, boolean arrival, FetchTrainType type) throws Exception {
54                  final String key = "" + stationID + ":" + arrival;                  
55                    final String key = "" + stationID + ":" + arrival + ":" + type.toString();
56                                    
57                  DepartureBean departureBean = cache.get(key);                  DepartureBean departureBean = cache.get(key);
58    
59                                    
60                  if (departureBean == null) {                  if (departureBean == null) {
61                          departureBean = lookupDepartures(stationID,arrival);                          departureBean = lookupDepartures(stationID, arrival, type);
62                          cache.put(key, departureBean);                          cache.put(key, departureBean);
63                  } else {                  } else {
64                          Statistics.getInstance().incrementDepartureCacheHits();                          Statistics.getInstance().incrementDepartureCacheHits();
# Line 59  public class DepartureFetcher { Line 68  public class DepartureFetcher {
68          }          }
69                                    
70    
71          public DepartureBean lookupDepartures(int stationID, boolean arrival) throws Exception {          public DepartureBean lookupDepartures(int stationID, boolean arrival, FetchTrainType type) throws Exception {
72                                    
73                  DepartureBean departureBean = new DepartureBean();                  DepartureBean departureBean = new DepartureBean();
74                                    
75                  StationBean station = stationDao.getById(stationID);                  StationEntry station = stationDao.getById(stationID);
76                                    
77                  departureBean.stationName = station.getName();                  departureBean.stationName = station.getName();
78                    
79                  if (station.getRegional() != null) {                  if (station.getRegional() != null && (type == FetchTrainType.REGIONAL||type == FetchTrainType.BOTH) ) {
80                          DepartureBean tempBean = lookupDepartures(station.getRegional(), TrainType.REGIONAL, arrival);                          DepartureBean tempBean = lookupDepartures(station.getRegional(), TrainType.REGIONAL, arrival);
81                          departureBean.departureEntries.addAll( tempBean.departureEntries );                          departureBean.entries.addAll( tempBean.entries );
82                          departureBean.notifications.addAll(tempBean.notifications);                          departureBean.notifications.addAll(tempBean.notifications);
83                  }                  }
84                                    
85                  if (station.getStrain() != null) {                  if (station.getStrain() != null && (type == FetchTrainType.STOG||type == FetchTrainType.BOTH)) {
86                          DepartureBean tempBean = lookupDepartures(station.getStrain(), TrainType.STOG, arrival);                          DepartureBean tempBean = lookupDepartures(station.getStrain(), TrainType.STOG, arrival);
87                          departureBean.departureEntries.addAll( tempBean.departureEntries );                          departureBean.entries.addAll( tempBean.entries );
88                          departureBean.notifications.addAll(tempBean.notifications);                          departureBean.notifications.addAll(tempBean.notifications);
89                  }                                }              
90                                    
91                  Collections.sort( departureBean.departureEntries );                  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;                  return departureBean;
# Line 127  public class DepartureFetcher { Line 142  public class DepartureFetcher {
142    
143              String uri = "http://trafikinfo.bane.dk/Trafikinformation/AfgangAnkomst/" + arrivalDeparture + "/" + stationcode + "/" + typeString + "/UdvidetVisning";                      String uri = "http://trafikinfo.bane.dk/Trafikinformation/AfgangAnkomst/" + arrivalDeparture + "/" + stationcode + "/" + typeString + "/UdvidetVisning";        
144                            
145              //logger.info("URI: " + uri);                        logger.fine("URI: " + uri);    
146              JsoupInvocation wrapper = new JsoupInvocation( new URL(uri), replyTimeout);              JsoupInvocation wrapper = new JsoupInvocation( new URL(uri), replyTimeout);
147              CircuitBreaker breaker = CircuitBreakerManager.getManager().getCircuitBreaker("banedk");              CircuitBreaker breaker = CircuitBreakerManager.getManager().getCircuitBreaker("banedk");
148                            
# Line 139  public class DepartureFetcher { Line 154  public class DepartureFetcher {
154              if (table != null) {              if (table != null) {
155                      Elements tableRows =  table.getElementsByTag("tr");                      Elements tableRows =  table.getElementsByTag("tr");
156                                            
157                      boolean tidsstregExists = (table.getElementsByAttributeValue("class", "Tidsstreg").size() > 0);                      //boolean tidsstregExists = (table.getElementsByAttributeValue("class", "Tidsstreg").size() > 0);
158                      boolean passedTidsstreg = false;                      //boolean passedTidsstreg = false;
159                                            
160                      for (Element currentRow : tableRows) {                      for (Element currentRow : tableRows) {
161                          String rowClass = currentRow.attr("class");                          String rowClass = currentRow.attr("class");
162                                                    /*
163                          if (tidsstregExists == true && passedTidsstreg == false) {                          if (tidsstregExists == true && passedTidsstreg == false) {
164                                  if (currentRow.getElementsByAttributeValue("class", "Tidsstreg").size() > 0) {                                  if (currentRow.getElementsByAttributeValue("class", "Tidsstreg").size() > 0) {
165                                          passedTidsstreg = true;                                          passedTidsstreg = true;
166                                  } else {                                  } else {
167                                          continue;                                          continue;
168                                  }                                  }
169                          }                          }*/
170                                                    
171                          if (rowClass != null && rowClass.toLowerCase().contains("station") ) {                          if (rowClass != null && rowClass.toLowerCase().contains("station") ) {
172                                                                    
# Line 169  public class DepartureFetcher { Line 184  public class DepartureFetcher {
184                                                                    
185                                  String trainNumber = fields.get(2).text();                                  String trainNumber = fields.get(2).text();
186                                  if (type == TrainType.STOG) //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
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).text();                                  String destination = fields.get(3).text();
# Line 189  public class DepartureFetcher { Line 204  public class DepartureFetcher {
204                                                                    
205                                  departure.setType(typeString);                                  departure.setType(typeString);
206                                                                    
207                                  departureBean.departureEntries.add( departure );                                  departureBean.entries.add( departure );
208                          }                          }
209                      }                      }
210              } else {              } else {
# Line 214  public class DepartureFetcher { Line 229  public class DepartureFetcher {
229              return departureBean;              return departureBean;
230          }          }
231                    
232            
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 {          public DepartureBean lookupDeparturesWwwSite(String stationcode, TrainType trainType, boolean arrival) throws Exception {
240                                    
241                  DepartureBean departureBean = new DepartureBean();                  DepartureBean departureBean = new DepartureBean();
242                                    
243                  String type = getTypeStringWww(trainType);                  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;              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);              JsoupInvocation wrapper = new JsoupInvocation( new URL(uri), replyTimeout);
253              CircuitBreaker breaker = CircuitBreakerManager.getManager().getCircuitBreaker("banedk");              CircuitBreaker breaker = CircuitBreakerManager.getManager().getCircuitBreaker("banedk");
254                            
# Line 230  public class DepartureFetcher { Line 257  public class DepartureFetcher {
257              String tableName = arrival == false ? "afgangtabel" : "ankomsttabel";              String tableName = arrival == false ? "afgangtabel" : "ankomsttabel";
258              Element table = page.getElementById(tableName);              Element table = page.getElementById(tableName);
259                            
260    
261                
262              if (table != null) {              if (table != null) {
263                      Elements tableRows =  table.getElementsByTag("tr");                      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) {                      for (Element currentRow : tableRows) {
269                          String rowClass = currentRow.attr("class");                          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") ) {                          if (rowClass != null && rowClass.toLowerCase().contains("station") ) {
281                                  Elements fields = currentRow.getElementsByTag("td");                                  Elements fields = currentRow.getElementsByTag("td");
282                    
# Line 242  public class DepartureFetcher { Line 284  public class DepartureFetcher {
284                                                                    
285    
286                                                                    
287                                  String time = fields.get(0).getAllElements().get(2).text();                                  String time = cleanText( fields.get(0).getAllElements().get(2).text() );
288                                  if (time.equals(""))                                  if (time.equals(""))
289                                          time = "0:00"; //Bane.dk bug work-around                                          time = "0:00"; //Bane.dk bug work-around
290                                  departure.setTime(time);                                  departure.setTime(time);
# Line 250  public class DepartureFetcher { Line 292  public class DepartureFetcher {
292                                  int updated = extractUpdated( fields.get(1) );                                  int updated = extractUpdated( fields.get(1) );
293                                  departure.setUpdated(updated);                                  departure.setUpdated(updated);
294                                                                    
295                                  String trainNumber = fields.get(2).text();                                  String trainNumber = cleanText( fields.get(2).text() );
296                                  if (type.equalsIgnoreCase("S2")) //If it is S-train we need to extract the trainNumber                                  if (type.equalsIgnoreCase("S2")) //If it is S-train we need to extract the trainNumber
297                                          trainNumber = trainNumber + " " + extractTrainNumber(fields.get(2));                                          trainNumber = trainNumber + " " + extractTrainNumberWww(fields.get(2));
298                                  departure.setTrainNumber(trainNumber);                                  departure.setTrainNumber(trainNumber);
299                                                                    
300                                  String destination = fields.get(3).text();                                  String destination = cleanText( fields.get(3).text() );
301                                  departure.setDestination(destination);                                  departure.setDestination(destination);
302                                                                    
303                                  String origin = fields.get(4).text();                                  String origin = cleanText( fields.get(4).text() );
304                                  departure.setOrigin(origin);                                  departure.setOrigin(origin);
305                                                                    
306                                  String location = fields.get(5).text();                                  String location = cleanText( fields.get(5).text() );
307                                  departure.setLocation(location);                                  departure.setLocation(location);
308                                                                    
309                                  String status = fields.get(6).text().trim();                                  String status = cleanText( fields.get(6).text() );
310                                  departure.setStatus(status);                                  departure.setStatus(status);
311                                                                    
312                                  String note = extractNote( fields.get(7) );                                  String note = cleanText( extractNote( fields.get(7) ) );
313                                  departure.setNote(note);                                  departure.setNote(note);
314                                                                    
315                                  departure.setType(type);                                  departure.setType(type);
316                                                                    
317                                  departureBean.departureEntries.add(departure);                                  departureBean.entries.add(departure);
318                                                                    
319                                                                    
320                          }                          }
# Line 312  public class DepartureFetcher { Line 354  public class DepartureFetcher {
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(Element trainTd) {          private String extractTrainNumberAzure(Element trainTd) {
361                  Element anchorElement = trainTd.getElementsByTag("a").get(0);                  Element anchorElement = trainTd.getElementsByTag("a").get(0);
362                  String href = anchorElement.attr("href");                  String href = anchorElement.attr("href");
363                                    
# Line 325  public class DepartureFetcher { Line 367  public class DepartureFetcher {
367                  return number;                  return number;
368          }          }
369                    
370            private String extractTrainNumberWww(Element trainTd) {
371                    String number = "";
372                    Element anchorElement = trainTd.getElementsByTag("a").get(0);
373                    String href = anchorElement.attr("href");
374                    String argstring = href.substring( href.indexOf('?') + 1);
375                    
376                    String args[] = argstring.split("&");
377                    for (String arg : args) {
378                            String pair[] = arg.split("="); // Key=pair[0], Value=pair[1]
379                            
380                            if (pair[0].equalsIgnoreCase("TogNr"))
381                                    number = pair[1];
382                    }
383                    
384                    
385                    return number;
386            }
387    
388            
389          //test          //test
390          /*          /*
391          public static void main(String args[]) throws Exception {          public static void main(String args[]) throws Exception {

Legend:
Removed from v.1035  
changed lines
  Added in v.1252

  ViewVC Help
Powered by ViewVC 1.1.20