/[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 307 by torben, Thu Sep 10 18:11:53 2009 UTC revision 1037 by torben, Sat Sep 11 07:43:09 2010 UTC
# Line 1  Line 1 
1  package dk.thoerup.traininfoservice.banedk;  package dk.thoerup.traininfoservice.banedk;
2    
3  import java.sql.Connection;  
4  import java.sql.ResultSet;  import java.net.URL;
5  import java.sql.Statement;  import java.net.URLEncoder;
 import java.util.ArrayList;  
6  import java.util.Collections;  import java.util.Collections;
7  import java.util.List;  import java.util.Map;
8    import java.util.logging.Logger;
9    
10  import com.gargoylesoftware.htmlunit.WebClient;  import org.jsoup.nodes.Document;
11  import com.gargoylesoftware.htmlunit.html.DomNodeList;  import org.jsoup.nodes.Element;
12  import com.gargoylesoftware.htmlunit.html.HtmlElement;  import org.jsoup.select.Elements;
 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    import dk.thoerup.traininfoservice.Statistics;
19    
20  public class DepartureFetcher {  public class DepartureFetcher {
21            
22            enum TrainType{
23                    STOG,
24                    REGIONAL
25            }
26            
27            Logger logger = Logger.getLogger(DepartureFetcher.class.getName());
28            
29            Map<String, DepartureBean> cache;
30            
31            StationDAO stationDao = new StationDAO();
32            
33            private boolean useAzureSite;
34            private int replyTimeout;
35            
36            public DepartureFetcher(boolean azureSite, int cacheTimeout, int replyTimeout) {
37                    this.replyTimeout = replyTimeout;
38                    useAzureSite = azureSite;
39                    cache = new TimeoutMap<String,DepartureBean>(cacheTimeout);
40            }
41            
42            
43                                    
44          @SuppressWarnings("unchecked")          
45          public List<DepartureBean> lookupDepartures(int stationID) throws Exception {          public DepartureBean cachedLookupDepartures(int stationID, boolean arrival) throws Exception {
46                  List<DepartureBean> departureList = new ArrayList<DepartureBean>();                  final String key = "" + stationID + ":" + arrival;
47                                    
48                  Connection conn = null;                  DepartureBean departureBean = cache.get(key);
49                  try  
50                  {                  
51                          conn = DBConnection.getConnection();                  if (departureBean == null) {
52                                            departureBean = lookupDepartures(stationID,arrival);
53                          String SQL = "SELECT stationcode_fjrn, stationcode_stog FROM trainstations WHERE id=" + stationID;                          cache.put(key, departureBean);
54                          Statement stmt = conn.createStatement();                  } else {
55                          ResultSet rs = stmt.executeQuery(SQL);                          Statistics.getInstance().incrementDepartureCacheHits();
56                                                    logger.info("Departure: Cache hit " + key); //remove before production
57                          if (rs.next()) {                  }
58                                  String code = rs.getString( 1 );                  return departureBean;
59                                  if (! rs.wasNull() ) {          }
60                                          List<DepartureBean> list = lookupDepartures(code, "FJRN");                  
61                                          departureList.addAll(list);  
62                                  }          public DepartureBean lookupDepartures(int stationID, boolean arrival) throws Exception {
63                                                    
64                                  code = rs.getString(2);                  DepartureBean departureBean = new DepartureBean();
65                                  if (! rs.wasNull() ) {                  
66                                          List<DepartureBean> list = lookupDepartures(code, "S2");                  StationBean station = stationDao.getById(stationID);
67                                          departureList.addAll(list);                      
68                                  }                  departureBean.stationName = station.getName();
69                                  Collections.sort( departureList );                  
70                                            if (station.getRegional() != null) {
71                          }                          DepartureBean tempBean = lookupDepartures(station.getRegional(), TrainType.REGIONAL, arrival);
72                                                    departureBean.departureEntries.addAll( tempBean.departureEntries );
73                  } finally {                          departureBean.notifications.addAll(tempBean.notifications);
74                          if (conn != null && !conn.isClosed() ) {                  }
75                                  conn.close();                  
76                          }                  if (station.getStrain() != null) {
77                            DepartureBean tempBean = lookupDepartures(station.getStrain(), TrainType.STOG, arrival);
78                            departureBean.departureEntries.addAll( tempBean.departureEntries );
79                            departureBean.notifications.addAll(tempBean.notifications);
80                    }              
81                    
82                    if (departureBean.departureEntries.size() == 0) {
83                            logger.info("No departures found for station " + stationID);
84                  }                  }
85                                    
86                  return departureList;                  Collections.sort( departureBean.departureEntries );
87    
88                    
89                    return departureBean;
90          }          }
91                    
92          public List<DepartureBean> lookupDepartures(String stationcode, String type) throws Exception {          public DepartureBean lookupDepartures(String stationcode, TrainType type, boolean arrival) throws Exception {
93                                    if (useAzureSite == true) {
94                  List<DepartureBean> departureList = new ArrayList<DepartureBean>();                          return lookupDeparturesAzureSite(stationcode, type, arrival);
95                    } else {
96                            return lookupDeparturesWwwSite(stationcode, type, arrival);
97                    }
98            }
99            
100            private String getTypeStringAzure(TrainType type) {
101                    switch (type) {
102                    case STOG:
103                            return "S-Tog";
104                    case REGIONAL:
105                            return "Fjerntog";
106                    default:
107                            return ""; //Can not happen
108                    }
109            }
110            
111            private String getTypeStringWww(TrainType type) {
112                    switch (type) {
113                    case STOG:
114                            return "S2";
115                    case REGIONAL:
116                            return "FJRN";
117                    default:
118                            return ""; //Can not happen
119                    }
120            }
121            
122            public DepartureBean lookupDeparturesAzureSite(String stationcode, TrainType type, boolean arrival) throws Exception {
123                                    
124              final WebClient webClient = new WebClient();                  DepartureBean departureBean = new DepartureBean();
125              webClient.setTimeout(1000);                  
126              webClient.setJavaScriptEnabled(false);              
127                            String typeString = getTypeStringAzure(type);
128              final HtmlPage page = webClient.getPage("http://www.bane.dk/visStation.asp?ArtikelID=4275&W=" + type + "&S=" + stationcode);              String arrivalDeparture = (arrival==false) ? "Afgang" : "Ankomst";
129                            
130              HtmlElement table = page.getElementById("afgangtabel");              stationcode = URLEncoder.encode(stationcode,"ISO-8859-1");
131              DomNodeList<HtmlElement> tableRows =  table.getElementsByTagName("tr");  
132                            String uri = "http://trafikinfo.bane.dk/Trafikinformation/AfgangAnkomst/" + arrivalDeparture + "/" + stationcode + "/" + typeString + "/UdvidetVisning";        
133              for (HtmlElement currentRow : tableRows) {              
134                  String rowClass = currentRow.getAttribute("class");              //logger.info("URI: " + uri);          
135                  if (rowClass != null && rowClass.toLowerCase().contains("station") ) {              JsoupInvocation wrapper = new JsoupInvocation( new URL(uri), replyTimeout);
136                          DomNodeList<HtmlElement> fields = currentRow.getElementsByTagName("td");              CircuitBreaker breaker = CircuitBreakerManager.getManager().getCircuitBreaker("banedk");
137                
138                          DepartureBean departure = new DepartureBean();              Document page = (Document) breaker.invoke(wrapper);
139                                        
140                          String time = fields.get(0).asText();              String tableName = arrival == false ? "afgangtabel" : "ankomsttabel";
141                          departure.setTime(time);              Element table = page.getElementById(tableName);
142                                        
143                          int updated = extractUpdated( fields.get(1) );              if (table != null) {
144                          departure.setUpdated(updated);                      Elements tableRows =  table.getElementsByTag("tr");
145                                                
146                          String trainNumber = fields.get(2).asText();                      boolean tidsstregExists = (table.getElementsByAttributeValue("class", "Tidsstreg").size() > 0);
147                          departure.setTrainNumber(trainNumber);                      boolean passedTidsstreg = false;
148                                                
149                          String destination = fields.get(3).asText();                      for (Element currentRow : tableRows) {
150                          departure.setDestination(destination);                          String rowClass = currentRow.attr("class");
151                                                    
152                          String origin = fields.get(4).asText();                          if (tidsstregExists == true && passedTidsstreg == false) {
153                          departure.setOrigin(origin);                                  if (currentRow.getElementsByAttributeValue("class", "Tidsstreg").size() > 0) {
154                                                                    passedTidsstreg = true;
155                          String location = fields.get(5).asText();                                  } else {
156                          departure.setLocation(location);                                          continue;
157                                                            }
158                          String status = fields.get(6).asText();                          }
159                          departure.setStatus(status);                          
160                                                    if (rowClass != null && rowClass.toLowerCase().contains("station") ) {
161                          String note = fields.get(7).asText();                                  
162                          departure.setNote(note);                                  Elements fields = currentRow.getElementsByTag("td");
163                                    
164                          departureList.add(departure);                                  DepartureEntry departure = new DepartureEntry();
165                                    
166                                    String time = fields.get(0).text();
167                                    if (time.equals(""))
168                                            time = "0:00"; //Bane.dk bug work-around
169                                    departure.setTime(time);
170                                    
171                                    int updated = extractUpdated( fields.get(1) );
172                                    departure.setUpdated(updated);
173                                    
174                                    String trainNumber = fields.get(2).text();
175                                    if (type == TrainType.STOG) //If it is S-train we need to extract the trainNumber
176                                            trainNumber = trainNumber + " " + extractTrainNumber(fields.get(2));
177                                    departure.setTrainNumber(trainNumber);
178                                    
179                                    String destination = fields.get(3).text();
180                                    departure.setDestination(destination);
181                                    
182                                    String origin = fields.get(4).text();
183                                    departure.setOrigin(origin);
184                                    
185                                    String location = fields.get(5).text();
186                                    departure.setLocation(location);
187                                    
188                                    String status = fields.get(6).text().trim();
189                                    departure.setStatus(status);
190                                    
191                                    String note = extractNote( fields.get(7) );
192                                    departure.setNote(note);
193                                    
194                                    departure.setType(typeString);
195                                    
196                                    departureBean.departureEntries.add( departure );
197                            }
198                        }
199                } else {
200                    logger.warning("No departures found for station=" + stationcode + ", type=" + type);
201                }
202                
203                Element notifDiv = page.getElementById("station_planlagte_text");
204                if (notifDiv != null) {
205    
206                    Elements tables = notifDiv.getElementsByTag("table");
207                    for (Element tab : tables) {
208    
209                            Elements anchors = tab.getElementsByTag("a");          
210                            if (anchors.size() == 2) {
211                                    departureBean.notifications.add(  anchors.get(1).text() );
212                            }
213                  }                  }
214                    
215                }
216                
217                
218                return departureBean;
219            }
220            
221            public DepartureBean lookupDeparturesWwwSite(String stationcode, TrainType trainType, boolean arrival) throws Exception {
222                    
223                    DepartureBean departureBean = new DepartureBean();
224                    
225                    String type = getTypeStringWww(trainType);
226                    
227                                                
228                String uri = "http://www.bane.dk/visStation.asp?ArtikelID=4275&W=" + type + "&S=" + stationcode;
229                JsoupInvocation wrapper = new JsoupInvocation( new URL(uri), replyTimeout);
230                CircuitBreaker breaker = CircuitBreakerManager.getManager().getCircuitBreaker("banedk");
231                
232                Element page = (Element) breaker.invoke(wrapper);
233                
234                String tableName = arrival == false ? "afgangtabel" : "ankomsttabel";
235                Element table = page.getElementById(tableName);
236                
237                if (table != null) {
238                        Elements tableRows =  table.getElementsByTag("tr");
239                        
240                        for (Element currentRow : tableRows) {
241                            String rowClass = currentRow.attr("class");
242                            if (rowClass != null && rowClass.toLowerCase().contains("station") ) {
243                                    Elements fields = currentRow.getElementsByTag("td");
244            
245                                    DepartureEntry departure = new DepartureEntry();
246                                    
247    
248                                    
249                                    String time = fields.get(0).getAllElements().get(2).text();
250                                    if (time.equals(""))
251                                            time = "0:00"; //Bane.dk bug work-around
252                                    departure.setTime(time);
253                                    
254                                    int updated = extractUpdated( fields.get(1) );
255                                    departure.setUpdated(updated);
256                                    
257                                    String trainNumber = fields.get(2).text();
258                                    if (type.equalsIgnoreCase("S2")) //If it is S-train we need to extract the trainNumber
259                                            trainNumber = trainNumber + " " + extractTrainNumber(fields.get(2));
260                                    departure.setTrainNumber(trainNumber);
261                                    
262                                    String destination = fields.get(3).text();
263                                    departure.setDestination(destination);
264                                    
265                                    String origin = fields.get(4).text();
266                                    departure.setOrigin(origin);
267                                    
268                                    String location = fields.get(5).text();
269                                    departure.setLocation(location);
270                                    
271                                    String status = fields.get(6).text().trim();
272                                    departure.setStatus(status);
273                                    
274                                    String note = extractNote( fields.get(7) );
275                                    departure.setNote(note);
276                                    
277                                    departure.setType(type);
278                                    
279                                    departureBean.departureEntries.add(departure);
280                                    
281                                    
282                            }
283                        }
284                } else {
285                    logger.warning("No departures found for station=" + stationcode + ", type=" + type);
286              }              }
287                            
288              return departureList;              
289                return departureBean;
290          }          }
291                    
292                    
293          private int extractUpdated(HtmlElement updatedTd) { //extract the digit (in this case: 4) from "media/trafikinfo/opdater4.gif"          private int extractUpdated(Element updatedTd) { //extract the digit (in this case: 4) from "media/trafikinfo/opdater4.gif"
294                  int updated = -1;                  int updated = -1;
295                                    
296                  DomNodeList<HtmlElement> updatedImgs = updatedTd.getElementsByTagName("img");                  Elements updatedImgs = updatedTd.getElementsByTag("img");
297                  String updatedStr = updatedImgs.get(0).getAttribute("src");                  String updatedStr = updatedImgs.get(0).attr("src");
298                                    
299                  if (updatedStr != null) {                  if (updatedStr != null) {
300                          for (int i=0; i<updatedStr.length(); i++) {                          for (int i=0; i<updatedStr.length(); i++) {
# Line 123  public class DepartureFetcher { Line 308  public class DepartureFetcher {
308                  return updated;                  return updated;
309          }          }
310                    
311            private String extractNote(Element noteTd) {
312                    String note = noteTd.text().trim();
313                    
314                    
315                    Elements elems = noteTd.getElementsByClass("bemtype");
316                    if (elems.size() > 0 && note.charAt(note.length()-1) == 'i')
317                            note = note.substring(0,note.length() -1 );
318    
319                    return note;
320            }
321            
322            private String extractTrainNumber(Element trainTd) {
323                    Element anchorElement = trainTd.getElementsByTag("a").get(0);
324                    String href = anchorElement.attr("href");
325                    
326                    int pos = href.lastIndexOf('/');
327                    String number = href.substring(pos+1);
328                    
329                    return number;
330            }
331            
332          //test          //test
333          public static void main(String args[]) throws Exception{          /*
334            public static void main(String args[]) throws Exception {
335                  DepartureFetcher f = new DepartureFetcher();                  DepartureFetcher f = new DepartureFetcher();
336                  List<DepartureBean> deps = f.lookupDepartures("AR", "FJRN");                  List<DepartureBean> deps = f.lookupDepartures("AR", "FJRN");
337                  for(DepartureBean d : deps) {                  for(DepartureBean d : deps) {
# Line 133  public class DepartureFetcher { Line 340  public class DepartureFetcher {
340                  }                  }
341                                    
342                  System.out.println("--------------------------");                  System.out.println("--------------------------");
343          }          }*/
344  }  }

Legend:
Removed from v.307  
changed lines
  Added in v.1037

  ViewVC Help
Powered by ViewVC 1.1.20