/[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 971 by torben, Fri Jul 9 21:46:45 2010 UTC
# Line 1  Line 1 
1  package dk.thoerup.traininfoservice.banedk;  package dk.thoerup.traininfoservice.banedk;
2    
 import java.sql.Connection;  
 import java.sql.ResultSet;  
 import java.sql.Statement;  
3  import java.util.ArrayList;  import java.util.ArrayList;
4  import java.util.Collections;  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.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.traininfoservice.DBConnection;  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            Logger logger = Logger.getLogger(DepartureFetcher.class.getName());
24            
25            Map<String, List<DepartureBean>> cache;
26            
27            StationDAO stationDao = new StationDAO();
28            
29            private boolean useTempSite;
30            
31            public DepartureFetcher(boolean tempSite, int cacheTimeout) {
32                    useTempSite = tempSite;
33                    cache = new TimeoutMap<String,List<DepartureBean>>(cacheTimeout);
34            }
35            
36            
37                    
38            
39            public List<DepartureBean> cachedLookupDepartures(int stationID, boolean arrival) throws Exception {
40                    final String key = "" + stationID + ":" + arrival;
41                                    
42                    List<DepartureBean> list = cache.get(key);
43    
44          public List<DepartureBean> lookupDepartures(int stationID) throws Exception {                  
45                    if (list == null) {
46                            list = lookupDepartures(stationID,arrival);
47                            cache.put(key, list);
48                    } else {
49                            Statistics.getInstance().incrementDepartureCacheHits();
50                            logger.info("Departure: Cache hit " + key); //remove before production
51                    }
52                    return list;
53            }
54                    
55    
56            public List<DepartureBean> lookupDepartures(int stationID, boolean arrival) throws Exception {
57                  List<DepartureBean> departureList = new ArrayList<DepartureBean>();                  List<DepartureBean> departureList = new ArrayList<DepartureBean>();
58                                    
59                  Connection conn = null;                  StationBean station = stationDao.getById(stationID);
60                  try                  
61                  {                  if (station.getRegional() != null) {
62                          conn = DBConnection.getConnection();                          List<DepartureBean> list = lookupDepartures(station.getRegional(), "Fjerntog", arrival);
63                                            departureList.addAll(list);                    
                         String SQL = "SELECT stationcode_fjrn, stationcode_stog FROM trainstations WHERE id=" + stationID;  
                         Statement stmt = conn.createStatement();  
                         ResultSet rs = stmt.executeQuery(SQL);  
                           
                         if (rs.next()) {  
                                 String code = rs.getString( 1 );  
                                 if (! rs.wasNull() ) {  
                                         List<DepartureBean> list = lookupDepartures(code, "FJRN");  
                                         departureList.addAll(list);  
                                 }  
                                   
                                 code = rs.getString(2);  
                                 if (! rs.wasNull() ) {  
                                         List<DepartureBean> list = lookupDepartures(code, "S2");  
                                         departureList.addAll(list);      
                                 }  
                                 Collections.sort( departureList );  
                           
                         }  
                           
                 } finally {  
                         if (conn != null && !conn.isClosed() ) {  
                                 conn.close();  
                         }  
64                  }                  }
65                                    
66                    if (station.getStrain() != null) {
67                            List<DepartureBean> list = lookupDepartures(station.getStrain(), "S-Tog", arrival);
68                            departureList.addAll(list);    
69                    }              
70                    
71                    Collections.sort( departureList );
72    
73                    
74                  return departureList;                  return departureList;
75          }          }
76                    
77          public List<DepartureBean> lookupDepartures(String stationcode, String type) throws Exception {          public List<DepartureBean> lookupDepartures(String stationcode, String type, boolean arrival) throws Exception {
78                    if (useTempSite == false) {
79                            return lookupDeparturesNormalSite(stationcode, type, arrival);
80                    } else {
81                            return lookupDeparturesFromTemporarySite(stationcode, type);
82                    }
83            }
84            
85            public List<DepartureBean> lookupDeparturesNormalSite(String stationcode, String type, boolean arrival) throws Exception {
86                    
87                    List<DepartureBean> departureList = new ArrayList<DepartureBean>();
88                    
89                final WebClient webClient = new WebClient( BrowserVersion.FIREFOX_3 );
90                webClient.setTimeout(2500);
91                webClient.setJavaScriptEnabled(false);
92                
93                String arrivalDeparture = (arrival==false) ? "Afgang" : "Ankomst";
94                                
95                //String uri = "http://www.bane.dk/visStation.asp?ArtikelID=4275&W=" + type + "&S=" + stationcode;
96                String uri = "http://trafikinfo.bane.dk/Trafikinformation/AfgangAnkomst/" + arrivalDeparture + "/" + stationcode + "/" +type + "/UdvidetVisning";
97    
98                //logger.info("URI: " + uri);
99                HtmlunitInvocation wrapper = new HtmlunitInvocation(webClient, uri);
100                CircuitBreaker breaker = CircuitBreakerManager.getManager().getCircuitBreaker("banedk");
101                
102                HtmlPage page = (HtmlPage) breaker.invoke(wrapper);
103                
104                String tableName = arrival == false ? "afgangtabel" : "ankomsttabel";
105                HtmlElement table = page.getElementById(tableName);
106                
107                if (table != null) {
108                        DomNodeList<HtmlElement> tableRows =  table.getElementsByTagName("tr");
109                        
110                        for (HtmlElement currentRow : tableRows) {
111                            String rowClass = currentRow.getAttribute("class");
112                            if (rowClass != null && rowClass.toLowerCase().contains("station") ) {
113                                    DomNodeList<HtmlElement> fields = currentRow.getElementsByTagName("td");
114            
115                                    DepartureBean departure = new DepartureBean();
116                                    
117                                    String time = fields.get(0).asText();
118                                    if (time.equals(""))
119                                            time = "0:00"; //Bane.dk bug work-around
120                                    departure.setTime(time);
121                                    
122                                    int updated = extractUpdated( fields.get(1) );
123                                    departure.setUpdated(updated);
124                                    
125                                    String trainNumber = fields.get(2).asText();
126                                    if (type.equalsIgnoreCase("S-Tog")) //If it is S-train we need to extract the trainNumber
127                                            trainNumber = trainNumber + " " + extractTrainNumber(fields.get(2));
128                                    departure.setTrainNumber(trainNumber);
129                                    
130                                    String destination = fields.get(3).asText();
131                                    departure.setDestination(destination);
132                                    
133                                    String origin = fields.get(4).asText();
134                                    departure.setOrigin(origin);
135                                    
136                                    String location = fields.get(5).asText();
137                                    departure.setLocation(location);
138                                    
139                                    String status = fields.get(6).asText().trim();
140                                    departure.setStatus(status);
141                                    
142                                    String note = extractNote( fields.get(7) );
143                                    departure.setNote(note);
144                                    
145                                    departure.setType(type);
146                                    
147                                    departureList.add(departure);
148                            }
149                        }
150                } else {
151                    logger.warning("No departures found for station=" + stationcode + ", type=" + type);
152                }
153                webClient.closeAllWindows();
154                
155                return departureList;
156            }
157            
158            public List<DepartureBean> lookupDeparturesFromTemporarySite(String stationcode, String type) throws Exception {
159                                    
160                  List<DepartureBean> departureList = new ArrayList<DepartureBean>();                  List<DepartureBean> departureList = new ArrayList<DepartureBean>();
161                                    
162              final WebClient webClient = new WebClient();              final WebClient webClient = new WebClient(BrowserVersion.FIREFOX_3);
163              webClient.setTimeout(1000);              webClient.setTimeout(2500);
164              webClient.setJavaScriptEnabled(false);              webClient.setJavaScriptEnabled(false);
165                            
166              final HtmlPage page = webClient.getPage("http://www.bane.dk/visStation.asp?ArtikelID=4275&W=" + type + "&S=" + stationcode);  
167                            String uri = "http://bane.dk/lite/station.asp?w=" + type + "&s=" + stationcode;
168              HtmlElement table = page.getElementById("afgangtabel");              
169              DomNodeList<HtmlElement> tableRows =  table.getElementsByTagName("tr");              HtmlunitInvocation wrapper = new HtmlunitInvocation(webClient, uri);
170                            CircuitBreaker breaker = CircuitBreakerManager.getManager().getCircuitBreaker("banedk");
171              for (HtmlElement currentRow : tableRows) {              
172                  String rowClass = currentRow.getAttribute("class");              HtmlPage page = (HtmlPage) breaker.invoke(wrapper);
173                  if (rowClass != null && rowClass.toLowerCase().contains("station") ) {              
174                          DomNodeList<HtmlElement> fields = currentRow.getElementsByTagName("td");              HtmlElement table = page.getElementById("traf_afgang");
175                
176                          DepartureBean departure = new DepartureBean();              if (table != null) {                        
177                                                DomNodeList<HtmlElement> tableRows =  table.getElementsByTagName("tr");
178                          String time = fields.get(0).asText();                      
179                          departure.setTime(time);                      boolean isFirst = true;
180                                                
181                          int updated = extractUpdated( fields.get(1) );                      for (HtmlElement currentRow : tableRows) {
182                          departure.setUpdated(updated);                          if (isFirst == true) { //skip table headers
183                                                            isFirst = false;
184                          String trainNumber = fields.get(2).asText();                                  continue;
185                          departure.setTrainNumber(trainNumber);                          }
186                                                    
187                          String destination = fields.get(3).asText();                          DomNodeList<HtmlElement> fields = currentRow.getElementsByTagName("td");
188                          departure.setDestination(destination);  
189                                                    DepartureBean departure = new DepartureBean();
190                          String origin = fields.get(4).asText();  
191                          departure.setOrigin(origin);                          String time = fields.get(0).asText().trim();
192                            
193                          String location = fields.get(5).asText();                          if (time.equals(""))
194                          departure.setLocation(location);                                  time = "0:00"; //Bane.dk bug work-around
195                                                    departure.setTime(time);
196                          String status = fields.get(6).asText();  
197                          departure.setStatus(status);  
198                                                    String trainNumber = fields.get(1).asText();
199                          String note = fields.get(7).asText();                          departure.setTrainNumber(trainNumber);
200                          departure.setNote(note);  
201                                                    String destination = fields.get(2).asText();
202                          departureList.add(departure);                          departure.setDestination(destination);
203                  }  
204                            String origin = fields.get(3).asText();
205                            departure.setOrigin(origin);
206    
207                            String status = fields.get(4).asText();
208                            departure.setStatus(status);
209    
210                            String note = fields.get(5).asText();
211                            departure.setNote(note);
212    
213                            departureList.add(departure);
214                        }
215                } else {
216                    logger.warning("No departures found for station=" + stationcode + ", type=" + type);
217              }              }
218                webClient.closeAllWindows();
219                
220                            
221              return departureList;              return departureList;
222          }          }
223    
224                    
225          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"
226                  int updated = -1;                  int updated = -1;
# Line 123  public class DepartureFetcher { Line 240  public class DepartureFetcher {
240                  return updated;                  return updated;
241          }          }
242                    
243            private String extractNote(HtmlElement noteTd) {
244                    String note = noteTd.asText().trim();
245                    
246                    List<HtmlElement> elems = noteTd.getElementsByAttribute("span", "class", "bemtype");
247                    if (elems.size() > 0 && note.charAt(note.length()-1) == 'i')
248                            note = note.substring(0,note.length() -1 );
249    
250                    return note;
251            }
252            
253            private String extractTrainNumber(HtmlElement trainTd) {
254                    String number = "";
255                    HtmlElement anchorElement = trainTd.getElementsByTagName("a").get(0);
256                    String href = anchorElement.getAttribute("href");
257                    String argstring = href.substring( href.indexOf('?') + 1);
258                    
259                    String args[] = argstring.split("/");
260                    number = args[args.length-1];
261                    
262                    /*for (String arg : args) {
263                            String pair[] = arg.split("="); // Key=pair[0], Value=pair[1]
264                            
265                            if (pair[0].equalsIgnoreCase("TogNr"))
266                                    number = pair[1];
267                    }*/
268                    
269                    
270                    return number;
271            }
272            
273          //test          //test
274          public static void main(String args[]) throws Exception{          /*
275            public static void main(String args[]) throws Exception {
276                  DepartureFetcher f = new DepartureFetcher();                  DepartureFetcher f = new DepartureFetcher();
277                  List<DepartureBean> deps = f.lookupDepartures("AR", "FJRN");                  List<DepartureBean> deps = f.lookupDepartures("AR", "FJRN");
278                  for(DepartureBean d : deps) {                  for(DepartureBean d : deps) {
# Line 133  public class DepartureFetcher { Line 281  public class DepartureFetcher {
281                  }                  }
282                                    
283                  System.out.println("--------------------------");                  System.out.println("--------------------------");
284          }          }*/
285  }  }

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

  ViewVC Help
Powered by ViewVC 1.1.20