/[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 308 by torben, Thu Sep 10 18:13:52 2009 UTC revision 584 by torben, Fri Feb 5 13:57:39 2010 UTC
# Line 6  import java.sql.Statement; Line 6  import java.sql.Statement;
6  import java.util.ArrayList;  import java.util.ArrayList;
7  import java.util.Collections;  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    
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;  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            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 {
# Line 55  public class DepartureFetcher { Line 86  public class DepartureFetcher {
86          }          }
87                    
88          public List<DepartureBean> lookupDepartures(String stationcode, String type) throws Exception {          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.setJavaScriptEnabled(false);              webClient.setJavaScriptEnabled(false);
103                                
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=" + type + "&S=" + stationcode);              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;
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;              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;
# Line 123  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("AR", "FJRN");                  List<DepartureBean> deps = f.lookupDepartures("AR", "FJRN");
277                  for(DepartureBean d : deps) {                  for(DepartureBean d : deps) {
# Line 133  public class DepartureFetcher { Line 280  public class DepartureFetcher {
280                  }                  }
281                                    
282                  System.out.println("--------------------------");                  System.out.println("--------------------------");
283          }          }*/
284  }  }

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

  ViewVC Help
Powered by ViewVC 1.1.20