/[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 588 by torben, Mon Feb 8 19:12: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    
 import com.gargoylesoftware.htmlunit.ProxyConfig;  
9  import com.gargoylesoftware.htmlunit.WebClient;  import com.gargoylesoftware.htmlunit.WebClient;
10  import com.gargoylesoftware.htmlunit.html.DomNodeList;  import com.gargoylesoftware.htmlunit.html.DomNodeList;
11  import com.gargoylesoftware.htmlunit.html.HtmlElement;  import com.gargoylesoftware.htmlunit.html.HtmlElement;
12  import com.gargoylesoftware.htmlunit.html.HtmlPage;  import com.gargoylesoftware.htmlunit.html.HtmlPage;
13    
14  import dk.thoerup.traininfoservice.DBConnection;  import dk.thoerup.circuitbreaker.CircuitBreaker;
15    import dk.thoerup.circuitbreaker.CircuitBreakerManager;
16    import dk.thoerup.traininfoservice.StationBean;
17    import dk.thoerup.traininfoservice.StationDAO;
18    
19  public class DepartureFetcher {  public class DepartureFetcher {
20            
21            Logger logger = Logger.getLogger(DepartureFetcher.class.getName());
22            
23            Map<Integer, List<DepartureBean>> cache;
24            
25            StationDAO stationDao = new StationDAO();
26            
27            private boolean useTempSite;
28            
29            public DepartureFetcher(boolean tempSite, int cacheTimeout) {
30                    useTempSite = tempSite;
31                    cache = new TimeoutMap<Integer,List<DepartureBean>>(cacheTimeout);
32            }
33            
34            
35                    
36            
37            public List<DepartureBean> cachedLookupDepartures(int stationID) throws Exception {
38    
39                    List<DepartureBean> list = cache.get(stationID);
40                    
41                    if (list == null) {
42                            list = lookupDepartures(stationID);
43                            cache.put(stationID, list);
44                    } else {
45                            logger.info("Departure: Cache hit " + stationID); //remove before production
46                    }
47                    return list;
48            }
49                                    
50    
51          public List<DepartureBean> lookupDepartures(int stationID) throws Exception {          public List<DepartureBean> lookupDepartures(int stationID) throws Exception {
52                  List<DepartureBean> departureList = new ArrayList<DepartureBean>();                  List<DepartureBean> departureList = new ArrayList<DepartureBean>();
53                                    
54                  Connection conn = null;                  StationBean station = stationDao.getById(stationID);
55                  try                  
56                  {                  if (station.getRegional() != null) {
57                          conn = DBConnection.getConnection();                          List<DepartureBean> list = lookupDepartures(station.getRegional(), "FJRN");
58                                            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();  
                         }  
59                  }                  }
60                                    
61                    if (station.getStrain() != null) {
62                            List<DepartureBean> list = lookupDepartures(station.getStrain(), "S2");
63                            departureList.addAll(list);    
64                    }              
65                    
66                    Collections.sort( departureList );
67    
68                    
69                  return departureList;                  return departureList;
70          }          }
71                    
72          public List<DepartureBean> lookupDepartures(String stationcode, String type) throws Exception {          public List<DepartureBean> lookupDepartures(String stationcode, String type) throws Exception {
73                    if (useTempSite == false) {
74                            return lookupDeparturesNormalSite(stationcode, type);
75                    } else {
76                            return lookupDeparturesFromTemporarySite(stationcode, type);
77                    }
78            }
79            
80            public List<DepartureBean> lookupDeparturesNormalSite(String stationcode, String type) throws Exception {
81                                    
82                  List<DepartureBean> departureList = new ArrayList<DepartureBean>();                  List<DepartureBean> departureList = new ArrayList<DepartureBean>();
83                                    
84              final WebClient webClient = new WebClient();              final WebClient webClient = new WebClient();
85              webClient.setTimeout(1000);              webClient.setTimeout(2500);
86              webClient.setJavaScriptEnabled(false);              webClient.setJavaScriptEnabled(false);
87                                                            
88                String uri = "http://www.bane.dk/visStation.asp?ArtikelID=4275&W=" + type + "&S=" + stationcode;
89                BanedkInvocation wrapper = new BanedkInvocation(webClient, uri);
90                CircuitBreaker breaker = CircuitBreakerManager.getManager().getCircuitBreaker("banedk");
91                            
92              final HtmlPage page = webClient.getPage("http://www.bane.dk/visStation.asp?ArtikelID=4275&W=" + type + "&S=" + stationcode);              HtmlPage page = (HtmlPage) breaker.invoke(wrapper);
93                            
94              HtmlElement table = page.getElementById("afgangtabel");              HtmlElement table = page.getElementById("afgangtabel");
             DomNodeList<HtmlElement> tableRows =  table.getElementsByTagName("tr");  
95                            
96              for (HtmlElement currentRow : tableRows) {              if (table != null) {
97                  String rowClass = currentRow.getAttribute("class");                      DomNodeList<HtmlElement> tableRows =  table.getElementsByTagName("tr");
98                  if (rowClass != null && rowClass.toLowerCase().contains("station") ) {                      
99                          DomNodeList<HtmlElement> fields = currentRow.getElementsByTagName("td");                      for (HtmlElement currentRow : tableRows) {
100                            String rowClass = currentRow.getAttribute("class");
101                          DepartureBean departure = new DepartureBean();                          if (rowClass != null && rowClass.toLowerCase().contains("station") ) {
102                                                            DomNodeList<HtmlElement> fields = currentRow.getElementsByTagName("td");
103                          String time = fields.get(0).asText();          
104                          departure.setTime(time);                                  DepartureBean departure = new DepartureBean();
105                                                            
106                          int updated = extractUpdated( fields.get(1) );                                  String time = fields.get(0).asText();
107                          departure.setUpdated(updated);                                  if (time.equals(""))
108                                                                    time = "0:00"; //Bane.dk bug work-around
109                          String trainNumber = fields.get(2).asText();                                  departure.setTime(time);
110                          departure.setTrainNumber(trainNumber);                                  
111                                                            int updated = extractUpdated( fields.get(1) );
112                          String destination = fields.get(3).asText();                                  departure.setUpdated(updated);
113                          departure.setDestination(destination);                                  
114                                                            String trainNumber = fields.get(2).asText();
115                          String origin = fields.get(4).asText();                                  if (type.equalsIgnoreCase("S2")) //If it is S-train we need to extract the trainNumber
116                          departure.setOrigin(origin);                                          trainNumber = trainNumber + " " + extractTrainNumber(fields.get(2));
117                                                            departure.setTrainNumber(trainNumber);
118                          String location = fields.get(5).asText();                                  
119                          departure.setLocation(location);                                  String destination = fields.get(3).asText();
120                                                            departure.setDestination(destination);
121                          String status = fields.get(6).asText();                                  
122                          departure.setStatus(status);                                  String origin = fields.get(4).asText();
123                                                            departure.setOrigin(origin);
124                          String note = extractNote( fields.get(7) );                                  
125                          departure.setNote(note);                                  String location = fields.get(5).asText();
126                                                            departure.setLocation(location);
127                          departureList.add(departure);                                  
128                  }                                  String status = fields.get(6).asText();
129                                    departure.setStatus(status);
130                                    
131                                    String note = extractNote( fields.get(7) );
132                                    departure.setNote(note);
133                                    
134                                    departureList.add(departure);
135                            }
136                        }
137                } else {
138                    logger.warning("No departures found for station=" + stationcode + ", type=" + type);
139                }
140                
141                return departureList;
142            }
143            
144            public List<DepartureBean> lookupDeparturesFromTemporarySite(String stationcode, String type) throws Exception {
145                    
146                    List<DepartureBean> departureList = new ArrayList<DepartureBean>();
147                    
148                final WebClient webClient = new WebClient();
149                webClient.setTimeout(2500);
150                webClient.setJavaScriptEnabled(false);
151                
152    
153                String uri = "http://bane.dk/lite/station.asp?w=" + type + "&s=" + stationcode;
154                
155                BanedkInvocation wrapper = new BanedkInvocation(webClient, uri);
156                CircuitBreaker breaker = CircuitBreakerManager.getManager().getCircuitBreaker("banedk");
157                
158                HtmlPage page = (HtmlPage) breaker.invoke(wrapper);
159                
160                HtmlElement table = page.getElementById("traf_afgang");
161                
162                if (table != null) {                        
163                        DomNodeList<HtmlElement> tableRows =  table.getElementsByTagName("tr");
164                        
165                        boolean isFirst = true;
166                        
167                        for (HtmlElement currentRow : tableRows) {
168                            if (isFirst == true) { //skip table headers
169                                    isFirst = false;
170                                    continue;
171                            }
172                            
173                            DomNodeList<HtmlElement> fields = currentRow.getElementsByTagName("td");
174    
175                            DepartureBean departure = new DepartureBean();
176    
177                            String time = fields.get(0).asText().trim();
178    
179                            if (time.equals(""))
180                                    time = "0:00"; //Bane.dk bug work-around
181                            departure.setTime(time);
182    
183    
184                            String trainNumber = fields.get(1).asText();
185                            departure.setTrainNumber(trainNumber);
186    
187                            String destination = fields.get(2).asText();
188                            departure.setDestination(destination);
189    
190                            String origin = fields.get(3).asText();
191                            departure.setOrigin(origin);
192    
193                            String status = fields.get(4).asText();
194                            departure.setStatus(status);
195    
196                            String note = fields.get(5).asText();
197                            departure.setNote(note);
198    
199                            departureList.add(departure);
200                        }
201                } else {
202                    logger.warning("No departures found for station=" + stationcode + ", type=" + type);
203              }              }
204                            
205              return departureList;              return departureList;
206          }          }
207    
208                    
209          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"
210                  int updated = -1;                  int updated = -1;
# Line 135  public class DepartureFetcher { Line 234  public class DepartureFetcher {
234                  return note;                  return note;
235          }          }
236                    
237            private String extractTrainNumber(HtmlElement trainTd) {
238                    String number = "";
239                    HtmlElement anchorElement = trainTd.getElementsByTagName("a").get(0);
240                    String href = anchorElement.getAttribute("href");
241                    String argstring = href.substring( href.indexOf('?') + 1);
242                    
243                    String args[] = argstring.split("&");
244                    for (String arg : args) {
245                            String pair[] = arg.split("="); // Key=pair[0], Value=pair[1]
246                            
247                            if (pair[0].equalsIgnoreCase("TogNr"))
248                                    number = pair[1];
249                    }
250                    
251                    
252                    
253                    return number;
254            }
255            
256          //test          //test
257          public static void main(String args[]) throws Exception{          /*
258            public static void main(String args[]) throws Exception {
259                  DepartureFetcher f = new DepartureFetcher();                  DepartureFetcher f = new DepartureFetcher();
260                  List<DepartureBean> deps = f.lookupDepartures("AR", "FJRN");                  List<DepartureBean> deps = f.lookupDepartures("AR", "FJRN");
261                  for(DepartureBean d : deps) {                  for(DepartureBean d : deps) {
# Line 145  public class DepartureFetcher { Line 264  public class DepartureFetcher {
264                  }                  }
265                                    
266                  System.out.println("--------------------------");                  System.out.println("--------------------------");
267          }          }*/
268  }  }

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

  ViewVC Help
Powered by ViewVC 1.1.20