/[projects]/android/TrainInfoService/src/dk/thoerup/traininfoservice/banedk/DepartureFetcher.java
ViewVC logotype

Annotation of /android/TrainInfoService/src/dk/thoerup/traininfoservice/banedk/DepartureFetcher.java

Parent Directory Parent Directory | Revision Log Revision Log


Revision 421 - (hide annotations) (download)
Thu Oct 8 12:19:42 2009 UTC (14 years, 7 months ago) by torben
File size: 6566 byte(s)
Enabled the usage of Circuit breaker to guard agains bane.dk failures
1 torben 305 package dk.thoerup.traininfoservice.banedk;
2    
3 torben 307 import java.sql.Connection;
4     import java.sql.ResultSet;
5     import java.sql.Statement;
6 torben 305 import java.util.ArrayList;
7 torben 307 import java.util.Collections;
8 torben 305 import java.util.List;
9 torben 348 import java.util.logging.Logger;
10 torben 305
11     import com.gargoylesoftware.htmlunit.WebClient;
12     import com.gargoylesoftware.htmlunit.html.DomNodeList;
13     import com.gargoylesoftware.htmlunit.html.HtmlElement;
14     import com.gargoylesoftware.htmlunit.html.HtmlPage;
15    
16 torben 421 import dk.thoerup.curcuitbreaker.CircuitBreaker;
17     import dk.thoerup.curcuitbreaker.CircuitBreakerManager;
18 torben 307 import dk.thoerup.traininfoservice.DBConnection;
19    
20 torben 305 public class DepartureFetcher {
21 torben 348
22     Logger logger = Logger.getLogger(DepartureFetcher.class.getName());
23 torben 387
24     TimeoutCache<Integer, List<DepartureBean>> cache = new TimeoutCache<Integer,List<DepartureBean>>(120 * 1000);
25    
26 torben 307
27 torben 387
28 torben 421 public List<DepartureBean> cachedLookupDepartures(int stationID) throws Throwable {
29 torben 308
30 torben 387 List<DepartureBean> list = cache.get(stationID);
31    
32     if (list == null) {
33     list = lookupDepartures(stationID);
34     cache.put(stationID, list);
35     } else {
36 torben 389 logger.info("Departure: Cache hit " + stationID); //remove before production
37 torben 387 }
38     return list;
39     }
40    
41    
42 torben 421 public List<DepartureBean> lookupDepartures(int stationID) throws Throwable {
43 torben 307 List<DepartureBean> departureList = new ArrayList<DepartureBean>();
44    
45     Connection conn = null;
46     try
47     {
48     conn = DBConnection.getConnection();
49    
50     String SQL = "SELECT stationcode_fjrn, stationcode_stog FROM trainstations WHERE id=" + stationID;
51     Statement stmt = conn.createStatement();
52     ResultSet rs = stmt.executeQuery(SQL);
53    
54     if (rs.next()) {
55     String code = rs.getString( 1 );
56     if (! rs.wasNull() ) {
57     List<DepartureBean> list = lookupDepartures(code, "FJRN");
58     departureList.addAll(list);
59     }
60    
61     code = rs.getString(2);
62     if (! rs.wasNull() ) {
63     List<DepartureBean> list = lookupDepartures(code, "S2");
64     departureList.addAll(list);
65     }
66     Collections.sort( departureList );
67    
68     }
69    
70     } finally {
71     if (conn != null && !conn.isClosed() ) {
72     conn.close();
73     }
74     }
75    
76     return departureList;
77 torben 305 }
78    
79 torben 421 public List<DepartureBean> lookupDepartures(String stationcode, String type) throws Throwable {
80 torben 305
81     List<DepartureBean> departureList = new ArrayList<DepartureBean>();
82    
83     final WebClient webClient = new WebClient();
84 torben 386 webClient.setTimeout(2500);
85 torben 313 webClient.setJavaScriptEnabled(false);
86    
87 torben 421 String uri = "http://www.bane.dk/visStation.asp?ArtikelID=4275&W=" + type + "&S=" + stationcode;
88     BanedkInvocation wrapper = new BanedkInvocation(webClient, uri);
89     CircuitBreaker breaker = CircuitBreakerManager.getManager().getCircuitBreaker("banedk");
90 torben 305
91 torben 421 HtmlPage page = (HtmlPage) breaker.invoke(wrapper);
92 torben 305
93     HtmlElement table = page.getElementById("afgangtabel");
94    
95 torben 342 if (table != null) {
96     DomNodeList<HtmlElement> tableRows = table.getElementsByTagName("tr");
97    
98     for (HtmlElement currentRow : tableRows) {
99     String rowClass = currentRow.getAttribute("class");
100     if (rowClass != null && rowClass.toLowerCase().contains("station") ) {
101     DomNodeList<HtmlElement> fields = currentRow.getElementsByTagName("td");
102    
103     DepartureBean departure = new DepartureBean();
104    
105     String time = fields.get(0).asText();
106 torben 375 if (time.equals(""))
107     time = "0:00"; //Bane.dk bug work-around
108 torben 342 departure.setTime(time);
109    
110     int updated = extractUpdated( fields.get(1) );
111     departure.setUpdated(updated);
112    
113     String trainNumber = fields.get(2).asText();
114 torben 410 if (type.equalsIgnoreCase("S2")) //If it is S-train we need to extract the trainNumber
115 torben 349 trainNumber = trainNumber + " " + extractTrainNumber(fields.get(2));
116 torben 342 departure.setTrainNumber(trainNumber);
117    
118     String destination = fields.get(3).asText();
119     departure.setDestination(destination);
120    
121     String origin = fields.get(4).asText();
122     departure.setOrigin(origin);
123    
124     String location = fields.get(5).asText();
125     departure.setLocation(location);
126    
127     String status = fields.get(6).asText();
128     departure.setStatus(status);
129    
130     String note = extractNote( fields.get(7) );
131     departure.setNote(note);
132    
133     departureList.add(departure);
134     }
135     }
136 torben 348 } else {
137     logger.warning("No departures found for station=" + stationcode + ", type=" + type);
138 torben 305 }
139 torben 348
140 torben 305 return departureList;
141     }
142    
143     private int extractUpdated(HtmlElement updatedTd) { //extract the digit (in this case: 4) from "media/trafikinfo/opdater4.gif"
144     int updated = -1;
145    
146     DomNodeList<HtmlElement> updatedImgs = updatedTd.getElementsByTagName("img");
147     String updatedStr = updatedImgs.get(0).getAttribute("src");
148    
149     if (updatedStr != null) {
150     for (int i=0; i<updatedStr.length(); i++) {
151     char c = updatedStr.charAt(i);
152     if ( Character.isDigit(c)) {
153     updated = Character.digit(c, 10);
154     break;
155     }
156     }
157     }
158     return updated;
159     }
160    
161 torben 313 private String extractNote(HtmlElement noteTd) {
162     String note = noteTd.asText().trim();
163    
164     List<HtmlElement> elems = noteTd.getElementsByAttribute("span", "class", "bemtype");
165     if (elems.size() > 0 && note.charAt(note.length()-1) == 'i')
166     note = note.substring(0,note.length() -1 );
167    
168     return note;
169     }
170    
171 torben 349 private String extractTrainNumber(HtmlElement trainTd) {
172     String number = "";
173     HtmlElement anchorElement = trainTd.getElementsByTagName("a").get(0);
174     String href = anchorElement.getAttribute("href");
175     String argstring = href.substring( href.indexOf('?') + 1);
176    
177     String args[] = argstring.split("&");
178     for (String arg : args) {
179     String pair[] = arg.split("="); // Key=pair[0], Value=pair[1]
180    
181     if (pair[0].equalsIgnoreCase("TogNr"))
182     number = pair[1];
183     }
184    
185    
186    
187     return number;
188     }
189    
190 torben 305 //test
191 torben 421 public static void main(String args[]) throws Throwable {
192 torben 305 DepartureFetcher f = new DepartureFetcher();
193 torben 307 List<DepartureBean> deps = f.lookupDepartures("AR", "FJRN");
194 torben 305 for(DepartureBean d : deps) {
195     System.out.println( d.getTime() + ";" + d.getUpdated() + ";" + d.getTrainNumber() + ";" +
196     d.getDestination() + ";" + d.getOrigin() + ";" + d.getLocation() + ";" + d.getStatus() + ";" + d.getNote() );
197     }
198    
199     System.out.println("--------------------------");
200     }
201     }

  ViewVC Help
Powered by ViewVC 1.1.20