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

  ViewVC Help
Powered by ViewVC 1.1.20