/[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 313 by torben, Fri Sep 11 07:13:46 2009 UTC revision 860 by torben, Wed Jun 16 08:57:15 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.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.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                    
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) throws Exception {          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(), "FJRN", 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(), "S2", 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>();                  List<DepartureBean> departureList = new ArrayList<DepartureBean>();
88                                    
89              final WebClient webClient = new WebClient();              final WebClient webClient = new WebClient( BrowserVersion.FIREFOX_3 );
90              webClient.setTimeout(1000);              webClient.setTimeout(2500);
91              webClient.setJavaScriptEnabled(false);              webClient.setJavaScriptEnabled(false);
92                                                            
93                String uri = "http://www.bane.dk/visStation.asp?ArtikelID=4275&W=" + type + "&S=" + stationcode;
94                BanedkInvocation wrapper = new BanedkInvocation(webClient, uri);
95                CircuitBreaker breaker = CircuitBreakerManager.getManager().getCircuitBreaker("banedk");
96                
97                HtmlPage page = (HtmlPage) breaker.invoke(wrapper);
98                
99                String tableName = arrival == false ? "afgangtabel" : "ankomsttabel";
100                HtmlElement table = page.getElementById(tableName);
101                
102                if (table != null) {
103                        DomNodeList<HtmlElement> tableRows =  table.getElementsByTagName("tr");
104                        
105                        for (HtmlElement currentRow : tableRows) {
106                            String rowClass = currentRow.getAttribute("class");
107                            if (rowClass != null && rowClass.toLowerCase().contains("station") ) {
108                                    DomNodeList<HtmlElement> fields = currentRow.getElementsByTagName("td");
109            
110                                    DepartureBean departure = new DepartureBean();
111                                    
112                                    String time = fields.get(0).asText();
113                                    if (time.equals(""))
114                                            time = "0:00"; //Bane.dk bug work-around
115                                    departure.setTime(time);
116                                    
117                                    int updated = extractUpdated( fields.get(1) );
118                                    departure.setUpdated(updated);
119                                    
120                                    String trainNumber = fields.get(2).asText();
121                                    if (type.equalsIgnoreCase("S2")) //If it is S-train we need to extract the trainNumber
122                                            trainNumber = trainNumber + " " + extractTrainNumber(fields.get(2));
123                                    departure.setTrainNumber(trainNumber);
124                                    
125                                    String destination = fields.get(3).asText();
126                                    departure.setDestination(destination);
127                                    
128                                    String origin = fields.get(4).asText();
129                                    departure.setOrigin(origin);
130                                    
131                                    String location = fields.get(5).asText();
132                                    departure.setLocation(location);
133                                    
134                                    String status = fields.get(6).asText().trim();
135                                    departure.setStatus(status);
136                                    
137                                    String note = extractNote( fields.get(7) );
138                                    departure.setNote(note);
139                                    
140                                    departure.setType(type);
141                                    
142                                    departureList.add(departure);
143                            }
144                        }
145                } else {
146                    logger.warning("No departures found for station=" + stationcode + ", type=" + type);
147                }
148                webClient.closeAllWindows();
149                            
150              final HtmlPage page = webClient.getPage("http://www.bane.dk/visStation.asp?ArtikelID=4275&W=" + type + "&S=" + stationcode);              return departureList;
151            }
152            
153            public List<DepartureBean> lookupDeparturesFromTemporarySite(String stationcode, String type) throws Exception {
154                    
155                    List<DepartureBean> departureList = new ArrayList<DepartureBean>();
156                    
157                final WebClient webClient = new WebClient(BrowserVersion.FIREFOX_3);
158                webClient.setTimeout(2500);
159                webClient.setJavaScriptEnabled(false);
160                            
161              HtmlElement table = page.getElementById("afgangtabel");  
162              DomNodeList<HtmlElement> tableRows =  table.getElementsByTagName("tr");              String uri = "http://bane.dk/lite/station.asp?w=" + type + "&s=" + stationcode;
163                
164                BanedkInvocation wrapper = new BanedkInvocation(webClient, uri);
165                CircuitBreaker breaker = CircuitBreakerManager.getManager().getCircuitBreaker("banedk");
166                
167                HtmlPage page = (HtmlPage) breaker.invoke(wrapper);
168                
169                HtmlElement table = page.getElementById("traf_afgang");
170                            
171              for (HtmlElement currentRow : tableRows) {              if (table != null) {                        
172                  String rowClass = currentRow.getAttribute("class");                      DomNodeList<HtmlElement> tableRows =  table.getElementsByTagName("tr");
173                  if (rowClass != null && rowClass.toLowerCase().contains("station") ) {                      
174                          DomNodeList<HtmlElement> fields = currentRow.getElementsByTagName("td");                      boolean isFirst = true;
175                        
176                          DepartureBean departure = new DepartureBean();                      for (HtmlElement currentRow : tableRows) {
177                                                    if (isFirst == true) { //skip table headers
178                          String time = fields.get(0).asText();                                  isFirst = false;
179                          departure.setTime(time);                                  continue;
180                                                    }
181                          int updated = extractUpdated( fields.get(1) );                          
182                          departure.setUpdated(updated);                          DomNodeList<HtmlElement> fields = currentRow.getElementsByTagName("td");
183                            
184                          String trainNumber = fields.get(2).asText();                          DepartureBean departure = new DepartureBean();
185                          departure.setTrainNumber(trainNumber);  
186                                                    String time = fields.get(0).asText().trim();
187                          String destination = fields.get(3).asText();  
188                          departure.setDestination(destination);                          if (time.equals(""))
189                                                            time = "0:00"; //Bane.dk bug work-around
190                          String origin = fields.get(4).asText();                          departure.setTime(time);
191                          departure.setOrigin(origin);  
192                            
193                          String location = fields.get(5).asText();                          String trainNumber = fields.get(1).asText();
194                          departure.setLocation(location);                          departure.setTrainNumber(trainNumber);
195                            
196                          String status = fields.get(6).asText();                          String destination = fields.get(2).asText();
197                          departure.setStatus(status);                          departure.setDestination(destination);
198                            
199                          String note = extractNote( fields.get(7) );                          String origin = fields.get(3).asText();
200                          departure.setNote(note);                          departure.setOrigin(origin);
201                            
202                          departureList.add(departure);                          String status = fields.get(4).asText();
203                  }                          departure.setStatus(status);
204    
205                            String note = fields.get(5).asText();
206                            departure.setNote(note);
207    
208                            departureList.add(departure);
209                        }
210                } else {
211                    logger.warning("No departures found for station=" + stationcode + ", type=" + type);
212              }              }
213                webClient.closeAllWindows();
214                
215                            
216              return departureList;              return departureList;
217          }          }
218    
219                    
220          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"
221                  int updated = -1;                  int updated = -1;
# Line 135  public class DepartureFetcher { Line 245  public class DepartureFetcher {
245                  return note;                  return note;
246          }          }
247                    
248            private String extractTrainNumber(HtmlElement trainTd) {
249                    String number = "";
250                    HtmlElement anchorElement = trainTd.getElementsByTagName("a").get(0);
251                    String href = anchorElement.getAttribute("href");
252                    String argstring = href.substring( href.indexOf('?') + 1);
253                    
254                    String args[] = argstring.split("&");
255                    for (String arg : args) {
256                            String pair[] = arg.split("="); // Key=pair[0], Value=pair[1]
257                            
258                            if (pair[0].equalsIgnoreCase("TogNr"))
259                                    number = pair[1];
260                    }
261                    
262                    
263                    return number;
264            }
265            
266          //test          //test
267          public static void main(String args[]) throws Exception{          /*
268            public static void main(String args[]) throws Exception {
269                  DepartureFetcher f = new DepartureFetcher();                  DepartureFetcher f = new DepartureFetcher();
270                  List<DepartureBean> deps = f.lookupDepartures("AR", "FJRN");                  List<DepartureBean> deps = f.lookupDepartures("AR", "FJRN");
271                  for(DepartureBean d : deps) {                  for(DepartureBean d : deps) {
# Line 145  public class DepartureFetcher { Line 274  public class DepartureFetcher {
274                  }                  }
275                                    
276                  System.out.println("--------------------------");                  System.out.println("--------------------------");
277          }          }*/
278  }  }

Legend:
Removed from v.313  
changed lines
  Added in v.860

  ViewVC Help
Powered by ViewVC 1.1.20