package dk.thoerup.traininfoservice.banedk; import java.net.URL; import java.sql.SQLException; import java.util.Map; import java.util.logging.Level; import java.util.logging.Logger; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import org.jsoup.select.Elements; import dk.thoerup.android.traininfo.common.TimetableBean; import dk.thoerup.android.traininfo.common.TimetableEntry; import dk.thoerup.circuitbreaker.CircuitBreaker; import dk.thoerup.circuitbreaker.CircuitBreakerManager; import dk.thoerup.traininfoservice.Statistics; import dk.thoerup.traininfoservice.TraininfoSettings; import dk.thoerup.traininfoservice.db.StationDAO; public class TimetableFetcher { Map cache; Map stationCache; StationDAO stationDao = new StationDAO(); Logger logger = Logger.getLogger(TimetableFetcher.class.getName()); TraininfoSettings settings; public TimetableFetcher(TraininfoSettings settings) { this.settings = settings; cache = new TimeoutMap( settings.getCacheTimeout() ); stationCache = new TimeoutMap( 3*60*60*1000 ); } TimetableBean cachedLookupTimetable(String trainID, String type) throws Exception { String key = trainID+type; TimetableBean list = cache.get(key); if (list == null) { list = lookupTimetable(trainID,type); cache.put(key, list); } else { Statistics.getInstance().incrementTimetableCacheHits(); logger.info("Timetable: Cache hit " + trainID); } return list; } TimetableBean lookupTimetable(String trainID, String type) throws Exception { if (settings.getUseAzureSite() == true ){ return lookupTimetableAzureSite(trainID, type); } else { return lookupTimetableMobileSite(trainID, type); } } int getStationId(String name) { Integer id = stationCache.get(name); if (id == null) { try { id = stationDao.getIdByName(name); stationCache.put(name, id); } catch (SQLException e) { logger.log(Level.SEVERE, "getStationId failed", e); id = -1; } } return id; } TimetableBean lookupTimetableAzureSite(String trainID, String type) throws Exception { TimetableBean timetableBean = new TimetableBean(); String url = "http://trafikinfo.bane.dk/TrafikInformation/Ruteplan/" + trainID; logger.fine("URL:" + url); JsoupInvocation wrapper = new JsoupInvocation( new URL(url) , settings.getReplyTimeout() ); CircuitBreaker breaker = CircuitBreakerManager.getManager().getCircuitBreaker("banedk"); Document doc = (Document) breaker.invoke(wrapper); boolean currentStation = false; boolean currentStationSaved = false; Elements tables = doc.getElementsByClass("Rute"); if (tables.size() == 1) { Element timetable = tables.get(0); Elements rows = timetable.getElementsByTag("tr"); for (int i=0; i0 && i