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

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

  ViewVC Help
Powered by ViewVC 1.1.20