/[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 305 by torben, Thu Sep 10 09:40:27 2009 UTC revision 584 by torben, Fri Feb 5 13:57:39 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;
5    import java.sql.Statement;
6  import java.util.ArrayList;  import java.util.ArrayList;
7    import java.util.Collections;
8  import java.util.List;  import java.util.List;
9    import java.util.Map;
10    import java.util.logging.Logger;
11    
 import com.gargoylesoftware.htmlunit.ProxyConfig;  
12  import com.gargoylesoftware.htmlunit.WebClient;  import com.gargoylesoftware.htmlunit.WebClient;
13  import com.gargoylesoftware.htmlunit.html.DomNodeList;  import com.gargoylesoftware.htmlunit.html.DomNodeList;
14  import com.gargoylesoftware.htmlunit.html.HtmlElement;  import com.gargoylesoftware.htmlunit.html.HtmlElement;
15  import com.gargoylesoftware.htmlunit.html.HtmlPage;  import com.gargoylesoftware.htmlunit.html.HtmlPage;
16    
17    import dk.thoerup.circuitbreaker.CircuitBreaker;
18    import dk.thoerup.circuitbreaker.CircuitBreakerManager;
19    import dk.thoerup.traininfoservice.DBConnection;
20    
21  public class DepartureFetcher {  public class DepartureFetcher {
22                    
23            Logger logger = Logger.getLogger(DepartureFetcher.class.getName());
24            
25            Map<Integer, List<DepartureBean>> cache;
26            
27            private boolean useTempSite;
28                    
29          static ProxyConfig proxyConfig;          public DepartureFetcher(boolean tempSite, int cacheTimeout) {
30          static {                  useTempSite = tempSite;
31                  proxyConfig = new ProxyConfig();                  cache = new TimeoutMap<Integer,List<DepartureBean>>(cacheTimeout);
                 proxyConfig.setProxyHost("rafiki.t-hoerup.dk");  
                 proxyConfig.setProxyPort(3128);  
32          }          }
33                    
34          public List<DepartureBean> lookupDepartures() throws Exception {          
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 {
52                    List<DepartureBean> departureList = new ArrayList<DepartureBean>();
53                    
54                    Connection conn = null;
55                    try
56                    {
57                            conn = DBConnection.getConnection();
58                    
59                            String SQL = "SELECT stationcode_fjrn, stationcode_stog FROM trainstations WHERE id=" + stationID;
60                            Statement stmt = conn.createStatement();
61                            ResultSet rs = stmt.executeQuery(SQL);
62                            
63                            if (rs.next()) {
64                                    String code = rs.getString( 1 );
65                                    if (! rs.wasNull() ) {
66                                            List<DepartureBean> list = lookupDepartures(code, "FJRN");
67                                            departureList.addAll(list);
68                                    }
69                                    
70                                    code = rs.getString(2);
71                                    if (! rs.wasNull() ) {
72                                            List<DepartureBean> list = lookupDepartures(code, "S2");
73                                            departureList.addAll(list);    
74                                    }
75                                    Collections.sort( departureList );
76                            
77                            }
78                            
79                    } finally {
80                            if (conn != null && !conn.isClosed() ) {
81                                    conn.close();
82                            }
83                    }
84                    
85                    return departureList;
86            }
87            
88            public List<DepartureBean> lookupDepartures(String stationcode, String type) throws Exception {
89                    if (useTempSite == false) {
90                            return lookupDeparturesNormalSite(stationcode, type);
91                    } else {
92                            return lookupDeparturesFromTemporarySite(stationcode, type);
93                    }
94            }
95            
96            public List<DepartureBean> lookupDeparturesNormalSite(String stationcode, String type) throws Exception {
97                                    
98                  List<DepartureBean> departureList = new ArrayList<DepartureBean>();                  List<DepartureBean> departureList = new ArrayList<DepartureBean>();
99                                    
100              final WebClient webClient = new WebClient();              final WebClient webClient = new WebClient();
101              webClient.setTimeout(1000);              webClient.setTimeout(2500);
102              webClient.setProxyConfig(proxyConfig);              webClient.setJavaScriptEnabled(false);
103              webClient.setJavaScriptEnabled(false);                              
104                String uri = "http://www.bane.dk/visStation.asp?ArtikelID=4275&W=" + type + "&S=" + stationcode;
105                BanedkInvocation wrapper = new BanedkInvocation(webClient, uri);
106                CircuitBreaker breaker = CircuitBreakerManager.getManager().getCircuitBreaker("banedk");
107                            
108              final HtmlPage page = webClient.getPage("http://www.bane.dk/visStation.asp?ArtikelID=4275&W=FJRN&S=BJ");              HtmlPage page = (HtmlPage) breaker.invoke(wrapper);
109                            
110              HtmlElement table = page.getElementById("afgangtabel");              HtmlElement table = page.getElementById("afgangtabel");
             DomNodeList<HtmlElement> tableRows =  table.getElementsByTagName("tr");  
111                            
112              for (HtmlElement currentRow : tableRows) {              if (table != null) {
113                  String rowClass = currentRow.getAttribute("class");                      DomNodeList<HtmlElement> tableRows =  table.getElementsByTagName("tr");
114                  if (rowClass != null && rowClass.toLowerCase().contains("station") ) {                      
115                          DomNodeList<HtmlElement> fields = currentRow.getElementsByTagName("td");                      for (HtmlElement currentRow : tableRows) {
116                            String rowClass = currentRow.getAttribute("class");
117                          DepartureBean departure = new DepartureBean();                          if (rowClass != null && rowClass.toLowerCase().contains("station") ) {
118                                                            DomNodeList<HtmlElement> fields = currentRow.getElementsByTagName("td");
119                          String time = fields.get(0).asText();          
120                          departure.setTime(time);                                  DepartureBean departure = new DepartureBean();
121                                                            
122                          int updated = extractUpdated( fields.get(1) );                                  String time = fields.get(0).asText();
123                          departure.setUpdated(updated);                                  if (time.equals(""))
124                                                                    time = "0:00"; //Bane.dk bug work-around
125                          String trainNumber = fields.get(2).asText();                                  departure.setTime(time);
126                          departure.setTrainNumber(trainNumber);                                  
127                                                            int updated = extractUpdated( fields.get(1) );
128                          String destination = fields.get(3).asText();                                  departure.setUpdated(updated);
129                          departure.setDestination(destination);                                  
130                                                            String trainNumber = fields.get(2).asText();
131                          String origin = fields.get(4).asText();                                  if (type.equalsIgnoreCase("S2")) //If it is S-train we need to extract the trainNumber
132                          departure.setOrigin(origin);                                          trainNumber = trainNumber + " " + extractTrainNumber(fields.get(2));
133                                                            departure.setTrainNumber(trainNumber);
134                          String location = fields.get(5).asText();                                  
135                          departure.setLocation(location);                                  String destination = fields.get(3).asText();
136                                                            departure.setDestination(destination);
137                          String status = fields.get(6).asText();                                  
138                          departure.setStatus(status);                                  String origin = fields.get(4).asText();
139                                                            departure.setOrigin(origin);
140                          String note = fields.get(7).asText();                                  
141                          departure.setNote(note);                                  String location = fields.get(5).asText();
142                                                            departure.setLocation(location);
143                          departureList.add(departure);                                  
144                  }                                  String status = fields.get(6).asText();
145                                    departure.setStatus(status);
146                                    
147                                    String note = extractNote( fields.get(7) );
148                                    departure.setNote(note);
149                                    
150                                    departureList.add(departure);
151                            }
152                        }
153                } else {
154                    logger.warning("No departures found for station=" + stationcode + ", type=" + type);
155              }              }
156                            
157              return departureList;              return departureList;
158          }          }
159                    
160            public List<DepartureBean> lookupDeparturesFromTemporarySite(String stationcode, String type) throws Exception {
161                    
162                    List<DepartureBean> departureList = new ArrayList<DepartureBean>();
163                    
164                final WebClient webClient = new WebClient();
165                webClient.setTimeout(2500);
166                webClient.setJavaScriptEnabled(false);
167                
168    
169                String uri = "http://bane.dk/lite/station.asp?w=" + type + "&s=" + stationcode;
170                
171                BanedkInvocation wrapper = new BanedkInvocation(webClient, uri);
172                CircuitBreaker breaker = CircuitBreakerManager.getManager().getCircuitBreaker("banedk");
173                
174                HtmlPage page = (HtmlPage) breaker.invoke(wrapper);
175                
176                HtmlElement table = page.getElementById("traf_afgang");
177                
178                if (table != null) {                        
179                        DomNodeList<HtmlElement> tableRows =  table.getElementsByTagName("tr");
180                        
181                        boolean isFirst = true;
182                        
183                        for (HtmlElement currentRow : tableRows) {
184                            if (isFirst == true) { //skip table headers
185                                    isFirst = false;
186                                    continue;
187                            }
188                            
189                            DomNodeList<HtmlElement> fields = currentRow.getElementsByTagName("td");
190    
191                            DepartureBean departure = new DepartureBean();
192    
193                            String time = fields.get(0).asText().trim();
194    
195                            if (time.equals(""))
196                                    time = "0:00"; //Bane.dk bug work-around
197                            departure.setTime(time);
198    
199    
200                            String trainNumber = fields.get(1).asText();
201                            departure.setTrainNumber(trainNumber);
202    
203                            String destination = fields.get(2).asText();
204                            departure.setDestination(destination);
205    
206                            String origin = fields.get(3).asText();
207                            departure.setOrigin(origin);
208    
209                            String status = fields.get(4).asText();
210                            departure.setStatus(status);
211    
212                            String note = fields.get(5).asText();
213                            departure.setNote(note);
214    
215                            departureList.add(departure);
216                        }
217                } else {
218                    logger.warning("No departures found for station=" + stationcode + ", type=" + type);
219                }
220                
221                return departureList;
222            }
223    
224            
225          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"
226                  int updated = -1;                  int updated = -1;
227                                    
# Line 89  public class DepartureFetcher { Line 240  public class DepartureFetcher {
240                  return updated;                  return updated;
241          }          }
242                    
243            private String extractNote(HtmlElement noteTd) {
244                    String note = noteTd.asText().trim();
245                    
246                    List<HtmlElement> elems = noteTd.getElementsByAttribute("span", "class", "bemtype");
247                    if (elems.size() > 0 && note.charAt(note.length()-1) == 'i')
248                            note = note.substring(0,note.length() -1 );
249    
250                    return note;
251            }
252            
253            private String extractTrainNumber(HtmlElement trainTd) {
254                    String number = "";
255                    HtmlElement anchorElement = trainTd.getElementsByTagName("a").get(0);
256                    String href = anchorElement.getAttribute("href");
257                    String argstring = href.substring( href.indexOf('?') + 1);
258                    
259                    String args[] = argstring.split("&");
260                    for (String arg : args) {
261                            String pair[] = arg.split("="); // Key=pair[0], Value=pair[1]
262                            
263                            if (pair[0].equalsIgnoreCase("TogNr"))
264                                    number = pair[1];
265                    }
266                    
267                    
268                    
269                    return number;
270            }
271            
272          //test          //test
273          public static void main(String args[]) throws Exception{          /*
274            public static void main(String args[]) throws Exception {
275                  DepartureFetcher f = new DepartureFetcher();                  DepartureFetcher f = new DepartureFetcher();
276                  List<DepartureBean> deps = f.lookupDepartures();                  List<DepartureBean> deps = f.lookupDepartures("AR", "FJRN");
277                  for(DepartureBean d : deps) {                  for(DepartureBean d : deps) {
278                          System.out.println( d.getTime() + ";" + d.getUpdated() + ";" + d.getTrainNumber() + ";" +                          System.out.println( d.getTime() + ";" + d.getUpdated() + ";" + d.getTrainNumber() + ";" +
279                                                  d.getDestination() + ";" + d.getOrigin() + ";" + d.getLocation() + ";" + d.getStatus() + ";" + d.getNote()   );                                                  d.getDestination() + ";" + d.getOrigin() + ";" + d.getLocation() + ";" + d.getStatus() + ";" + d.getNote()   );
280                  }                  }
281                                    
282                  System.out.println("--------------------------");                  System.out.println("--------------------------");
283          }          }*/
284  }  }

Legend:
Removed from v.305  
changed lines
  Added in v.584

  ViewVC Help
Powered by ViewVC 1.1.20