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

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

  ViewVC Help
Powered by ViewVC 1.1.20