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

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

  ViewVC Help
Powered by ViewVC 1.1.20