/[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 978 by torben, Sat Jul 10 10:53:44 2010 UTC
# Line 1  Line 1 
1  package dk.thoerup.traininfoservice.banedk;  package dk.thoerup.traininfoservice.banedk;
2    
3  import java.util.ArrayList;  
4    import java.util.Collections;
5  import java.util.List;  import java.util.List;
6    import java.util.Map;
7    import java.util.logging.Logger;
8    
9  import com.gargoylesoftware.htmlunit.ProxyConfig;  import com.gargoylesoftware.htmlunit.BrowserVersion;
10  import com.gargoylesoftware.htmlunit.WebClient;  import com.gargoylesoftware.htmlunit.WebClient;
11  import com.gargoylesoftware.htmlunit.html.DomNodeList;  import com.gargoylesoftware.htmlunit.html.DomNodeList;
12  import com.gargoylesoftware.htmlunit.html.HtmlElement;  import com.gargoylesoftware.htmlunit.html.HtmlElement;
13  import com.gargoylesoftware.htmlunit.html.HtmlPage;  import com.gargoylesoftware.htmlunit.html.HtmlPage;
14    
15    import dk.thoerup.circuitbreaker.CircuitBreaker;
16    import dk.thoerup.circuitbreaker.CircuitBreakerManager;
17    import dk.thoerup.traininfoservice.StationBean;
18    import dk.thoerup.traininfoservice.StationDAO;
19    import dk.thoerup.traininfoservice.Statistics;
20    
21  public class DepartureFetcher {  public class DepartureFetcher {
22                    
23            enum TrainType{
24                    STOG,
25                    REGIONAL
26            }
27            
28            Logger logger = Logger.getLogger(DepartureFetcher.class.getName());
29            
30            Map<String, DepartureBean> cache;
31            
32            StationDAO stationDao = new StationDAO();
33                    
34          static ProxyConfig proxyConfig;          private boolean useTempSite;
35          static {          
36                  proxyConfig = new ProxyConfig();          public DepartureFetcher(boolean tempSite, int cacheTimeout) {
37                  proxyConfig.setProxyHost("rafiki.t-hoerup.dk");                  useTempSite = tempSite;
38                  proxyConfig.setProxyPort(3128);                  cache = new TimeoutMap<String,DepartureBean>(cacheTimeout);
39          }          }
40                    
41          public List<DepartureBean> lookupDepartures() throws Exception {          
42                                    
43                  List<DepartureBean> departureList = new ArrayList<DepartureBean>();          
44            public DepartureBean cachedLookupDepartures(int stationID, boolean arrival) throws Exception {
45                    final String key = "" + stationID + ":" + arrival;
46                    /*
47                    DepartureBean departureBean = cache.get(key);
48    
49                    
50                    if (departureBean == null) {
51                            departureBean = lookupDepartures(stationID,arrival);
52                            cache.put(key, departureBean);
53                    } else {
54                            Statistics.getInstance().incrementDepartureCacheHits();
55                            logger.info("Departure: Cache hit " + key); //remove before production
56                    }
57                    return departureBean;*/
58                    
59                    return lookupDepartures(stationID,arrival);
60            }
61                    
62    
63            public DepartureBean lookupDepartures(int stationID, boolean arrival) throws Exception {
64                    
65                    DepartureBean departureBean = new DepartureBean();
66                    
67                    StationBean station = stationDao.getById(stationID);
68                    
69                    if (station.getRegional() != null) {
70                            DepartureBean tempBean = lookupDepartures(station.getRegional(), TrainType.REGIONAL, arrival);
71                            departureBean.departureEntries.addAll( tempBean.departureEntries );
72                            departureBean.notifications.addAll(tempBean.notifications);
73                    }
74                                    
75              final WebClient webClient = new WebClient();                  if (station.getStrain() != null) {
76              webClient.setTimeout(1000);                          DepartureBean tempBean = lookupDepartures(station.getStrain(), TrainType.STOG, arrival);
77              webClient.setProxyConfig(proxyConfig);                          departureBean.departureEntries.addAll( tempBean.departureEntries );
78              webClient.setJavaScriptEnabled(false);                          departureBean.notifications.addAll(tempBean.notifications);
79                                }              
80              final HtmlPage page = webClient.getPage("http://www.bane.dk/visStation.asp?ArtikelID=4275&W=FJRN&S=BJ");                  
81                                Collections.sort( departureBean.departureEntries );
82              HtmlElement table = page.getElementById("afgangtabel");  
83              DomNodeList<HtmlElement> tableRows =  table.getElementsByTagName("tr");                  
84                                return departureBean;
85              for (HtmlElement currentRow : tableRows) {          }
86                  String rowClass = currentRow.getAttribute("class");          
87                  if (rowClass != null && rowClass.toLowerCase().contains("station") ) {          public DepartureBean lookupDepartures(String stationcode, TrainType type, boolean arrival) throws Exception {
88                          DomNodeList<HtmlElement> fields = currentRow.getElementsByTagName("td");                  if (useTempSite == false) {
89                            return lookupDeparturesNormalSite(stationcode, type, arrival);
90                          DepartureBean departure = new DepartureBean();                  } else {
91                                                    //return lookupDeparturesFromTemporarySite(stationcode, type);
92                          String time = fields.get(0).asText();                          //TODO: find out what to to if they ever put a temp site up on trafikinfo.bane.dk
93                          departure.setTime(time);                          return null;
94                                            }
95                          int updated = extractUpdated( fields.get(1) );          }
96                          departure.setUpdated(updated);          
97                                    private String getTypeString(TrainType type) {
98                          String trainNumber = fields.get(2).asText();                  switch (type) {
99                          departure.setTrainNumber(trainNumber);                  case STOG:
100                                                    return "S-Tog";
101                          String destination = fields.get(3).asText();                  case REGIONAL:
102                          departure.setDestination(destination);                          return "Fjerntog";
103                                            default:
104                          String origin = fields.get(4).asText();                          return ""; //Can not happen
105                          departure.setOrigin(origin);                  }
106                                    }
107                          String location = fields.get(5).asText();          
108                          departure.setLocation(location);          public DepartureBean lookupDeparturesNormalSite(String stationcode, TrainType type, boolean arrival) throws Exception {
109                                            
110                          String status = fields.get(6).asText();                  DepartureBean departureBean = new DepartureBean();
111                          departure.setStatus(status);                  
112                                        final WebClient webClient = new WebClient( BrowserVersion.FIREFOX_3 );
113                          String note = fields.get(7).asText();              webClient.setTimeout(2500);
114                          departure.setNote(note);              webClient.setJavaScriptEnabled(false);
115                                        
116                          departureList.add(departure);              
117                String typeString = getTypeString(type);
118                String arrivalDeparture = (arrival==false) ? "Afgang" : "Ankomst";
119                                
120                //String uri = "http://www.bane.dk/visStation.asp?ArtikelID=4275&W=" + type + "&S=" + stationcode;
121                String uri = "http://trafikinfo.bane.dk/Trafikinformation/AfgangAnkomst/" + arrivalDeparture + "/" + stationcode + "/" + typeString + "/UdvidetVisning";
122    
123                //logger.info("URI: " + uri);
124                HtmlunitInvocation wrapper = new HtmlunitInvocation(webClient, uri);
125                CircuitBreaker breaker = CircuitBreakerManager.getManager().getCircuitBreaker("banedk");
126                
127                HtmlPage page = (HtmlPage) breaker.invoke(wrapper);
128                
129                String tableName = arrival == false ? "afgangtabel" : "ankomsttabel";
130                HtmlElement table = page.getElementById(tableName);
131                
132                if (table != null) {
133                        DomNodeList<HtmlElement> tableRows =  table.getElementsByTagName("tr");
134                        
135                        for (HtmlElement currentRow : tableRows) {
136                            String rowClass = currentRow.getAttribute("class");
137                            if (rowClass != null && rowClass.toLowerCase().contains("station") ) {
138                                    DomNodeList<HtmlElement> fields = currentRow.getElementsByTagName("td");
139            
140                                    DepartureEntry departure = new DepartureEntry();
141                                    
142                                    String time = fields.get(0).asText();
143                                    if (time.equals(""))
144                                            time = "0:00"; //Bane.dk bug work-around
145                                    departure.setTime(time);
146                                    
147                                    int updated = extractUpdated( fields.get(1) );
148                                    departure.setUpdated(updated);
149                                    
150                                    String trainNumber = fields.get(2).asText();
151                                    if (type == TrainType.STOG) //If it is S-train we need to extract the trainNumber
152                                            trainNumber = trainNumber + " " + extractTrainNumber(fields.get(2));
153                                    departure.setTrainNumber(trainNumber);
154                                    
155                                    String destination = fields.get(3).asText();
156                                    departure.setDestination(destination);
157                                    
158                                    String origin = fields.get(4).asText();
159                                    departure.setOrigin(origin);
160                                    
161                                    String location = fields.get(5).asText();
162                                    departure.setLocation(location);
163                                    
164                                    String status = fields.get(6).asText().trim();
165                                    departure.setStatus(status);
166                                    
167                                    String note = extractNote( fields.get(7) );
168                                    departure.setNote(note);
169                                    
170                                    departure.setType(typeString);
171                                    
172                                    departureBean.departureEntries.add( departure );
173                            }
174                        }
175                } else {
176                    logger.warning("No departures found for station=" + stationcode + ", type=" + type);
177                }
178                
179                HtmlElement notifDiv = page.getElementById("station_planlagte_text");
180                if (notifDiv != null) {
181    
182                    DomNodeList<HtmlElement> tables = notifDiv.getElementsByTagName("table");
183                    for (HtmlElement tab : tables) {
184    
185                            DomNodeList<HtmlElement> anchors = tab.getElementsByTagName("a");              
186                            if (anchors.size() == 2) {
187                                    departureBean.notifications.add(  anchors.get(1).getTextContent() );
188                            }
189                  }                  }
190                    
191              }              }
192                            
193              return departureList;              
194                webClient.closeAllWindows();
195                
196                return departureBean;
197          }          }
198                    
199            /*
200            @Deprecated
201            public List<DepartureBean> lookupDeparturesFromTemporarySite(String stationcode, String type) throws Exception {
202                    
203                    List<DepartureBean> departureList = new ArrayList<DepartureBean>();
204                    
205                final WebClient webClient = new WebClient(BrowserVersion.FIREFOX_3);
206                webClient.setTimeout(2500);
207                webClient.setJavaScriptEnabled(false);
208                
209    
210                String uri = "http://bane.dk/lite/station.asp?w=" + type + "&s=" + stationcode;
211                
212                HtmlunitInvocation wrapper = new HtmlunitInvocation(webClient, uri);
213                CircuitBreaker breaker = CircuitBreakerManager.getManager().getCircuitBreaker("banedk");
214                
215                HtmlPage page = (HtmlPage) breaker.invoke(wrapper);
216                
217                HtmlElement table = page.getElementById("traf_afgang");
218                
219                if (table != null) {                        
220                        DomNodeList<HtmlElement> tableRows =  table.getElementsByTagName("tr");
221                        
222                        boolean isFirst = true;
223                        
224                        for (HtmlElement currentRow : tableRows) {
225                            if (isFirst == true) { //skip table headers
226                                    isFirst = false;
227                                    continue;
228                            }
229                            
230                            DomNodeList<HtmlElement> fields = currentRow.getElementsByTagName("td");
231    
232                            DepartureBean departure = new DepartureBean();
233    
234                            String time = fields.get(0).asText().trim();
235    
236                            if (time.equals(""))
237                                    time = "0:00"; //Bane.dk bug work-around
238                            departure.setTime(time);
239    
240    
241                            String trainNumber = fields.get(1).asText();
242                            departure.setTrainNumber(trainNumber);
243    
244                            String destination = fields.get(2).asText();
245                            departure.setDestination(destination);
246    
247                            String origin = fields.get(3).asText();
248                            departure.setOrigin(origin);
249    
250                            String status = fields.get(4).asText();
251                            departure.setStatus(status);
252    
253                            String note = fields.get(5).asText();
254                            departure.setNote(note);
255    
256                            departureList.add(departure);
257                        }
258                } else {
259                    logger.warning("No departures found for station=" + stationcode + ", type=" + type);
260                }
261                webClient.closeAllWindows();
262                
263                
264                return departureList;
265            }*/
266    
267            
268          private int extractUpdated(HtmlElement updatedTd) { //extract the digit (in this case: 4) from "media/trafikinfo/opdater4.gif"          private int extractUpdated(HtmlElement updatedTd) { //extract the digit (in this case: 4) from "media/trafikinfo/opdater4.gif"
269                  int updated = -1;                  int updated = -1;
270                                    
# Line 89  public class DepartureFetcher { Line 283  public class DepartureFetcher {
283                  return updated;                  return updated;
284          }          }
285                    
286            private String extractNote(HtmlElement noteTd) {
287                    String note = noteTd.asText().trim();
288                    
289                    List<HtmlElement> elems = noteTd.getElementsByAttribute("span", "class", "bemtype");
290                    if (elems.size() > 0 && note.charAt(note.length()-1) == 'i')
291                            note = note.substring(0,note.length() -1 );
292    
293                    return note;
294            }
295            
296            private String extractTrainNumber(HtmlElement trainTd) {
297                    HtmlElement anchorElement = trainTd.getElementsByTagName("a").get(0);
298                    String href = anchorElement.getAttribute("href");
299                    
300                    int pos = href.lastIndexOf('/');
301                    String number = href.substring(pos+1);
302                    
303                    return number;
304            }
305            
306          //test          //test
307          public static void main(String args[]) throws Exception{          /*
308            public static void main(String args[]) throws Exception {
309                  DepartureFetcher f = new DepartureFetcher();                  DepartureFetcher f = new DepartureFetcher();
310                  List<DepartureBean> deps = f.lookupDepartures();                  List<DepartureBean> deps = f.lookupDepartures("AR", "FJRN");
311                  for(DepartureBean d : deps) {                  for(DepartureBean d : deps) {
312                          System.out.println( d.getTime() + ";" + d.getUpdated() + ";" + d.getTrainNumber() + ";" +                          System.out.println( d.getTime() + ";" + d.getUpdated() + ";" + d.getTrainNumber() + ";" +
313                                                  d.getDestination() + ";" + d.getOrigin() + ";" + d.getLocation() + ";" + d.getStatus() + ";" + d.getNote()   );                                                  d.getDestination() + ";" + d.getOrigin() + ";" + d.getLocation() + ";" + d.getStatus() + ";" + d.getNote()   );
314                  }                  }
315                                    
316                  System.out.println("--------------------------");                  System.out.println("--------------------------");
317          }          }*/
318  }  }

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

  ViewVC Help
Powered by ViewVC 1.1.20