/[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 349 by torben, Mon Sep 28 19:14:18 2009 UTC revision 711 by torben, Wed May 5 20:11:03 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;  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());          Logger logger = Logger.getLogger(DepartureFetcher.class.getName());
24            
25            Map<Integer, 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<Integer,List<DepartureBean>>(cacheTimeout);
34            }
35            
36            
37                    
38            
39            public List<DepartureBean> cachedLookupDepartures(int stationID) throws Exception {
40    
41                    List<DepartureBean> list = cache.get(stationID);
42                    
43                    if (list == null) {
44                            list = lookupDepartures(stationID);
45                            cache.put(stationID, list);
46                    } else {
47                            Statistics.getInstance().incrementDepartureCacheHits();
48                            logger.info("Departure: Cache hit " + stationID); //remove before production
49                    }
50                    return list;
51            }
52                                    
53    
54          public List<DepartureBean> lookupDepartures(int stationID) throws Exception {          public List<DepartureBean> lookupDepartures(int stationID) throws Exception {
55                  List<DepartureBean> departureList = new ArrayList<DepartureBean>();                  List<DepartureBean> departureList = new ArrayList<DepartureBean>();
56                                    
57                  Connection conn = null;                  StationBean station = stationDao.getById(stationID);
58                  try                  
59                  {                  if (station.getRegional() != null) {
60                          conn = DBConnection.getConnection();                          List<DepartureBean> list = lookupDepartures(station.getRegional(), "FJRN");
61                                            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();  
                         }  
62                  }                  }
63                                    
64                    if (station.getStrain() != null) {
65                            List<DepartureBean> list = lookupDepartures(station.getStrain(), "S2");
66                            departureList.addAll(list);    
67                    }              
68                    
69                    Collections.sort( departureList );
70    
71                    
72                  return departureList;                  return departureList;
73          }          }
74                    
75          public List<DepartureBean> lookupDepartures(String stationcode, String type) throws Exception {          public List<DepartureBean> lookupDepartures(String stationcode, String type) throws Exception {
76                    if (useTempSite == false) {
77                            return lookupDeparturesNormalSite(stationcode, type);
78                    } else {
79                            return lookupDeparturesFromTemporarySite(stationcode, type);
80                    }
81            }
82            
83            public List<DepartureBean> lookupDeparturesNormalSite(String stationcode, String type) throws Exception {
84                                    
85                  List<DepartureBean> departureList = new ArrayList<DepartureBean>();                  List<DepartureBean> departureList = new ArrayList<DepartureBean>();
86                                    
87              final WebClient webClient = new WebClient();              final WebClient webClient = new WebClient( BrowserVersion.FIREFOX_3 );
88              webClient.setTimeout(1000);              webClient.setTimeout(2500);
89              webClient.setJavaScriptEnabled(false);              webClient.setJavaScriptEnabled(false);
90                                                            
91                String uri = "http://www.bane.dk/visStation.asp?ArtikelID=4275&W=" + type + "&S=" + stationcode;
92                BanedkInvocation wrapper = new BanedkInvocation(webClient, uri);
93                CircuitBreaker breaker = CircuitBreakerManager.getManager().getCircuitBreaker("banedk");
94                            
95              final HtmlPage page = webClient.getPage("http://www.bane.dk/visStation.asp?ArtikelID=4275&W=" + type + "&S=" + stationcode);              HtmlPage page = (HtmlPage) breaker.invoke(wrapper);
96                            
97              HtmlElement table = page.getElementById("afgangtabel");              HtmlElement table = page.getElementById("afgangtabel");
98                            
# Line 82  public class DepartureFetcher { Line 107  public class DepartureFetcher {
107                                  DepartureBean departure = new DepartureBean();                                  DepartureBean departure = new DepartureBean();
108                                                                    
109                                  String time = fields.get(0).asText();                                  String time = fields.get(0).asText();
110                                    if (time.equals(""))
111                                            time = "0:00"; //Bane.dk bug work-around
112                                  departure.setTime(time);                                  departure.setTime(time);
113                                                                    
114                                  int updated = extractUpdated( fields.get(1) );                                  int updated = extractUpdated( fields.get(1) );
115                                  departure.setUpdated(updated);                                  departure.setUpdated(updated);
116                                                                    
117                                  String trainNumber = fields.get(2).asText();                                  String trainNumber = fields.get(2).asText();
118                                  if (trainNumber.trim().length() == 1)                                  if (type.equalsIgnoreCase("S2")) //If it is S-train we need to extract the trainNumber
119                                          trainNumber = trainNumber + " " + extractTrainNumber(fields.get(2));                                          trainNumber = trainNumber + " " + extractTrainNumber(fields.get(2));
120                                  departure.setTrainNumber(trainNumber);                                  departure.setTrainNumber(trainNumber);
121                                                                    
# Line 107  public class DepartureFetcher { Line 134  public class DepartureFetcher {
134                                  String note = extractNote( fields.get(7) );                                  String note = extractNote( fields.get(7) );
135                                  departure.setNote(note);                                  departure.setNote(note);
136                                                                    
137                                    departure.setType(type);
138                                    
139                                  departureList.add(departure);                                  departureList.add(departure);
140                          }                          }
141                      }                      }
142              } else {              } else {
143                  logger.warning("No departures found for station=" + stationcode + ", type=" + type);                  logger.warning("No departures found for station=" + stationcode + ", type=" + type);
144              }              }
145                webClient.closeAllWindows();
146                
147                return departureList;
148            }
149            
150            public List<DepartureBean> lookupDeparturesFromTemporarySite(String stationcode, String type) throws Exception {
151                    
152                    List<DepartureBean> departureList = new ArrayList<DepartureBean>();
153                    
154                final WebClient webClient = new WebClient(BrowserVersion.FIREFOX_3);
155                webClient.setTimeout(2500);
156                webClient.setJavaScriptEnabled(false);
157                
158    
159                String uri = "http://bane.dk/lite/station.asp?w=" + type + "&s=" + stationcode;
160                
161                BanedkInvocation wrapper = new BanedkInvocation(webClient, uri);
162                CircuitBreaker breaker = CircuitBreakerManager.getManager().getCircuitBreaker("banedk");
163                
164                HtmlPage page = (HtmlPage) breaker.invoke(wrapper);
165                
166                HtmlElement table = page.getElementById("traf_afgang");
167                
168                if (table != null) {                        
169                        DomNodeList<HtmlElement> tableRows =  table.getElementsByTagName("tr");
170                        
171                        boolean isFirst = true;
172                        
173                        for (HtmlElement currentRow : tableRows) {
174                            if (isFirst == true) { //skip table headers
175                                    isFirst = false;
176                                    continue;
177                            }
178                            
179                            DomNodeList<HtmlElement> fields = currentRow.getElementsByTagName("td");
180    
181                            DepartureBean departure = new DepartureBean();
182    
183                            String time = fields.get(0).asText().trim();
184    
185                            if (time.equals(""))
186                                    time = "0:00"; //Bane.dk bug work-around
187                            departure.setTime(time);
188    
189    
190                            String trainNumber = fields.get(1).asText();
191                            departure.setTrainNumber(trainNumber);
192    
193                            String destination = fields.get(2).asText();
194                            departure.setDestination(destination);
195    
196                            String origin = fields.get(3).asText();
197                            departure.setOrigin(origin);
198    
199                            String status = fields.get(4).asText();
200                            departure.setStatus(status);
201    
202                            String note = fields.get(5).asText();
203                            departure.setNote(note);
204    
205                            departureList.add(departure);
206                        }
207                } else {
208                    logger.warning("No departures found for station=" + stationcode + ", type=" + type);
209                }
210                webClient.closeAllWindows();
211                
212                            
213              return departureList;              return departureList;
214          }          }
215    
216                    
217          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"
218                  int updated = -1;                  int updated = -1;
# Line 160  public class DepartureFetcher { Line 257  public class DepartureFetcher {
257                  }                  }
258                                    
259                                    
                   
260                  return number;                  return number;
261          }          }
262                    
263          //test          //test
264          public static void main(String args[]) throws Exception{          /*
265            public static void main(String args[]) throws Exception {
266                  DepartureFetcher f = new DepartureFetcher();                  DepartureFetcher f = new DepartureFetcher();
267                  List<DepartureBean> deps = f.lookupDepartures("AR", "FJRN");                  List<DepartureBean> deps = f.lookupDepartures("AR", "FJRN");
268                  for(DepartureBean d : deps) {                  for(DepartureBean d : deps) {
# Line 174  public class DepartureFetcher { Line 271  public class DepartureFetcher {
271                  }                  }
272                                    
273                  System.out.println("--------------------------");                  System.out.println("--------------------------");
274          }          }*/
275  }  }

Legend:
Removed from v.349  
changed lines
  Added in v.711

  ViewVC Help
Powered by ViewVC 1.1.20