1 |
package dk.thoerup.traininfoservice.banedk; |
package dk.thoerup.traininfoservice.banedk; |
2 |
|
|
3 |
import java.sql.Connection; |
|
4 |
import java.sql.ResultSet; |
import java.net.URL; |
5 |
import java.sql.Statement; |
import java.net.URLEncoder; |
|
import java.util.ArrayList; |
|
6 |
import java.util.Collections; |
import java.util.Collections; |
|
import java.util.List; |
|
7 |
import java.util.Map; |
import java.util.Map; |
8 |
import java.util.logging.Logger; |
import java.util.logging.Logger; |
9 |
|
|
10 |
import com.gargoylesoftware.htmlunit.WebClient; |
import org.jsoup.nodes.Document; |
11 |
import com.gargoylesoftware.htmlunit.html.DomNodeList; |
import org.jsoup.nodes.Element; |
12 |
import com.gargoylesoftware.htmlunit.html.HtmlElement; |
import org.jsoup.select.Elements; |
|
import com.gargoylesoftware.htmlunit.html.HtmlPage; |
|
13 |
|
|
14 |
import dk.thoerup.circuitbreaker.CircuitBreaker; |
import dk.thoerup.circuitbreaker.CircuitBreaker; |
15 |
import dk.thoerup.circuitbreaker.CircuitBreakerManager; |
import dk.thoerup.circuitbreaker.CircuitBreakerManager; |
16 |
import dk.thoerup.traininfoservice.DBConnection; |
import dk.thoerup.traininfoservice.StationBean; |
17 |
|
import dk.thoerup.traininfoservice.StationDAO; |
18 |
|
import dk.thoerup.traininfoservice.Statistics; |
19 |
|
|
20 |
public class DepartureFetcher { |
public class DepartureFetcher { |
21 |
|
|
22 |
|
enum TrainType{ |
23 |
|
STOG, |
24 |
|
REGIONAL |
25 |
|
} |
26 |
|
|
27 |
Logger logger = Logger.getLogger(DepartureFetcher.class.getName()); |
Logger logger = Logger.getLogger(DepartureFetcher.class.getName()); |
28 |
|
|
29 |
Map<Integer, List<DepartureBean>> cache = new TimeoutMap<Integer,List<DepartureBean>>(120 * 1000); |
Map<String, DepartureBean> cache; |
30 |
|
|
31 |
|
StationDAO stationDao = new StationDAO(); |
32 |
|
|
33 |
private boolean useTempSite; |
private boolean useTempSite; |
34 |
|
|
35 |
public DepartureFetcher(boolean tempSite) { |
public DepartureFetcher(boolean tempSite, int cacheTimeout) { |
36 |
useTempSite = tempSite; |
useTempSite = tempSite; |
37 |
|
cache = new TimeoutMap<String,DepartureBean>(cacheTimeout); |
38 |
} |
} |
39 |
|
|
40 |
|
|
41 |
|
|
42 |
|
|
43 |
public List<DepartureBean> cachedLookupDepartures(int stationID) throws Exception { |
public DepartureBean cachedLookupDepartures(int stationID, boolean arrival) throws Exception { |
44 |
|
final String key = "" + stationID + ":" + arrival; |
45 |
|
|
46 |
|
DepartureBean departureBean = cache.get(key); |
47 |
|
|
|
List<DepartureBean> list = cache.get(stationID); |
|
48 |
|
|
49 |
if (list == null) { |
if (departureBean == null) { |
50 |
list = lookupDepartures(stationID); |
departureBean = lookupDepartures(stationID,arrival); |
51 |
cache.put(stationID, list); |
cache.put(key, departureBean); |
52 |
} else { |
} else { |
53 |
logger.info("Departure: Cache hit " + stationID); //remove before production |
Statistics.getInstance().incrementDepartureCacheHits(); |
54 |
|
logger.info("Departure: Cache hit " + key); //remove before production |
55 |
} |
} |
56 |
return list; |
return departureBean; |
57 |
} |
} |
58 |
|
|
59 |
|
|
60 |
public List<DepartureBean> lookupDepartures(int stationID) throws Exception { |
public DepartureBean lookupDepartures(int stationID, boolean arrival) throws Exception { |
|
List<DepartureBean> departureList = new ArrayList<DepartureBean>(); |
|
61 |
|
|
62 |
Connection conn = null; |
DepartureBean departureBean = new DepartureBean(); |
63 |
try |
|
64 |
{ |
StationBean station = stationDao.getById(stationID); |
65 |
conn = DBConnection.getConnection(); |
|
66 |
|
if (station.getRegional() != null) { |
67 |
String SQL = "SELECT stationcode_fjrn, stationcode_stog FROM trainstations WHERE id=" + stationID; |
DepartureBean tempBean = lookupDepartures(station.getRegional(), TrainType.REGIONAL, arrival); |
68 |
Statement stmt = conn.createStatement(); |
departureBean.departureEntries.addAll( tempBean.departureEntries ); |
69 |
ResultSet rs = stmt.executeQuery(SQL); |
departureBean.notifications.addAll(tempBean.notifications); |
|
|
|
|
if (rs.next()) { |
|
|
String code = rs.getString( 1 ); |
|
|
if (! rs.wasNull() ) { |
|
|
List<DepartureBean> list = lookupDepartures(code, "FJRN"); |
|
|
departureList.addAll(list); |
|
|
} |
|
|
|
|
|
code = rs.getString(2); |
|
|
if (! rs.wasNull() ) { |
|
|
List<DepartureBean> list = lookupDepartures(code, "S2"); |
|
|
departureList.addAll(list); |
|
|
} |
|
|
Collections.sort( departureList ); |
|
|
|
|
|
} |
|
|
|
|
|
} finally { |
|
|
if (conn != null && !conn.isClosed() ) { |
|
|
conn.close(); |
|
|
} |
|
70 |
} |
} |
71 |
|
|
72 |
return departureList; |
if (station.getStrain() != null) { |
73 |
|
DepartureBean tempBean = lookupDepartures(station.getStrain(), TrainType.STOG, arrival); |
74 |
|
departureBean.departureEntries.addAll( tempBean.departureEntries ); |
75 |
|
departureBean.notifications.addAll(tempBean.notifications); |
76 |
|
} |
77 |
|
|
78 |
|
Collections.sort( departureBean.departureEntries ); |
79 |
|
|
80 |
|
|
81 |
|
return departureBean; |
82 |
} |
} |
83 |
|
|
84 |
public List<DepartureBean> lookupDepartures(String stationcode, String type) throws Exception { |
public DepartureBean lookupDepartures(String stationcode, TrainType type, boolean arrival) throws Exception { |
85 |
if (useTempSite == false) { |
if (useTempSite == false) { |
86 |
return lookupDeparturesNormalSite(stationcode, type); |
return lookupDeparturesNormalSite(stationcode, type, arrival); |
87 |
} else { |
} else { |
88 |
return lookupDeparturesFromTemporarySite(stationcode, type); |
//return lookupDeparturesFromTemporarySite(stationcode, type); |
89 |
|
//TODO: find out what to to if they ever put a temp site up on trafikinfo.bane.dk |
90 |
|
return null; |
91 |
} |
} |
92 |
} |
} |
93 |
|
|
94 |
public List<DepartureBean> lookupDeparturesNormalSite(String stationcode, String type) throws Exception { |
private String getTypeString(TrainType type) { |
95 |
|
switch (type) { |
96 |
List<DepartureBean> departureList = new ArrayList<DepartureBean>(); |
case STOG: |
97 |
|
return "S-Tog"; |
98 |
|
case REGIONAL: |
99 |
|
return "Fjerntog"; |
100 |
|
default: |
101 |
|
return ""; //Can not happen |
102 |
|
} |
103 |
|
} |
104 |
|
|
105 |
|
public DepartureBean lookupDeparturesNormalSite(String stationcode, TrainType type, boolean arrival) throws Exception { |
106 |
|
|
107 |
final WebClient webClient = new WebClient(); |
DepartureBean departureBean = new DepartureBean(); |
108 |
webClient.setTimeout(2500); |
|
109 |
webClient.setJavaScriptEnabled(false); |
|
110 |
|
String typeString = getTypeString(type); |
111 |
String uri = "http://www.bane.dk/visStation.asp?ArtikelID=4275&W=" + type + "&S=" + stationcode; |
String arrivalDeparture = (arrival==false) ? "Afgang" : "Ankomst"; |
112 |
BanedkInvocation wrapper = new BanedkInvocation(webClient, uri); |
|
113 |
|
stationcode = URLEncoder.encode(stationcode,"ISO-8859-1"); |
114 |
|
//String uri = "http://www.bane.dk/visStation.asp?ArtikelID=4275&W=" + type + "&S=" + stationcode; |
115 |
|
String uri = "http://trafikinfo.bane.dk/Trafikinformation/AfgangAnkomst/" + arrivalDeparture + "/" + stationcode + "/" + typeString + "/UdvidetVisning"; |
116 |
|
|
117 |
|
|
118 |
|
|
119 |
|
//logger.info("URI: " + uri); |
120 |
|
JsoupInvocation wrapper = new JsoupInvocation( new URL(uri), 2500); |
121 |
CircuitBreaker breaker = CircuitBreakerManager.getManager().getCircuitBreaker("banedk"); |
CircuitBreaker breaker = CircuitBreakerManager.getManager().getCircuitBreaker("banedk"); |
122 |
|
|
123 |
HtmlPage page = (HtmlPage) breaker.invoke(wrapper); |
Document page = (Document) breaker.invoke(wrapper); |
124 |
|
|
125 |
HtmlElement table = page.getElementById("afgangtabel"); |
String tableName = arrival == false ? "afgangtabel" : "ankomsttabel"; |
126 |
|
Element table = page.getElementById(tableName); |
127 |
|
|
128 |
if (table != null) { |
if (table != null) { |
129 |
DomNodeList<HtmlElement> tableRows = table.getElementsByTagName("tr"); |
Elements tableRows = table.getElementsByTag("tr"); |
130 |
|
|
131 |
for (HtmlElement currentRow : tableRows) { |
boolean tidsstregExists = (table.getElementsByAttributeValue("class", "Tidsstreg").size() > 0); |
132 |
String rowClass = currentRow.getAttribute("class"); |
boolean passedTidsstreg = false; |
133 |
|
|
134 |
|
for (Element currentRow : tableRows) { |
135 |
|
String rowClass = currentRow.attr("class"); |
136 |
|
|
137 |
|
if (tidsstregExists == true && passedTidsstreg == false) { |
138 |
|
if (currentRow.getElementsByAttributeValue("class", "Tidsstreg").size() > 0) { |
139 |
|
passedTidsstreg = true; |
140 |
|
} else { |
141 |
|
continue; |
142 |
|
} |
143 |
|
} |
144 |
|
|
145 |
if (rowClass != null && rowClass.toLowerCase().contains("station") ) { |
if (rowClass != null && rowClass.toLowerCase().contains("station") ) { |
146 |
DomNodeList<HtmlElement> fields = currentRow.getElementsByTagName("td"); |
|
147 |
|
Elements fields = currentRow.getElementsByTag("td"); |
148 |
|
|
149 |
DepartureBean departure = new DepartureBean(); |
DepartureEntry departure = new DepartureEntry(); |
150 |
|
|
151 |
String time = fields.get(0).asText(); |
String time = fields.get(0).text(); |
152 |
if (time.equals("")) |
if (time.equals("")) |
153 |
time = "0:00"; //Bane.dk bug work-around |
time = "0:00"; //Bane.dk bug work-around |
154 |
departure.setTime(time); |
departure.setTime(time); |
156 |
int updated = extractUpdated( fields.get(1) ); |
int updated = extractUpdated( fields.get(1) ); |
157 |
departure.setUpdated(updated); |
departure.setUpdated(updated); |
158 |
|
|
159 |
String trainNumber = fields.get(2).asText(); |
String trainNumber = fields.get(2).text(); |
160 |
if (type.equalsIgnoreCase("S2")) //If it is S-train we need to extract the trainNumber |
if (type == TrainType.STOG) //If it is S-train we need to extract the trainNumber |
161 |
trainNumber = trainNumber + " " + extractTrainNumber(fields.get(2)); |
trainNumber = trainNumber + " " + extractTrainNumber(fields.get(2)); |
162 |
departure.setTrainNumber(trainNumber); |
departure.setTrainNumber(trainNumber); |
163 |
|
|
164 |
String destination = fields.get(3).asText(); |
String destination = fields.get(3).text(); |
165 |
departure.setDestination(destination); |
departure.setDestination(destination); |
166 |
|
|
167 |
String origin = fields.get(4).asText(); |
String origin = fields.get(4).text(); |
168 |
departure.setOrigin(origin); |
departure.setOrigin(origin); |
169 |
|
|
170 |
String location = fields.get(5).asText(); |
String location = fields.get(5).text(); |
171 |
departure.setLocation(location); |
departure.setLocation(location); |
172 |
|
|
173 |
String status = fields.get(6).asText(); |
String status = fields.get(6).text().trim(); |
174 |
departure.setStatus(status); |
departure.setStatus(status); |
175 |
|
|
176 |
String note = extractNote( fields.get(7) ); |
String note = extractNote( fields.get(7) ); |
177 |
departure.setNote(note); |
departure.setNote(note); |
178 |
|
|
179 |
departureList.add(departure); |
departure.setType(typeString); |
180 |
|
|
181 |
|
departureBean.departureEntries.add( departure ); |
182 |
} |
} |
183 |
} |
} |
184 |
} else { |
} else { |
185 |
logger.warning("No departures found for station=" + stationcode + ", type=" + type); |
logger.warning("No departures found for station=" + stationcode + ", type=" + type); |
186 |
} |
} |
187 |
|
|
188 |
return departureList; |
Element notifDiv = page.getElementById("station_planlagte_text"); |
189 |
|
if (notifDiv != null) { |
190 |
|
|
191 |
|
Elements tables = notifDiv.getElementsByTag("table"); |
192 |
|
for (Element tab : tables) { |
193 |
|
|
194 |
|
Elements anchors = tab.getElementsByTag("a"); |
195 |
|
if (anchors.size() == 2) { |
196 |
|
departureBean.notifications.add( anchors.get(1).text() ); |
197 |
|
} |
198 |
|
} |
199 |
|
|
200 |
|
} |
201 |
|
|
202 |
|
|
203 |
|
return departureBean; |
204 |
} |
} |
205 |
|
|
206 |
|
/* |
207 |
|
@Deprecated |
208 |
public List<DepartureBean> lookupDeparturesFromTemporarySite(String stationcode, String type) throws Exception { |
public List<DepartureBean> lookupDeparturesFromTemporarySite(String stationcode, String type) throws Exception { |
209 |
|
|
210 |
List<DepartureBean> departureList = new ArrayList<DepartureBean>(); |
List<DepartureBean> departureList = new ArrayList<DepartureBean>(); |
211 |
|
|
212 |
final WebClient webClient = new WebClient(); |
final WebClient webClient = new WebClient(BrowserVersion.FIREFOX_3); |
213 |
webClient.setTimeout(2500); |
webClient.setTimeout(2500); |
214 |
webClient.setJavaScriptEnabled(false); |
webClient.setJavaScriptEnabled(false); |
215 |
|
|
216 |
|
|
217 |
String uri = "http://bane.dk/lite/station.asp?w=" + type + "&s=" + stationcode; |
String uri = "http://bane.dk/lite/station.asp?w=" + type + "&s=" + stationcode; |
218 |
|
|
219 |
BanedkInvocation wrapper = new BanedkInvocation(webClient, uri); |
HtmlunitInvocation wrapper = new HtmlunitInvocation(webClient, uri); |
220 |
CircuitBreaker breaker = CircuitBreakerManager.getManager().getCircuitBreaker("banedk"); |
CircuitBreaker breaker = CircuitBreakerManager.getManager().getCircuitBreaker("banedk"); |
221 |
|
|
222 |
HtmlPage page = (HtmlPage) breaker.invoke(wrapper); |
HtmlPage page = (HtmlPage) breaker.invoke(wrapper); |
265 |
} else { |
} else { |
266 |
logger.warning("No departures found for station=" + stationcode + ", type=" + type); |
logger.warning("No departures found for station=" + stationcode + ", type=" + type); |
267 |
} |
} |
268 |
|
webClient.closeAllWindows(); |
269 |
|
|
270 |
|
|
271 |
return departureList; |
return departureList; |
272 |
} |
}*/ |
273 |
|
|
274 |
|
|
275 |
private int extractUpdated(HtmlElement updatedTd) { //extract the digit (in this case: 4) from "media/trafikinfo/opdater4.gif" |
private int extractUpdated(Element updatedTd) { //extract the digit (in this case: 4) from "media/trafikinfo/opdater4.gif" |
276 |
int updated = -1; |
int updated = -1; |
277 |
|
|
278 |
DomNodeList<HtmlElement> updatedImgs = updatedTd.getElementsByTagName("img"); |
Elements updatedImgs = updatedTd.getElementsByTag("img"); |
279 |
String updatedStr = updatedImgs.get(0).getAttribute("src"); |
String updatedStr = updatedImgs.get(0).attr("src"); |
280 |
|
|
281 |
if (updatedStr != null) { |
if (updatedStr != null) { |
282 |
for (int i=0; i<updatedStr.length(); i++) { |
for (int i=0; i<updatedStr.length(); i++) { |
290 |
return updated; |
return updated; |
291 |
} |
} |
292 |
|
|
293 |
private String extractNote(HtmlElement noteTd) { |
private String extractNote(Element noteTd) { |
294 |
String note = noteTd.asText().trim(); |
String note = noteTd.text().trim(); |
295 |
|
|
296 |
List<HtmlElement> elems = noteTd.getElementsByAttribute("span", "class", "bemtype"); |
|
297 |
|
Elements elems = noteTd.getElementsByClass("bemtype"); |
298 |
if (elems.size() > 0 && note.charAt(note.length()-1) == 'i') |
if (elems.size() > 0 && note.charAt(note.length()-1) == 'i') |
299 |
note = note.substring(0,note.length() -1 ); |
note = note.substring(0,note.length() -1 ); |
300 |
|
|
301 |
return note; |
return note; |
302 |
} |
} |
303 |
|
|
304 |
private String extractTrainNumber(HtmlElement trainTd) { |
private String extractTrainNumber(Element trainTd) { |
305 |
String number = ""; |
Element anchorElement = trainTd.getElementsByTag("a").get(0); |
306 |
HtmlElement anchorElement = trainTd.getElementsByTagName("a").get(0); |
String href = anchorElement.attr("href"); |
|
String href = anchorElement.getAttribute("href"); |
|
|
String argstring = href.substring( href.indexOf('?') + 1); |
|
|
|
|
|
String args[] = argstring.split("&"); |
|
|
for (String arg : args) { |
|
|
String pair[] = arg.split("="); // Key=pair[0], Value=pair[1] |
|
|
|
|
|
if (pair[0].equalsIgnoreCase("TogNr")) |
|
|
number = pair[1]; |
|
|
} |
|
|
|
|
307 |
|
|
308 |
|
int pos = href.lastIndexOf('/'); |
309 |
|
String number = href.substring(pos+1); |
310 |
|
|
311 |
return number; |
return number; |
312 |
} |
} |