--- android/TrainInfo/src/dk/thoerup/traininfo/provider/XmlDepartureProvider.java 2009/08/09 17:46:09 244 +++ android/TrainInfo/src/dk/thoerup/traininfo/provider/XmlDepartureProvider.java 2009/09/12 12:33:24 320 @@ -2,6 +2,8 @@ import java.io.StringReader; import java.util.ArrayList; +import java.util.Collections; +import java.util.HashMap; import java.util.List; import javax.xml.parsers.SAXParser; @@ -19,18 +21,54 @@ public class XmlDepartureProvider extends DefaultHandler implements DepartureProvider { - ArrayList departures = new ArrayList(); + final static long CACHE_TIMEOUT = 60*1000; + class CacheEntry { + public long timestamp; + public List departures; + } + + HashMap departureCache = new HashMap(); + ArrayList departures; + DepartureBean tempDeparture; StringBuilder builder = new StringBuilder(512); @Override - public void lookupDepartures(String station) { - departures.clear(); + public boolean lookupDepartures(int stationID) { + CacheEntry entry = departureCache.get(stationID); + boolean success; + + long now = android.os.SystemClock.elapsedRealtime(); + if (entry == null || (entry.timestamp+CACHE_TIMEOUT) < now) { + + success = lookupDeparturesWorker(stationID); + + if (success) { + entry = new CacheEntry(); + entry.timestamp = android.os.SystemClock.elapsedRealtime(); + entry.departures = departures; + + departureCache.put(stationID, entry); + } + } else { + Log.i("XmlDepartureProvider", "cache hit !!!"); + success = true; + } + + return success; + } + + private boolean lookupDeparturesWorker(int stationID) { + boolean success = false; + departures = new ArrayList(); try - { String url = "http://t-hoerup.dk/tog/xml_display.php?stationname="+station; - String doc = DownloadUtil.getContent(url, 30000, "ISO-8859-1"); + { + //String url = "http://t-hoerup.dk/tog/xml_display.php?stationcode="+stationCode; + String url = "http://app.t-hoerup.dk/TrainInfoService/DepartureServlet?format=xml&station=" + stationID; + Log.i("xmlurl",url); + String doc = DownloadUtil.getContentString(url, 45000, "ISO-8859-1"); InputSource source = new InputSource( new StringReader(doc)); @@ -40,16 +78,25 @@ xr.setContentHandler(this); xr.setErrorHandler(this); - xr.setDTDHandler(this); xr.parse(source); + success = true; + } catch (Exception e) { Log.e("XmlDepartureProvider", "looupFunction", e); } + return success; } @Override - public List getDepartures() { - return departures; + public List getDepartures(int station) { + CacheEntry entry = departureCache.get(station); + + if (entry != null) { + return entry.departures; + } else { + return new ArrayList(); + } + } // this can be called several times fore the same text-node if there are many chardata / lines