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

Legend:
Removed from v.305  
changed lines
  Added in v.1046

  ViewVC Help
Powered by ViewVC 1.1.20