--- android/TrainInfoService/src/dk/thoerup/traininfoservice/banedk/DepartureFetcher.java 2009/09/24 20:20:49 342 +++ android/TrainInfoService/src/dk/thoerup/traininfoservice/banedk/DepartureFetcher.java 2009/10/02 17:18:31 389 @@ -6,8 +6,9 @@ import java.util.ArrayList; import java.util.Collections; import java.util.List; +import java.util.logging.Logger; + -import com.gargoylesoftware.htmlunit.ProxyConfig; import com.gargoylesoftware.htmlunit.WebClient; import com.gargoylesoftware.htmlunit.html.DomNodeList; import com.gargoylesoftware.htmlunit.html.HtmlElement; @@ -16,6 +17,25 @@ import dk.thoerup.traininfoservice.DBConnection; public class DepartureFetcher { + + Logger logger = Logger.getLogger(DepartureFetcher.class.getName()); + + TimeoutCache> cache = new TimeoutCache>(120 * 1000); + + + + public List cachedLookupDepartures(int stationID) throws Exception { + + List list = cache.get(stationID); + + if (list == null) { + list = lookupDepartures(stationID); + cache.put(stationID, list); + } else { + logger.info("Departure: Cache hit " + stationID); //remove before production + } + return list; + } public List lookupDepartures(int stationID) throws Exception { @@ -60,7 +80,7 @@ List departureList = new ArrayList(); final WebClient webClient = new WebClient(); - webClient.setTimeout(1000); + webClient.setTimeout(2500); webClient.setJavaScriptEnabled(false); @@ -79,12 +99,16 @@ DepartureBean departure = new DepartureBean(); String time = fields.get(0).asText(); + if (time.equals("")) + time = "0:00"; //Bane.dk bug work-around departure.setTime(time); int updated = extractUpdated( fields.get(1) ); departure.setUpdated(updated); String trainNumber = fields.get(2).asText(); + if (trainNumber.trim().length() == 1) + trainNumber = trainNumber + " " + extractTrainNumber(fields.get(2)); departure.setTrainNumber(trainNumber); String destination = fields.get(3).asText(); @@ -105,7 +129,10 @@ departureList.add(departure); } } + } else { + logger.warning("No departures found for station=" + stationcode + ", type=" + type); } + return departureList; } @@ -137,6 +164,25 @@ return note; } + private String extractTrainNumber(HtmlElement trainTd) { + String number = ""; + HtmlElement anchorElement = trainTd.getElementsByTagName("a").get(0); + 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]; + } + + + + return number; + } + //test public static void main(String args[]) throws Exception{ DepartureFetcher f = new DepartureFetcher();