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

  ViewVC Help
Powered by ViewVC 1.1.20