/* * Copyright 2010-2015 the original author or authors. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ package de.schildbach.pte; import static com.google.common.base.Preconditions.checkState; import java.io.IOException; import java.io.InputStream; import java.nio.charset.Charset; import java.util.ArrayList; import java.util.Calendar; import java.util.Collection; import java.util.Currency; import java.util.Date; import java.util.EnumSet; import java.util.GregorianCalendar; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Set; import java.util.concurrent.atomic.AtomicReference; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import org.xmlpull.v1.XmlPullParser; import org.xmlpull.v1.XmlPullParserException; import org.xmlpull.v1.XmlPullParserFactory; import com.google.common.base.Charsets; import de.schildbach.pte.dto.Departure; import de.schildbach.pte.dto.Fare; import de.schildbach.pte.dto.Fare.Type; import de.schildbach.pte.dto.Line; import de.schildbach.pte.dto.LineDestination; import de.schildbach.pte.dto.Location; import de.schildbach.pte.dto.LocationType; import de.schildbach.pte.dto.NearbyLocationsResult; import de.schildbach.pte.dto.Point; import de.schildbach.pte.dto.Position; import de.schildbach.pte.dto.Product; import de.schildbach.pte.dto.QueryDeparturesResult; import de.schildbach.pte.dto.QueryTripsContext; import de.schildbach.pte.dto.QueryTripsResult; import de.schildbach.pte.dto.ResultHeader; import de.schildbach.pte.dto.StationDepartures; import de.schildbach.pte.dto.Stop; import de.schildbach.pte.dto.SuggestLocationsResult; import de.schildbach.pte.dto.SuggestedLocation; import de.schildbach.pte.dto.Trip; import de.schildbach.pte.exception.InvalidDataException; import de.schildbach.pte.exception.ParserException; import de.schildbach.pte.util.ParserUtils; import de.schildbach.pte.util.XmlPullUtil; /** * @author Andreas Schildbach */ public abstract class AbstractEfaProvider extends AbstractNetworkProvider { protected static final String DEFAULT_DEPARTURE_MONITOR_ENDPOINT = "XSLT_DM_REQUEST"; protected static final String DEFAULT_TRIP_ENDPOINT = "XSLT_TRIP_REQUEST2"; protected static final String DEFAULT_STOPFINDER_ENDPOINT = "XML_STOPFINDER_REQUEST"; protected static final String DEFAULT_COORD_ENDPOINT = "XML_COORD_REQUEST"; protected static final String SERVER_PRODUCT = "efa"; private final String departureMonitorEndpoint; private final String tripEndpoint; private final String stopFinderEndpoint; private final String coordEndpoint; private String language = "de"; private String additionalQueryParameter = null; private boolean useRealtime = true; private boolean needsSpEncId = false; private boolean includeRegionId = true; private boolean useProxFootSearch = true; private Charset requestUrlEncoding = Charsets.ISO_8859_1; private String httpReferer = null; private String httpRefererTrip = null; private boolean httpPost = false; private boolean useRouteIndexAsTripId = true; private boolean useLineRestriction = true; private boolean useStringCoordListOutputFormat = true; private float fareCorrectionFactor = 1f; private final XmlPullParserFactory parserFactory; private static class Context implements QueryTripsContext { private final String context; private Context(final String context) { this.context = context; } public boolean canQueryLater() { return context != null; } public boolean canQueryEarlier() { return false; // TODO enable earlier querying } @Override public String toString() { return getClass().getName() + "[" + context + "]"; } } public AbstractEfaProvider(final String apiBase) { this(apiBase, null, null, null, null); } public AbstractEfaProvider(final String apiBase, final String departureMonitorEndpoint, final String tripEndpoint, final String stopFinderEndpoint, final String coordEndpoint) { this(apiBase + (departureMonitorEndpoint != null ? departureMonitorEndpoint : DEFAULT_DEPARTURE_MONITOR_ENDPOINT), // apiBase + (tripEndpoint != null ? tripEndpoint : DEFAULT_TRIP_ENDPOINT), // apiBase + (stopFinderEndpoint != null ? stopFinderEndpoint : DEFAULT_STOPFINDER_ENDPOINT), // apiBase + (coordEndpoint != null ? coordEndpoint : DEFAULT_COORD_ENDPOINT)); } public AbstractEfaProvider(final String departureMonitorEndpoint, final String tripEndpoint, final String stopFinderEndpoint, final String coordEndpoint) { try { parserFactory = XmlPullParserFactory.newInstance(System.getProperty(XmlPullParserFactory.PROPERTY_NAME), null); } catch (final XmlPullParserException x) { throw new RuntimeException(x); } this.departureMonitorEndpoint = departureMonitorEndpoint; this.tripEndpoint = tripEndpoint; this.stopFinderEndpoint = stopFinderEndpoint; this.coordEndpoint = coordEndpoint; } protected void setLanguage(final String language) { this.language = language; } protected void setAdditionalQueryParameter(final String additionalQueryParameter) { this.additionalQueryParameter = additionalQueryParameter; } protected void setRequestUrlEncoding(final Charset requestUrlEncoding) { this.requestUrlEncoding = requestUrlEncoding; } protected void setHttpReferer(final String httpReferer) { this.httpReferer = httpReferer; this.httpRefererTrip = httpReferer; } public void setHttpRefererTrip(final String httpRefererTrip) { this.httpRefererTrip = httpRefererTrip; } protected void setHttpPost(final boolean httpPost) { this.httpPost = httpPost; } protected void setUseRealtime(final boolean useRealtime) { this.useRealtime = useRealtime; } protected void setIncludeRegionId(final boolean includeRegionId) { this.includeRegionId = includeRegionId; } protected void setUseProxFootSearch(final boolean useProxFootSearch) { this.useProxFootSearch = useProxFootSearch; } protected void setUseRouteIndexAsTripId(final boolean useRouteIndexAsTripId) { this.useRouteIndexAsTripId = useRouteIndexAsTripId; } protected void setUseLineRestriction(final boolean useLineRestriction) { this.useLineRestriction = useLineRestriction; } protected void setUseStringCoordListOutputFormat(final boolean useStringCoordListOutputFormat) { this.useStringCoordListOutputFormat = useStringCoordListOutputFormat; } protected void setNeedsSpEncId(final boolean needsSpEncId) { this.needsSpEncId = needsSpEncId; } protected void setFareCorrectionFactor(final float fareCorrectionFactor) { this.fareCorrectionFactor = fareCorrectionFactor; } @Override protected boolean hasCapability(final Capability capability) { return true; } private final void appendCommonRequestParams(final StringBuilder uri, final String outputFormat) { uri.append("?outputFormat=").append(outputFormat); uri.append("&language=").append(language); uri.append("&stateless=1"); uri.append("&coordOutputFormat=WGS84"); if (additionalQueryParameter != null) uri.append('&').append(additionalQueryParameter); } protected SuggestLocationsResult jsonStopfinderRequest(final Location constraint) throws IOException { final StringBuilder parameters = stopfinderRequestParameters(constraint, "JSON"); final StringBuilder uri = new StringBuilder(stopFinderEndpoint); if (!httpPost) uri.append(parameters); // System.out.println(uri); // System.out.println(parameters); final CharSequence page = ParserUtils.scrape(uri.toString(), httpPost ? parameters.substring(1) : null, Charsets.UTF_8); final ResultHeader header = new ResultHeader(SERVER_PRODUCT); try { final List locations = new ArrayList(); final JSONObject head = new JSONObject(page.toString()); final JSONObject stopFinder = head.optJSONObject("stopFinder"); final JSONArray stops; if (stopFinder == null) { stops = head.getJSONArray("stopFinder"); } else { final JSONObject points = stopFinder.optJSONObject("points"); if (points != null) { final JSONObject stop = points.getJSONObject("point"); final SuggestedLocation location = parseJsonStop(stop); locations.add(location); return new SuggestLocationsResult(header, locations); } stops = stopFinder.optJSONArray("points"); if (stops == null) return new SuggestLocationsResult(header, locations); } final int nStops = stops.length(); for (int i = 0; i < nStops; i++) { final JSONObject stop = stops.optJSONObject(i); final SuggestedLocation location = parseJsonStop(stop); locations.add(location); } return new SuggestLocationsResult(header, locations); } catch (final JSONException x) { throw new RuntimeException("cannot parse: '" + page + "' on " + uri, x); } } private SuggestedLocation parseJsonStop(final JSONObject stop) throws JSONException { String type = stop.getString("type"); if ("any".equals(type)) type = stop.getString("anyType"); final String id = stop.getString("stateless"); final String name = normalizeLocationName(stop.optString("name")); final String object = normalizeLocationName(stop.optString("object")); final String postcode = stop.optString("postcode"); final int quality = stop.getInt("quality"); final JSONObject ref = stop.getJSONObject("ref"); String place = ref.getString("place"); if (place != null && place.length() == 0) place = null; final Point coord = parseCoord(ref.optString("coords", null)); final Location location; if ("stop".equals(type)) location = new Location(LocationType.STATION, id, coord, place, object); else if ("poi".equals(type)) location = new Location(LocationType.POI, id, coord, place, object); else if ("crossing".equals(type)) location = new Location(LocationType.ADDRESS, id, coord, place, object); else if ("street".equals(type) || "address".equals(type) || "singlehouse".equals(type) || "buildingname".equals(type)) location = new Location(LocationType.ADDRESS, id, coord, place, name); else if ("postcode".equals(type)) location = new Location(LocationType.ADDRESS, id, coord, place, postcode); else throw new JSONException("unknown type: " + type); return new SuggestedLocation(location, quality); } private StringBuilder stopfinderRequestParameters(final Location constraint, final String outputFormat) { final StringBuilder parameters = new StringBuilder(); appendCommonRequestParams(parameters, outputFormat); parameters.append("&locationServerActive=1"); if (includeRegionId) parameters.append("®ionID_sf=1"); // prefer own region appendLocation(parameters, constraint, "sf"); if (constraint.type == LocationType.ANY) { if (needsSpEncId) parameters.append("&SpEncId=0"); // 1=place 2=stop 4=street 8=address 16=crossing 32=poi 64=postcode parameters.append("&anyObjFilter_sf=").append(2 + 4 + 8 + 16 + 32 + 64); parameters.append("&reducedAnyPostcodeObjFilter_sf=64&reducedAnyTooManyObjFilter_sf=2"); parameters.append("&useHouseNumberList=true"); parameters.append("&anyMaxSizeHitList=500"); } return parameters; } protected SuggestLocationsResult xmlStopfinderRequest(final Location constraint) throws IOException { final StringBuilder parameters = stopfinderRequestParameters(constraint, "XML"); final StringBuilder uri = new StringBuilder(stopFinderEndpoint); if (!httpPost) uri.append(parameters); // System.out.println(uri); // System.out.println(parameters); InputStream is = null; String firstChars = null; try { is = ParserUtils.scrapeInputStream(uri.toString(), httpPost ? parameters.substring(1) : null, null, httpReferer, null); firstChars = ParserUtils.peekFirstChars(is); final XmlPullParser pp = parserFactory.newPullParser(); pp.setInput(is, null); final ResultHeader header = enterItdRequest(pp); final List locations = new ArrayList(); XmlPullUtil.enter(pp, "itdStopFinderRequest"); processItdOdv(pp, "sf", new ProcessItdOdvCallback() { public void location(final String nameState, final Location location, final int matchQuality) { locations.add(new SuggestedLocation(location, matchQuality)); } }); XmlPullUtil.skipExit(pp, "itdStopFinderRequest"); return new SuggestLocationsResult(header, locations); } catch (final XmlPullParserException x) { throw new ParserException("cannot parse xml: " + firstChars, x); } finally { if (is != null) is.close(); } } protected SuggestLocationsResult mobileStopfinderRequest(final Location constraint) throws IOException { final StringBuilder parameters = stopfinderRequestParameters(constraint, "XML"); final StringBuilder uri = new StringBuilder(stopFinderEndpoint); if (!httpPost) uri.append(parameters); // System.out.println(uri); // System.out.println(parameters); InputStream is = null; String firstChars = null; try { is = ParserUtils.scrapeInputStream(uri.toString(), httpPost ? parameters.substring(1) : null, null, httpReferer, null); firstChars = ParserUtils.peekFirstChars(is); final XmlPullParser pp = parserFactory.newPullParser(); pp.setInput(is, null); final ResultHeader header = enterEfa(pp); final List locations = new ArrayList(); XmlPullUtil.require(pp, "sf"); if (!pp.isEmptyElementTag()) { XmlPullUtil.enter(pp, "sf"); while (XmlPullUtil.test(pp, "p")) { XmlPullUtil.enter(pp, "p"); final String name = normalizeLocationName(XmlPullUtil.valueTag(pp, "n")); final String u = XmlPullUtil.valueTag(pp, "u"); if (!"sf".equals(u)) throw new RuntimeException("unknown usage: " + u); final String ty = XmlPullUtil.valueTag(pp, "ty"); final LocationType type; if ("stop".equals(ty)) type = LocationType.STATION; else if ("poi".equals(ty)) type = LocationType.POI; else if ("loc".equals(ty)) type = LocationType.ADDRESS; else if ("street".equals(ty)) type = LocationType.ADDRESS; else if ("singlehouse".equals(ty)) type = LocationType.ADDRESS; else throw new RuntimeException("unknown type: " + ty); XmlPullUtil.enter(pp, "r"); final String id = XmlPullUtil.valueTag(pp, "id"); XmlPullUtil.valueTag(pp, "stateless"); XmlPullUtil.valueTag(pp, "omc"); final String place = normalizeLocationName(XmlPullUtil.optValueTag(pp, "pc", null)); XmlPullUtil.valueTag(pp, "pid"); final Point coord = parseCoord(XmlPullUtil.optValueTag(pp, "c", null)); XmlPullUtil.skipExit(pp, "r"); final String qal = XmlPullUtil.optValueTag(pp, "qal", null); final int quality = qal != null ? Integer.parseInt(qal) : 0; XmlPullUtil.skipExit(pp, "p"); final Location location = new Location(type, type == LocationType.STATION ? id : null, coord, place, name); final SuggestedLocation locationAndQuality = new SuggestedLocation(location, quality); locations.add(locationAndQuality); } XmlPullUtil.skipExit(pp, "sf"); } else { XmlPullUtil.next(pp); } return new SuggestLocationsResult(header, locations); } catch (final XmlPullParserException x) { throw new ParserException("cannot parse xml: " + firstChars, x); } finally { if (is != null) is.close(); } } private StringBuilder xmlCoordRequestParameters(final EnumSet types, final int lat, final int lon, final int maxDistance, final int maxLocations) { final StringBuilder parameters = new StringBuilder(); appendCommonRequestParams(parameters, "XML"); parameters.append("&coord=").append(String.format(Locale.ENGLISH, "%2.6f:%2.6f:WGS84", latLonToDouble(lon), latLonToDouble(lat))); if (useStringCoordListOutputFormat) parameters.append("&coordListOutputFormat=STRING"); parameters.append("&max=").append(maxLocations != 0 ? maxLocations : 50); parameters.append("&inclFilter=1"); int i = 1; for (final LocationType type : types) { parameters.append("&radius_").append(i).append('=').append(maxDistance != 0 ? maxDistance : 1320); parameters.append("&type_").append(i).append('='); if (type == LocationType.STATION) parameters.append("STOP"); else if (type == LocationType.POI) parameters.append("POI_POINT"); else throw new IllegalArgumentException("cannot handle location type: " + type); // ENTRANCE, BUS_POINT i++; } return parameters; } protected NearbyLocationsResult xmlCoordRequest(final EnumSet types, final int lat, final int lon, final int maxDistance, final int maxStations) throws IOException { final StringBuilder parameters = xmlCoordRequestParameters(types, lat, lon, maxDistance, maxStations); final StringBuilder uri = new StringBuilder(coordEndpoint); if (!httpPost) uri.append(parameters); // System.out.println(uri); // System.out.println(parameters); InputStream is = null; String firstChars = null; try { is = ParserUtils.scrapeInputStream(uri.toString(), httpPost ? parameters.substring(1) : null, null, httpReferer, null); firstChars = ParserUtils.peekFirstChars(is); final XmlPullParser pp = parserFactory.newPullParser(); pp.setInput(is, null); final ResultHeader header = enterItdRequest(pp); XmlPullUtil.enter(pp, "itdCoordInfoRequest"); XmlPullUtil.enter(pp, "itdCoordInfo"); XmlPullUtil.enter(pp, "coordInfoRequest"); XmlPullUtil.skipExit(pp, "coordInfoRequest"); final List locations = new ArrayList(); if (XmlPullUtil.test(pp, "coordInfoItemList")) { XmlPullUtil.enter(pp, "coordInfoItemList"); while (XmlPullUtil.test(pp, "coordInfoItem")) { final String type = XmlPullUtil.attr(pp, "type"); final LocationType locationType; if ("STOP".equals(type)) locationType = LocationType.STATION; else if ("POI_POINT".equals(type)) locationType = LocationType.POI; else throw new IllegalStateException("unknown type: " + type); String id = XmlPullUtil.optAttr(pp, "stateless", null); if (id == null) id = XmlPullUtil.attr(pp, "id"); final String name = normalizeLocationName(XmlPullUtil.optAttr(pp, "name", null)); final String place = normalizeLocationName(XmlPullUtil.optAttr(pp, "locality", null)); XmlPullUtil.enter(pp, "coordInfoItem"); // FIXME this is always only one coordinate final Point coord = processItdPathCoordinates(pp).get(0); XmlPullUtil.skipExit(pp, "coordInfoItem"); if (name != null) locations.add(new Location(locationType, id, coord, place, name)); } XmlPullUtil.skipExit(pp, "coordInfoItemList"); } return new NearbyLocationsResult(header, locations); } catch (final XmlPullParserException x) { throw new ParserException("cannot parse xml: " + firstChars, x); } finally { if (is != null) is.close(); } } protected NearbyLocationsResult mobileCoordRequest(final EnumSet types, final int lat, final int lon, final int maxDistance, final int maxStations) throws IOException { final StringBuilder parameters = xmlCoordRequestParameters(types, lat, lon, maxDistance, maxStations); final StringBuilder uri = new StringBuilder(coordEndpoint); if (!httpPost) uri.append(parameters); // System.out.println(uri); // System.out.println(parameters); InputStream is = null; String firstChars = null; try { is = ParserUtils.scrapeInputStream(uri.toString(), httpPost ? parameters.substring(1) : null, null, httpReferer, null); firstChars = ParserUtils.peekFirstChars(is); final XmlPullParser pp = parserFactory.newPullParser(); pp.setInput(is, null); final ResultHeader header = enterEfa(pp); XmlPullUtil.enter(pp, "ci"); XmlPullUtil.enter(pp, "request"); XmlPullUtil.skipExit(pp, "request"); final List stations = new ArrayList(); if (XmlPullUtil.test(pp, "pis")) { XmlPullUtil.enter(pp, "pis"); while (XmlPullUtil.test(pp, "pi")) { XmlPullUtil.enter(pp, "pi"); final String name = normalizeLocationName(XmlPullUtil.valueTag(pp, "de")); final String type = XmlPullUtil.valueTag(pp, "ty"); final LocationType locationType; if ("STOP".equals(type)) locationType = LocationType.STATION; else if ("POI_POINT".equals(type)) locationType = LocationType.POI; else throw new IllegalStateException("unknown type: " + type); final String id = XmlPullUtil.valueTag(pp, "id"); XmlPullUtil.valueTag(pp, "omc"); XmlPullUtil.valueTag(pp, "pid"); final String place = normalizeLocationName(XmlPullUtil.valueTag(pp, "locality")); XmlPullUtil.valueTag(pp, "layer"); XmlPullUtil.valueTag(pp, "gisID"); XmlPullUtil.valueTag(pp, "ds"); final Point coord = parseCoord(XmlPullUtil.valueTag(pp, "c")); stations.add(new Location(locationType, id, coord, place, name)); XmlPullUtil.skipExit(pp, "pi"); } XmlPullUtil.skipExit(pp, "pis"); } XmlPullUtil.skipExit(pp, "ci"); return new NearbyLocationsResult(header, stations); } catch (final XmlPullParserException x) { throw new ParserException("cannot parse xml: " + firstChars, x); } finally { if (is != null) is.close(); } } public SuggestLocationsResult suggestLocations(final CharSequence constraint) throws IOException { return jsonStopfinderRequest(new Location(LocationType.ANY, null, null, constraint.toString())); } private interface ProcessItdOdvCallback { void location(String nameState, Location location, int matchQuality); } private String processItdOdv(final XmlPullParser pp, final String expectedUsage, final ProcessItdOdvCallback callback) throws XmlPullParserException, IOException { if (!XmlPullUtil.test(pp, "itdOdv")) throw new IllegalStateException("expecting "); final String usage = XmlPullUtil.attr(pp, "usage"); if (expectedUsage != null && !usage.equals(expectedUsage)) throw new IllegalStateException("expecting "); final String type = XmlPullUtil.attr(pp, "type"); XmlPullUtil.enter(pp, "itdOdv"); final String place = processItdOdvPlace(pp); XmlPullUtil.require(pp, "itdOdvName"); final String nameState = XmlPullUtil.attr(pp, "state"); XmlPullUtil.enter(pp, "itdOdvName"); XmlPullUtil.optSkip(pp, "itdMessage"); if ("identified".equals(nameState)) { final Location location = processOdvNameElem(pp, type, place); if (location != null) callback.location(nameState, location, Integer.MAX_VALUE); } else if ("list".equals(nameState)) { while (XmlPullUtil.test(pp, "odvNameElem")) { final int matchQuality = XmlPullUtil.intAttr(pp, "matchQuality"); final Location location = processOdvNameElem(pp, type, place); if (location != null) callback.location(nameState, location, matchQuality); } } else if ("notidentified".equals(nameState) || "empty".equals(nameState)) { XmlPullUtil.optSkip(pp, "odvNameElem"); } else { throw new RuntimeException("cannot handle nameState '" + nameState + "'"); } while (XmlPullUtil.test(pp, "infoLink")) XmlPullUtil.requireSkip(pp, "infoLink"); XmlPullUtil.optSkip(pp, "odvNameInput"); XmlPullUtil.exit(pp, "itdOdvName"); XmlPullUtil.optSkip(pp, "odvInfoList"); XmlPullUtil.optSkip(pp, "itdPoiHierarchyRoot"); if (XmlPullUtil.test(pp, "itdOdvAssignedStops")) { XmlPullUtil.enter(pp, "itdOdvAssignedStops"); while (XmlPullUtil.test(pp, "itdOdvAssignedStop")) { final Location stop = processItdOdvAssignedStop(pp); if (stop != null) callback.location("assigned", stop, 0); } XmlPullUtil.exit(pp, "itdOdvAssignedStops"); } XmlPullUtil.optSkip(pp, "itdServingModes"); XmlPullUtil.optSkip(pp, "genAttrList"); XmlPullUtil.exit(pp, "itdOdv"); return nameState; } private String processItdOdvPlace(final XmlPullParser pp) throws XmlPullParserException, IOException { if (!XmlPullUtil.test(pp, "itdOdvPlace")) throw new IllegalStateException("expecting "); final String placeState = XmlPullUtil.attr(pp, "state"); XmlPullUtil.enter(pp, "itdOdvPlace"); String place = null; if ("identified".equals(placeState)) { if (XmlPullUtil.test(pp, "odvPlaceElem")) place = normalizeLocationName(XmlPullUtil.valueTag(pp, "odvPlaceElem")); } XmlPullUtil.skipExit(pp, "itdOdvPlace"); return place; } private Location processOdvNameElem(final XmlPullParser pp, String type, final String defaultPlace) throws XmlPullParserException, IOException { if (!XmlPullUtil.test(pp, "odvNameElem")) throw new IllegalStateException("expecting "); if ("any".equals(type)) type = XmlPullUtil.attr(pp, "anyType"); final String id = XmlPullUtil.attr(pp, "stateless"); final String locality = normalizeLocationName(XmlPullUtil.optAttr(pp, "locality", null)); final String objectName = normalizeLocationName(XmlPullUtil.optAttr(pp, "objectName", null)); final String buildingName = XmlPullUtil.optAttr(pp, "buildingName", null); final String buildingNumber = XmlPullUtil.optAttr(pp, "buildingNumber", null); final String postCode = XmlPullUtil.optAttr(pp, "postCode", null); final Point coord = processCoordAttr(pp); final String nameElem = normalizeLocationName(XmlPullUtil.valueTag(pp, "odvNameElem")); final LocationType locationType; final String place; final String name; if ("stop".equals(type)) { locationType = LocationType.STATION; place = locality; name = objectName; } else if ("poi".equals(type)) { locationType = LocationType.POI; place = locality; name = objectName; } else if ("loc".equals(type)) { return null; } else if ("address".equals(type) || "singlehouse".equals(type)) { locationType = LocationType.ADDRESS; place = locality; name = objectName + (buildingNumber != null ? " " + buildingNumber : ""); } else if ("street".equals(type) || "crossing".equals(type)) { locationType = LocationType.ADDRESS; place = locality; name = objectName; } else if ("postcode".equals(type)) { locationType = LocationType.ADDRESS; place = locality; name = postCode; } else if ("buildingname".equals(type)) { locationType = LocationType.ADDRESS; place = locality; name = buildingName; } else if ("coord".equals(type)) { locationType = LocationType.ADDRESS; place = defaultPlace; name = nameElem; } else { throw new IllegalArgumentException("unknown type/anyType: " + type); } return new Location(locationType, id, coord, place != null ? place : defaultPlace, name != null ? name : nameElem); } private Location processItdOdvAssignedStop(final XmlPullParser pp) throws XmlPullParserException, IOException { final String id = XmlPullUtil.attr(pp, "stopID"); final Point coord = processCoordAttr(pp); final String place = normalizeLocationName(XmlPullUtil.optAttr(pp, "place", null)); final String name = normalizeLocationName(XmlPullUtil.optValueTag(pp, "itdOdvAssignedStop", null)); if (name != null) return new Location(LocationType.STATION, id, coord, place, name); else return null; } public NearbyLocationsResult queryNearbyLocations(final EnumSet types, final Location location, final int maxDistance, final int maxLocations) throws IOException { if (location.hasLocation()) return xmlCoordRequest(types, location.lat, location.lon, maxDistance, maxLocations); if (location.type != LocationType.STATION) throw new IllegalArgumentException("cannot handle: " + location.type); if (!location.hasId()) throw new IllegalArgumentException("at least one of stationId or lat/lon must be given"); return nearbyStationsRequest(location.id, maxLocations); } private NearbyLocationsResult nearbyStationsRequest(final String stationId, final int maxLocations) throws IOException { final StringBuilder parameters = new StringBuilder(); appendCommonRequestParams(parameters, "XML"); parameters.append("&type_dm=stop&name_dm=").append(normalizeStationId(stationId)); parameters.append("&itOptionsActive=1"); parameters.append("&ptOptionsActive=1"); if (useProxFootSearch) parameters.append("&useProxFootSearch=1"); parameters.append("&mergeDep=1"); parameters.append("&useAllStops=1"); parameters.append("&mode=direct"); final StringBuilder uri = new StringBuilder(departureMonitorEndpoint); if (!httpPost) uri.append(parameters); // System.out.println(uri); // System.out.println(parameters); InputStream is = null; String firstChars = null; try { is = ParserUtils.scrapeInputStream(uri.toString(), httpPost ? parameters.substring(1) : null, null, httpReferer, null); firstChars = ParserUtils.peekFirstChars(is); final XmlPullParser pp = parserFactory.newPullParser(); pp.setInput(is, null); final ResultHeader header = enterItdRequest(pp); XmlPullUtil.enter(pp, "itdDepartureMonitorRequest"); final AtomicReference ownStation = new AtomicReference(); final List stations = new ArrayList(); final String nameState = processItdOdv(pp, "dm", new ProcessItdOdvCallback() { public void location(final String nameState, final Location location, final int matchQuality) { if (location.type == LocationType.STATION) { if ("identified".equals(nameState)) ownStation.set(location); else if ("assigned".equals(nameState)) stations.add(location); } else { throw new IllegalStateException("cannot handle: " + location.type); } } }); if ("notidentified".equals(nameState)) return new NearbyLocationsResult(header, NearbyLocationsResult.Status.INVALID_ID); if (ownStation.get() != null && !stations.contains(ownStation)) stations.add(ownStation.get()); if (maxLocations == 0 || maxLocations >= stations.size()) return new NearbyLocationsResult(header, stations); else return new NearbyLocationsResult(header, stations.subList(0, maxLocations)); } catch (final XmlPullParserException x) { throw new ParserException("cannot parse xml: " + firstChars, x); } finally { if (is != null) is.close(); } } private static final Pattern P_LINE_RE = Pattern.compile("RE ?\\d+"); private static final Pattern P_LINE_RB = Pattern.compile("RB ?\\d+"); private static final Pattern P_LINE_R = Pattern.compile("R ?\\d+"); private static final Pattern P_LINE_S = Pattern.compile("S ?\\d+"); private static final Pattern P_LINE_NUMBER = Pattern.compile("\\d+"); protected String parseLine(final String mot, String symbol, final String name, final String longName, final String trainType, final String trainNum, final String trainName) { if (mot == null) { if (trainName != null) { final String str = name != null ? name : ""; if (trainName.equals("S-Bahn")) return 'S' + str; if (trainName.equals("U-Bahn")) return 'U' + str; if (trainName.equals("Straßenbahn")) return 'T' + str; if (trainName.equals("Badner Bahn")) return 'T' + str; if (trainName.equals("Stadtbus")) return 'B' + str; if (trainName.equals("Citybus")) return 'B' + str; if (trainName.equals("Regionalbus")) return 'B' + str; if (trainName.equals("ÖBB-Postbus")) return 'B' + str; if (trainName.equals("Autobus")) return 'B' + str; if (trainName.equals("Discobus")) return 'B' + str; if (trainName.equals("Nachtbus")) return 'B' + str; if (trainName.equals("Anrufsammeltaxi")) return 'B' + str; if (trainName.equals("Ersatzverkehr")) return 'B' + str; if (trainName.equals("Vienna Airport Lines")) return 'B' + str; } throw new IllegalStateException("cannot normalize mot='" + mot + "' symbol='" + symbol + "' name='" + name + "' long='" + longName + "' trainType='" + trainType + "' trainNum='" + trainNum + "' trainName='" + trainName + "'"); } else if ("0".equals(mot)) { final String trainNumStr = trainNum != null ? trainNum : ""; if (("EC".equals(trainType) || "EuroCity".equals(trainName) || "Eurocity".equals(trainName)) && trainNum != null) return "IEC" + trainNum; if (("EN".equals(trainType) || "EuroNight".equals(trainName)) && trainNum != null) return "IEN" + trainNum; if (("IC".equals(trainType) || "InterCity".equals(trainName)) && trainNum != null) return "IIC" + trainNum; if (("ICE".equals(trainType) || "ICE".equals(trainName) || "Intercity-Express".equals(trainName)) && trainNum != null) return "IICE" + trainNum; if (("ICN".equals(trainType) || "InterCityNight".equals(trainName)) && trainNum != null) return "IICN" + trainNum; if (("X".equals(trainType) || "InterConnex".equals(trainName)) && trainNum != null) return "IX" + trainNum; if (("CNL".equals(trainType) || "CityNightLine".equals(trainName)) && trainNum != null) // City Night Line return "ICNL" + trainNum; if (("THA".equals(trainType) || "Thalys".equals(trainName)) && trainNum != null) return "ITHA" + trainNum; if ("RHI".equals(trainType) && trainNum != null) return "IRHI" + trainNum; if (("TGV".equals(trainType) || "TGV".equals(trainName)) && trainNum != null) return "ITGV" + trainNum; if ("TGD".equals(trainType) && trainNum != null) return "ITGD" + trainNum; if ("INZ".equals(trainType) && trainNum != null) return "IINZ" + trainNum; if (("RJ".equals(trainType) || "railjet".equals(trainName)) && trainNum != null) // railjet return "IRJ" + trainNum; if (("WB".equals(trainType) || "WESTbahn".equals(trainName)) && trainNum != null) return "IWB" + trainNum; if (("HKX".equals(trainType) || "Hamburg-Köln-Express".equals(trainName)) && trainNum != null) return "IHKX" + trainNum; if ("INT".equals(trainType) && trainNum != null) // SVV, VAGFR return "IINT" + trainNum; if (("SC".equals(trainType) || "SC Pendolino".equals(trainName)) && trainNum != null) // SuperCity return "ISC" + trainNum; if ("ECB".equals(trainType) && trainNum != null) // EC, Verona-München return "IECB" + trainNum; if ("ES".equals(trainType) && trainNum != null) // Eurostar Italia return "IES" + trainNum; if (("EST".equals(trainType) || "EUROSTAR".equals(trainName)) && trainNum != null) return "IEST" + trainNum; if ("EIC".equals(trainType) && trainNum != null) // Ekspres InterCity, Polen return "IEIC" + trainNum; if ("MT".equals(trainType) && "Schnee-Express".equals(trainName) && trainNum != null) return "IMT" + trainNum; if (("TLK".equals(trainType) || "Tanie Linie Kolejowe".equals(trainName)) && trainNum != null) return "ITLK" + trainNum; if ("Zug".equals(trainName)) return 'R' + symbol; if ("Zuglinie".equals(trainName)) return 'R' + symbol; if ("IR".equals(trainType) || "Interregio".equals(trainName) || "InterRegio".equals(trainName)) return "RIR" + trainNum; if ("IRE".equals(trainType) || "Interregio-Express".equals(trainName)) return "RIRE" + trainNum; if ("InterRegioExpress".equals(trainName)) return "RIRE" + trainNumStr; if ("RE".equals(trainType) || "Regional-Express".equals(trainName)) return "RRE" + trainNum; if (trainType == null && trainNum != null && P_LINE_RE.matcher(trainNum).matches()) return 'R' + trainNum; if ("Regionalexpress".equals(trainName)) return 'R' + symbol; if ("R-Bahn".equals(trainName)) return 'R' + symbol; if ("RB-Bahn".equals(trainName)) return 'R' + symbol; if ("RE-Bahn".equals(trainName)) return 'R' + symbol; if ("REX".equals(trainType)) // RegionalExpress, Österreich return "RREX" + trainNum; if (("RB".equals(trainType) || "Regionalbahn".equals(trainName)) && trainNum != null) return "RRB" + trainNum; if (trainType == null && trainNum != null && P_LINE_RB.matcher(trainNum).matches()) return 'R' + trainNum; if ("Abellio-Zug".equals(trainName)) return "R" + symbol; if ("Westfalenbahn".equals(trainName)) return 'R' + symbol; if ("Chiemseebahn".equals(trainName)) return 'R' + symbol; if ("R".equals(trainType) || "Regionalzug".equals(trainName)) return "RR" + trainNum; if (trainType == null && trainNum != null && P_LINE_R.matcher(trainNum).matches()) return 'R' + trainNum; if ("D".equals(trainType) || "Schnellzug".equals(trainName)) return "RD" + trainNum; if ("E".equals(trainType) || "Eilzug".equals(trainName)) return "RE" + trainNum; if ("WFB".equals(trainType) || "WestfalenBahn".equals(trainName)) return "RWFB" + trainNum; if (("NWB".equals(trainType) || "NordWestBahn".equals(trainName)) && trainNum != null) return "RNWB" + trainNum; if ("WES".equals(trainType) || "Westbahn".equals(trainName)) return "RWES" + trainNum; if ("ERB".equals(trainType) || "eurobahn".equals(trainName)) return "RERB" + trainNum; if ("CAN".equals(trainType) || "cantus Verkehrsgesellschaft".equals(trainName)) return "RCAN" + trainNum; if ("HEX".equals(trainType) || "Veolia Verkehr Sachsen-Anhalt".equals(trainName)) return "RHEX" + trainNum; if ("EB".equals(trainType) || "Erfurter Bahn".equals(trainName)) return "REB" + trainNum; if ("Erfurter Bahn".equals(longName)) return "REB"; if ("EBx".equals(trainType) || "Erfurter Bahn Express".equals(trainName)) return "REBx" + trainNum; if ("Erfurter Bahn Express".equals(longName)) return "REBx"; if ("MRB".equals(trainType) || "Mitteldeutsche Regiobahn".equals(trainName)) return "RMRB" + trainNum; if ("ABR".equals(trainType) || "ABELLIO Rail NRW GmbH".equals(trainName)) return "RABR" + trainNum; if ("NEB".equals(trainType) || "NEB Niederbarnimer Eisenbahn".equals(trainName)) return "RNEB" + trainNum; if ("OE".equals(trainType) || "Ostdeutsche Eisenbahn GmbH".equals(trainName)) return "ROE" + trainNum; if ("ODE".equals(trainType)) return 'R' + symbol; if ("OLA".equals(trainType) || "Ostseeland Verkehr GmbH".equals(trainName)) return "ROLA" + trainNum; if ("UBB".equals(trainType) || "Usedomer Bäderbahn".equals(trainName)) return "RUBB" + trainNum; if ("EVB".equals(trainType) || "ELBE-WESER GmbH".equals(trainName)) return "REVB" + trainNum; if ("RTB".equals(trainType) || "Rurtalbahn GmbH".equals(trainName)) return "RRTB" + trainNum; if ("STB".equals(trainType) || "Süd-Thüringen-Bahn".equals(trainName)) return "RSTB" + trainNum; if ("HTB".equals(trainType) || "Hellertalbahn".equals(trainName)) return "RHTB" + trainNum; if ("VBG".equals(trainType) || "Vogtlandbahn".equals(trainName)) return "RVBG" + trainNum; if ("CB".equals(trainType) || "City-Bahn Chemnitz".equals(trainName)) return "RCB" + trainNum; if ("VEC".equals(trainType) || "vectus Verkehrsgesellschaft".equals(trainName)) return "RVEC" + trainNum; if ("HzL".equals(trainType) || "Hohenzollerische Landesbahn AG".equals(trainName)) return "RHzL" + trainNum; if ("SBB".equals(trainType) || "SBB GmbH".equals(trainName)) return "RSBB" + trainNum; if ("MBB".equals(trainType) || "Mecklenburgische Bäderbahn Molli".equals(trainName)) return "RMBB" + trainNum; if ("OS".equals(trainType)) // Osobní vlak return "ROS" + trainNum; if ("SP".equals(trainType) || "Sp".equals(trainType)) // Spěšný vlak return "RSP" + trainNum; if ("Dab".equals(trainType) || "Daadetalbahn".equals(trainName)) return "RDab" + trainNum; if ("FEG".equals(trainType) || "Freiberger Eisenbahngesellschaft".equals(trainName)) return "RFEG" + trainNum; if ("ARR".equals(trainType) || "ARRIVA".equals(trainName)) return "RARR" + trainNum; if ("HSB".equals(trainType) || "Harzer Schmalspurbahn".equals(trainName)) return "RHSB" + trainNum; if ("ALX".equals(trainType) || "alex - Länderbahn und Vogtlandbahn GmbH".equals(trainName)) return "RALX" + trainNum; if ("EX".equals(trainType) || "Fatra".equals(trainName)) return "REX" + trainNum; if ("ME".equals(trainType) || "metronom".equals(trainName)) return "RME" + trainNum; if ("metronom".equals(longName)) return "RME"; if ("MEr".equals(trainType)) return "RMEr" + trainNum; if ("AKN".equals(trainType) || "AKN Eisenbahn AG".equals(trainName)) return "RAKN" + trainNum; if ("SOE".equals(trainType) || "Sächsisch-Oberlausitzer Eisenbahngesellschaft".equals(trainName)) return "RSOE" + trainNum; if ("VIA".equals(trainType) || "VIAS GmbH".equals(trainName)) return "RVIA" + trainNum; if ("BRB".equals(trainType) || "Bayerische Regiobahn".equals(trainName)) return "RBRB" + trainNum; if ("BLB".equals(trainType) || "Berchtesgadener Land Bahn".equals(trainName)) return "RBLB" + trainNum; if ("HLB".equals(trainType) || "Hessische Landesbahn".equals(trainName)) return "RHLB" + trainNum; if ("NOB".equals(trainType) || "NordOstseeBahn".equals(trainName)) return "RNOB" + trainNum; if ("NBE".equals(trainType) || "Nordbahn Eisenbahngesellschaft".equals(trainName)) return "RNBE" + trainNum; if ("VEN".equals(trainType) || "Rhenus Veniro".equals(trainName)) return "RVEN" + trainType; if ("DPN".equals(trainType) || "Nahreisezug".equals(trainName)) return "RDPN" + trainNum; if ("RBG".equals(trainType) || "Regental Bahnbetriebs GmbH".equals(trainName)) return "RRBG" + trainNum; if ("BOB".equals(trainType) || "Bodensee-Oberschwaben-Bahn".equals(trainName)) return "RBOB" + trainNum; if ("VE".equals(trainType) || "Vetter".equals(trainName)) return "RVE" + trainNum; if ("SDG".equals(trainType) || "SDG Sächsische Dampfeisenbahngesellschaft mbH".equals(trainName)) return "RSDG" + trainNum; if ("PRE".equals(trainType) || "Pressnitztalbahn".equals(trainName)) return "RPRE" + trainNum; if ("VEB".equals(trainType) || "Vulkan-Eifel-Bahn".equals(trainName)) return "RVEB" + trainNum; if ("neg".equals(trainType) || "Norddeutsche Eisenbahn Gesellschaft".equals(trainName)) return "Rneg" + trainNum; if ("AVG".equals(trainType) || "Felsenland-Express".equals(trainName)) return "RAVG" + trainNum; if ("P".equals(trainType) || "BayernBahn Betriebs-GmbH".equals(trainName) || "Brohltalbahn".equals(trainName) || "Kasbachtalbahn".equals(trainName)) return "RP" + trainNum; if ("SBS".equals(trainType) || "Städtebahn Sachsen".equals(trainName)) return "RSBS" + trainNum; if ("SES".equals(trainType) || "Städteexpress Sachsen".equals(trainName)) return "RSES" + trainNum; if ("SB-".equals(trainType)) // Städtebahn Sachsen return "RSB" + trainNum; if ("ag".equals(trainType)) // agilis return "Rag" + trainNum; if ("agi".equals(trainType) || "agilis".equals(trainName)) return "Ragi" + trainNum; if ("as".equals(trainType) || "agilis-Schnellzug".equals(trainName)) return "Ras" + trainNum; if ("TLX".equals(trainType) || "TRILEX".equals(trainName)) // Trilex (Vogtlandbahn) return "RTLX" + trainNum; if ("MSB".equals(trainType) || "Mainschleifenbahn".equals(trainName)) return "RMSB" + trainNum; if ("BE".equals(trainType) || "Bentheimer Eisenbahn".equals(trainName)) return "RBE" + trainNum; if ("erx".equals(trainType) || "erixx - Der Heidesprinter".equals(trainName)) return "Rerx" + trainNum; if ("SWEG-Zug".equals(trainName)) // Südwestdeutschen Verkehrs-Aktiengesellschaft return "RSWEG" + trainNum; if ("SWEG-Zug".equals(longName)) return "RSWEG"; if ("EGP Eisenbahngesellschaft Potsdam".equals(trainName)) return "REGP" + trainNumStr; if ("ÖBB".equals(trainType) || "ÖBB".equals(trainName)) return "RÖBB" + trainNum; if ("CAT".equals(trainType)) // City Airport Train Wien return "RCAT" + trainNum; if ("DZ".equals(trainType) || "Dampfzug".equals(trainName)) return "RDZ" + trainNum; if ("CD".equals(trainType)) // Tschechien return "RCD" + trainNum; if ("VR".equals(trainType)) // Polen return 'R' + symbol; if ("PR".equals(trainType)) // Polen return 'R' + symbol; if ("KD".equals(trainType)) // Koleje Dolnośląskie (Niederschlesische Eisenbahn) return 'R' + symbol; if ("Koleje Dolnoslaskie".equals(trainName) && symbol != null) // Koleje Dolnośląskie return "R" + symbol; if ("OO".equals(trainType) || "Ordinary passenger (o.pas.)".equals(trainName)) // GB return "ROO" + trainNum; if ("XX".equals(trainType) || "Express passenger (ex.pas.)".equals(trainName)) // GB return "RXX" + trainNum; if ("XZ".equals(trainType) || "Express passenger sleeper".equals(trainName)) // GB return "RXZ" + trainNum; if ("ATB".equals(trainType)) // Autoschleuse Tauernbahn return "RATB" + trainNum; if ("ATZ".equals(trainType)) // Autozug return "RATZ" + trainNum; if ("AZ".equals(trainType) || "Auto-Zug".equals(trainName)) return "RAZ" + trainNum; if ("DWE".equals(trainType) || "Dessau-Wörlitzer Eisenbahn".equals(trainName)) return "RDWE" + trainNum; if ("KTB".equals(trainType) || "Kandertalbahn".equals(trainName)) return "RKTB" + trainNum; if ("CBC".equals(trainType) || "CBC".equals(trainName)) // City-Bahn Chemnitz return "RCBC" + trainNum; if ("Bernina Express".equals(trainName)) return 'R' + trainNum; if ("STR".equals(trainType)) // Harzquerbahn, Nordhausen return "RSTR" + trainNum; if ("EXT".equals(trainType) || "Extrazug".equals(trainName)) return "REXT" + trainNum; if ("Heritage Railway".equals(trainName)) // GB return 'R' + symbol; if ("WTB".equals(trainType) || "Wutachtalbahn".equals(trainName)) return "RWTB" + trainNum; if ("DB".equals(trainType) || "DB Regio".equals(trainName)) return "RDB" + trainNum; if ("M".equals(trainType) && "Meridian".equals(trainName)) return "RM" + trainNum; if ("M".equals(trainType) && "Messezug".equals(trainName)) return "RM" + trainNum; if ("EZ".equals(trainType)) // ÖBB Erlebniszug return "REZ" + trainNum; if ("DPF".equals(trainType)) return "RDPF" + trainNum; if ("WBA".equals(trainType) || "Waldbahn".equals(trainName)) return "RWBA" + trainNum; if ("ÖBA".equals(trainType) && trainNum != null) // Eisenbahn-Betriebsgesellschaft Ochsenhausen return "RÖBA" + trainNum; if (("UEF".equals(trainType) || "Ulmer Eisenbahnfreunde".equals(trainName)) && trainNum != null) return "RUEF" + trainNum; if (("DBG".equals(trainType) || "Döllnitzbahn".equals(trainName)) && trainNum != null) return "RDBG" + trainNum; if (("TL".equals(trainType) || "Trilex".equals(trainName)) && trainNum != null) return "RTL" + trainNum; if (("OPB".equals(trainType) || "oberpfalzbahn".equals(trainName)) && trainNum != null) return "ROPB" + trainNum; if (("OPX".equals(trainType) || "oberpfalz-express".equals(trainName)) && trainNum != null) return "ROPX" + trainNum; if (("V6".equals(trainType) || "vlexx".equals(trainName)) && trainNum != null) return "Rvlexx" + trainNum; if ("BSB-Zug".equals(trainName) && trainNum != null) // Breisgau-S-Bahn return 'S' + trainNum; if ("BSB-Zug".equals(trainName) && trainNum == null) return "SBSB"; if ("BSB-Zug".equals(longName)) return "SBSB"; if ("RSB".equals(trainType)) // Regionalschnellbahn, Wien return "SRSB" + trainNum; if ("RER".equals(trainName) && symbol != null && symbol.length() == 1) // Réseau Express Régional, // Frankreich return 'S' + symbol; if ("S".equals(trainType)) return "SS" + trainNum; if ("S-Bahn".equals(trainName)) return "SS" + trainNumStr; if ("RT".equals(trainType) || "RegioTram".equals(trainName)) return "TRT" + trainNum; if ("Bus".equals(trainType)) return "B" + trainNum; if ("SEV".equals(trainType) || "SEV".equals(trainNum) || "SEV".equals(trainName) || "SEV".equals(symbol) || "BSV".equals(trainType) || "Ersatzverkehr".equals(trainName) || "Schienenersatzverkehr".equals(trainName)) return "BSEV" + (trainNum != null ? trainNum : ""); if ("Bus replacement".equals(trainName)) // GB return "BBR"; if ("BR".equals(trainType) && trainName.startsWith("Bus")) // GB return "BBR" + trainNum; if ("GB".equals(trainType)) // Gondelbahn return "CGB" + trainNum; if ("SB".equals(trainType)) // Seilbahn return "CSB" + trainNum; if ("ZUG".equals(trainType) && trainNum != null) return '?' + trainNum; if (symbol != null && P_LINE_NUMBER.matcher(symbol).matches() && trainType == null && trainName == null) return '?' + symbol; if ("N".equals(trainType) && trainName == null && symbol == null) return "?N" + trainNum; if ("Train".equals(trainName)) return "?"; // generic if (trainName != null && trainType == null && trainNum == null) return '?' + trainName; throw new IllegalStateException("cannot normalize mot='" + mot + "' symbol='" + symbol + "' name='" + name + "' long='" + longName + "' trainType='" + trainType + "' trainNum='" + trainNum + "' trainName='" + trainName + "'"); } else if ("1".equals(mot)) { if (symbol != null && P_LINE_S.matcher(symbol).matches()) return "S" + symbol; if (name != null && P_LINE_S.matcher(name).matches()) return "S" + name; if ("S-Bahn".equals(trainName) && trainNum == null) return "SS"; } else if ("2".equals(mot)) { return 'U' + name; } else if ("3".equals(mot) || "4".equals(mot)) { return 'T' + name; } else if ("5".equals(mot) || "6".equals(mot) || "7".equals(mot) || "10".equals(mot)) { if ("Schienenersatzverkehr".equals(name)) return "BSEV"; else return 'B' + name; } else if ("8".equals(mot)) { return 'C' + name; } else if ("9".equals(mot)) { return 'F' + name; } else if ("11".equals(mot)) { return '?' + ParserUtils.firstNotEmpty(symbol, name); } throw new IllegalStateException("cannot normalize mot='" + mot + "' symbol='" + symbol + "' name='" + name + "' long='" + longName + "' trainType='" + trainType + "' trainNum='" + trainNum + "' trainName='" + trainName + "'"); } public QueryDeparturesResult queryDepartures(final String stationId, final Date time, final int maxDepartures, final boolean equivs) throws IOException { return xsltDepartureMonitorRequest(stationId, time, maxDepartures, equivs); } protected StringBuilder xsltDepartureMonitorRequestParameters(final String stationId, final Date time, final int maxDepartures, final boolean equivs) { final StringBuilder parameters = new StringBuilder(); appendCommonRequestParams(parameters, "XML"); parameters.append("&type_dm=stop"); parameters.append("&name_dm=").append(normalizeStationId(stationId)); if (time != null) appendItdDateTimeParameters(parameters, time); if (useRealtime) parameters.append("&useRealtime=1"); parameters.append("&mode=direct"); parameters.append("&ptOptionsActive=1"); parameters.append("&deleteAssignedStops_dm=").append(equivs ? '0' : '1'); if (useProxFootSearch) parameters.append("&useProxFootSearch=").append(equivs ? '1' : '0'); parameters.append("&mergeDep=1"); // merge departures if (maxDepartures > 0) parameters.append("&limit=").append(maxDepartures); return parameters; } private final void appendItdDateTimeParameters(final StringBuilder uri, final Date time) { final Calendar c = new GregorianCalendar(timeZone); c.setTime(time); final int year = c.get(Calendar.YEAR); final int month = c.get(Calendar.MONTH) + 1; final int day = c.get(Calendar.DAY_OF_MONTH); final int hour = c.get(Calendar.HOUR_OF_DAY); final int minute = c.get(Calendar.MINUTE); uri.append("&itdDate=").append(ParserUtils.urlEncode(String.format(Locale.ENGLISH, "%04d%02d%02d", year, month, day))); uri.append("&itdTime=").append(ParserUtils.urlEncode(String.format(Locale.ENGLISH, "%02d%02d", hour, minute))); } private QueryDeparturesResult xsltDepartureMonitorRequest(final String stationId, final Date time, final int maxDepartures, final boolean equivs) throws IOException { final StringBuilder parameters = xsltDepartureMonitorRequestParameters(stationId, time, maxDepartures, equivs); final StringBuilder uri = new StringBuilder(departureMonitorEndpoint); if (!httpPost) uri.append(parameters); // System.out.println(uri); // System.out.println(parameters); InputStream is = null; String firstChars = null; try { is = ParserUtils.scrapeInputStream(uri.toString(), httpPost ? parameters.substring(1) : null, null, httpReferer, null); firstChars = ParserUtils.peekFirstChars(is); final XmlPullParser pp = parserFactory.newPullParser(); pp.setInput(is, null); final ResultHeader header = enterItdRequest(pp); final QueryDeparturesResult result = new QueryDeparturesResult(header); XmlPullUtil.enter(pp, "itdDepartureMonitorRequest"); XmlPullUtil.optSkip(pp, "itdMessage"); final String nameState = processItdOdv(pp, "dm", new ProcessItdOdvCallback() { public void location(final String nameState, final Location location, final int matchQuality) { if (location.type == LocationType.STATION) if (findStationDepartures(result.stationDepartures, location.id) == null) result.stationDepartures.add(new StationDepartures(location, new LinkedList(), new LinkedList())); } }); if ("notidentified".equals(nameState) || "list".equals(nameState)) return new QueryDeparturesResult(header, QueryDeparturesResult.Status.INVALID_STATION); XmlPullUtil.optSkip(pp, "itdDateTime"); XmlPullUtil.optSkip(pp, "itdDMDateTime"); XmlPullUtil.optSkip(pp, "itdDateRange"); XmlPullUtil.optSkip(pp, "itdTripOptions"); XmlPullUtil.optSkip(pp, "itdMessage"); final Calendar plannedDepartureTime = new GregorianCalendar(timeZone); final Calendar predictedDepartureTime = new GregorianCalendar(timeZone); XmlPullUtil.require(pp, "itdServingLines"); if (!pp.isEmptyElementTag()) { XmlPullUtil.enter(pp, "itdServingLines"); while (XmlPullUtil.test(pp, "itdServingLine")) { final String assignedStopId = XmlPullUtil.optAttr(pp, "assignedStopID", null); final String destinationName = normalizeLocationName(XmlPullUtil.attr(pp, "direction")); final String destinationId = XmlPullUtil.optAttr(pp, "destID", null); final Location destination = new Location(destinationId != null ? LocationType.STATION : LocationType.ANY, destinationId, null, destinationName); final LineDestination line = new LineDestination(processItdServingLine(pp), destination); StationDepartures assignedStationDepartures; if (assignedStopId == null) assignedStationDepartures = result.stationDepartures.get(0); else assignedStationDepartures = findStationDepartures(result.stationDepartures, assignedStopId); if (assignedStationDepartures == null) assignedStationDepartures = new StationDepartures(new Location(LocationType.STATION, assignedStopId), new LinkedList(), new LinkedList()); if (!assignedStationDepartures.lines.contains(line)) assignedStationDepartures.lines.add(line); } XmlPullUtil.skipExit(pp, "itdServingLines"); } else { XmlPullUtil.next(pp); } XmlPullUtil.require(pp, "itdDepartureList"); if (!pp.isEmptyElementTag()) { XmlPullUtil.enter(pp, "itdDepartureList"); while (XmlPullUtil.test(pp, "itdDeparture")) { final String assignedStopId = XmlPullUtil.attr(pp, "stopID"); StationDepartures assignedStationDepartures = findStationDepartures(result.stationDepartures, assignedStopId); if (assignedStationDepartures == null) { final Point coord = processCoordAttr(pp); // final String name = normalizeLocationName(XmlPullUtil.attr(pp, "nameWO")); assignedStationDepartures = new StationDepartures(new Location(LocationType.STATION, assignedStopId, coord), new LinkedList(), new LinkedList()); } final Position position = parsePosition(XmlPullUtil.optAttr(pp, "platformName", null)); XmlPullUtil.enter(pp, "itdDeparture"); XmlPullUtil.require(pp, "itdDateTime"); plannedDepartureTime.clear(); processItdDateTime(pp, plannedDepartureTime); predictedDepartureTime.clear(); if (XmlPullUtil.test(pp, "itdRTDateTime")) processItdDateTime(pp, predictedDepartureTime); if (XmlPullUtil.test(pp, "itdFrequencyInfo")) XmlPullUtil.next(pp); XmlPullUtil.require(pp, "itdServingLine"); final boolean isRealtime = XmlPullUtil.attr(pp, "realtime").equals("1"); final String destinationName = normalizeLocationName(XmlPullUtil.attr(pp, "direction")); final String destinationIdStr = XmlPullUtil.optAttr(pp, "destID", null); final String destinationId = !"-1".equals(destinationIdStr) ? destinationIdStr : null; final Location destination = new Location(destinationId != null ? LocationType.STATION : LocationType.ANY, destinationId, null, destinationName); final Line line = processItdServingLine(pp); if (isRealtime && !predictedDepartureTime.isSet(Calendar.HOUR_OF_DAY)) predictedDepartureTime.setTimeInMillis(plannedDepartureTime.getTimeInMillis()); XmlPullUtil.skipExit(pp, "itdDeparture"); final Departure departure = new Departure(plannedDepartureTime.getTime(), predictedDepartureTime.isSet(Calendar.HOUR_OF_DAY) ? predictedDepartureTime.getTime() : null, line, position, destination, null, null); assignedStationDepartures.departures.add(departure); } XmlPullUtil.skipExit(pp, "itdDepartureList"); } else { XmlPullUtil.next(pp); } return result; } catch (final XmlPullParserException x) { throw new ParserException("cannot parse xml: " + firstChars, x); } finally { if (is != null) is.close(); } } protected QueryDeparturesResult queryDeparturesMobile(final String stationId, final Date time, final int maxDepartures, final boolean equivs) throws IOException { final StringBuilder parameters = xsltDepartureMonitorRequestParameters(stationId, time, maxDepartures, equivs); final StringBuilder uri = new StringBuilder(departureMonitorEndpoint); if (!httpPost) uri.append(parameters); // System.out.println(uri); // System.out.println(parameters); InputStream is = null; String firstChars = null; try { is = ParserUtils.scrapeInputStream(uri.toString(), httpPost ? parameters.substring(1) : null, null, httpReferer, null); firstChars = ParserUtils.peekFirstChars(is); final XmlPullParser pp = parserFactory.newPullParser(); pp.setInput(is, null); final ResultHeader header = enterEfa(pp); final QueryDeparturesResult result = new QueryDeparturesResult(header); XmlPullUtil.require(pp, "dps"); if (!pp.isEmptyElementTag()) { XmlPullUtil.enter(pp, "dps"); final Calendar plannedDepartureTime = new GregorianCalendar(timeZone); final Calendar predictedDepartureTime = new GregorianCalendar(timeZone); while (XmlPullUtil.test(pp, "dp")) { XmlPullUtil.enter(pp, "dp"); // misc /* final String stationName = */normalizeLocationName(XmlPullUtil.valueTag(pp, "n")); /* final boolean isRealtime = */XmlPullUtil.valueTag(pp, "realtime").equals("1"); XmlPullUtil.optSkip(pp, "dt"); // time parseMobileSt(pp, plannedDepartureTime, predictedDepartureTime); final LineDestination lineDestination = parseMobileM(pp, true); XmlPullUtil.enter(pp, "r"); final String assignedId = XmlPullUtil.valueTag(pp, "id"); XmlPullUtil.valueTag(pp, "a"); final Position position = super.parsePosition(XmlPullUtil.optValueTag(pp, "pl", null)); XmlPullUtil.skipExit(pp, "r"); /* final Point positionCoordinate = */parseCoord(XmlPullUtil.optValueTag(pp, "c", null)); // TODO messages StationDepartures stationDepartures = findStationDepartures(result.stationDepartures, assignedId); if (stationDepartures == null) { stationDepartures = new StationDepartures(new Location(LocationType.STATION, assignedId), new ArrayList( maxDepartures), null); result.stationDepartures.add(stationDepartures); } stationDepartures.departures.add(new Departure(plannedDepartureTime.getTime(), predictedDepartureTime.isSet(Calendar.HOUR_OF_DAY) ? predictedDepartureTime.getTime() : null, lineDestination.line, position, lineDestination.destination, null, null)); XmlPullUtil.skipExit(pp, "dp"); } XmlPullUtil.skipExit(pp, "dps"); return result; } else { return new QueryDeparturesResult(header, QueryDeparturesResult.Status.INVALID_STATION); } } catch (final XmlPullParserException x) { throw new ParserException("cannot parse xml: " + firstChars, x); } finally { if (is != null) is.close(); } } private static final Pattern P_MOBILE_M_SYMBOL = Pattern.compile("([^\\s]*)\\s+([^\\s]*)"); private LineDestination parseMobileM(final XmlPullParser pp, final boolean tyOrCo) throws XmlPullParserException, IOException { XmlPullUtil.enter(pp, "m"); final String n = XmlPullUtil.optValueTag(pp, "n", null); final String productNu = XmlPullUtil.valueTag(pp, "nu"); final String ty = XmlPullUtil.valueTag(pp, "ty"); final Line line; final Location destination; if ("100".equals(ty) || "99".equals(ty)) { destination = null; line = Line.FOOTWAY; } else if ("105".equals(ty)) { destination = null; line = Line.TRANSFER; } else if ("98".equals(ty)) { destination = null; line = Line.SECURE_CONNECTION; } else if ("97".equals(ty)) { destination = null; line = Line.DO_NOT_CHANGE; } else { final String co = XmlPullUtil.valueTag(pp, "co"); final String productType = tyOrCo ? ty : co; final String destinationName = normalizeLocationName(XmlPullUtil.valueTag(pp, "des")); destination = new Location(LocationType.ANY, null, null, destinationName); XmlPullUtil.optValueTag(pp, "dy", null); final String de = XmlPullUtil.optValueTag(pp, "de", null); final String productName = n != null ? n : de; final String lineId = parseMobileDv(pp); final String symbol; if (productName != null && productNu == null) symbol = productName; else if (productName != null && productNu.endsWith(" " + productName)) symbol = productNu.substring(0, productNu.length() - productName.length() - 1); else symbol = productNu; final String trainType; final String trainNum; final Matcher mSymbol = P_MOBILE_M_SYMBOL.matcher(symbol); if (mSymbol.matches()) { trainType = mSymbol.group(1); trainNum = mSymbol.group(2); } else { trainType = null; trainNum = null; } final String network = lineId.substring(0, lineId.indexOf(':')); final String lineLabel = parseLine(productType, symbol, symbol, null, trainType, trainNum, productName); line = new Line(lineId, lineLabel, lineStyle(network, lineLabel)); } XmlPullUtil.skipExit(pp, "m"); return new LineDestination(line, destination); } private String parseMobileDv(final XmlPullParser pp) throws XmlPullParserException, IOException { XmlPullUtil.enter(pp, "dv"); XmlPullUtil.optValueTag(pp, "branch", null); final String lineIdLi = XmlPullUtil.valueTag(pp, "li"); final String lineIdSu = XmlPullUtil.valueTag(pp, "su"); final String lineIdPr = XmlPullUtil.valueTag(pp, "pr"); final String lineIdDct = XmlPullUtil.valueTag(pp, "dct"); final String lineIdNe = XmlPullUtil.valueTag(pp, "ne"); XmlPullUtil.skipExit(pp, "dv"); return lineIdNe + ":" + lineIdLi + ":" + lineIdSu + ":" + lineIdDct + ":" + lineIdPr; } private void parseMobileSt(final XmlPullParser pp, final Calendar plannedDepartureTime, final Calendar predictedDepartureTime) throws XmlPullParserException, IOException { XmlPullUtil.enter(pp, "st"); plannedDepartureTime.clear(); ParserUtils.parseIsoDate(plannedDepartureTime, XmlPullUtil.valueTag(pp, "da")); ParserUtils.parseIsoTime(plannedDepartureTime, XmlPullUtil.valueTag(pp, "t")); predictedDepartureTime.clear(); if (XmlPullUtil.test(pp, "rda")) { ParserUtils.parseIsoDate(predictedDepartureTime, XmlPullUtil.valueTag(pp, "rda")); ParserUtils.parseIsoTime(predictedDepartureTime, XmlPullUtil.valueTag(pp, "rt")); } XmlPullUtil.skipExit(pp, "st"); } private StationDepartures findStationDepartures(final List stationDepartures, final String id) { for (final StationDepartures stationDeparture : stationDepartures) if (stationDeparture.location.id.equals(id)) return stationDeparture; return null; } private Location processItdPointAttributes(final XmlPullParser pp) { final String id = XmlPullUtil.attr(pp, "stopID"); String place = normalizeLocationName(XmlPullUtil.optAttr(pp, "locality", null)); if (place == null) place = normalizeLocationName(XmlPullUtil.optAttr(pp, "place", null)); String name = normalizeLocationName(XmlPullUtil.optAttr(pp, "nameWO", null)); if (name == null) name = normalizeLocationName(XmlPullUtil.optAttr(pp, "name", null)); final Point coord = processCoordAttr(pp); return new Location(LocationType.STATION, id, coord, place, name); } private boolean processItdDateTime(final XmlPullParser pp, final Calendar calendar) throws XmlPullParserException, IOException { XmlPullUtil.enter(pp); calendar.clear(); final boolean success = processItdDate(pp, calendar); if (success) processItdTime(pp, calendar); XmlPullUtil.skipExit(pp); return success; } private boolean processItdDate(final XmlPullParser pp, final Calendar calendar) throws XmlPullParserException, IOException { XmlPullUtil.require(pp, "itdDate"); final int year = XmlPullUtil.intAttr(pp, "year"); final int month = XmlPullUtil.intAttr(pp, "month") - 1; final int day = XmlPullUtil.intAttr(pp, "day"); final int weekday = XmlPullUtil.intAttr(pp, "weekday"); XmlPullUtil.next(pp); if (weekday < 0) return false; if (year == 0) return false; if (year < 1900 || year > 2100) throw new InvalidDataException("invalid year: " + year); if (month < 0 || month > 11) throw new InvalidDataException("invalid month: " + month); if (day < 1 || day > 31) throw new InvalidDataException("invalid day: " + day); calendar.set(Calendar.YEAR, year); calendar.set(Calendar.MONTH, month); calendar.set(Calendar.DAY_OF_MONTH, day); return true; } private void processItdTime(final XmlPullParser pp, final Calendar calendar) throws XmlPullParserException, IOException { XmlPullUtil.require(pp, "itdTime"); calendar.set(Calendar.HOUR_OF_DAY, XmlPullUtil.intAttr(pp, "hour")); calendar.set(Calendar.MINUTE, XmlPullUtil.intAttr(pp, "minute")); XmlPullUtil.next(pp); } private Line processItdServingLine(final XmlPullParser pp) throws XmlPullParserException, IOException { XmlPullUtil.require(pp, "itdServingLine"); final String slMotType = XmlPullUtil.attr(pp, "motType"); final String slSymbol = XmlPullUtil.optAttr(pp, "symbol", null); final String slNumber = XmlPullUtil.optAttr(pp, "number", null); final String slStateless = XmlPullUtil.optAttr(pp, "stateless", null); final String slTrainType = XmlPullUtil.optAttr(pp, "trainType", null); final String slTrainName = XmlPullUtil.optAttr(pp, "trainName", null); final String slTrainNum = XmlPullUtil.optAttr(pp, "trainNum", null); XmlPullUtil.enter(pp, "itdServingLine"); String itdTrainName = null; String itdTrainType = null; String itdMessage = null; if (XmlPullUtil.test(pp, "itdTrain")) { itdTrainName = XmlPullUtil.attr(pp, "name"); itdTrainType = XmlPullUtil.attr(pp, "type"); if (!pp.isEmptyElementTag()) { XmlPullUtil.enter(pp, "itdTrain"); XmlPullUtil.skipExit(pp, "itdTrain"); } else { XmlPullUtil.next(pp); } } if (XmlPullUtil.test(pp, "itdNoTrain")) { itdTrainName = XmlPullUtil.optAttr(pp, "name", null); itdTrainType = XmlPullUtil.optAttr(pp, "type", null); if (!pp.isEmptyElementTag()) { final String text = XmlPullUtil.valueTag(pp, "itdNoTrain"); if (itdTrainName != null && itdTrainName.toLowerCase().contains("ruf")) itdMessage = text; else if (text != null && text.toLowerCase().contains("ruf")) itdMessage = text; } else { XmlPullUtil.next(pp); } } XmlPullUtil.require(pp, "motDivaParams"); final String divaNetwork = XmlPullUtil.optAttr(pp, "network", null); XmlPullUtil.skipExit(pp, "itdServingLine"); final String trainType = ParserUtils.firstNotEmpty(slTrainType, itdTrainType); final String trainName = ParserUtils.firstNotEmpty(slTrainName, itdTrainName); final String label = parseLine(slMotType, slSymbol, slNumber, slNumber, trainType, slTrainNum, trainName); return new Line(slStateless, label, lineStyle(divaNetwork, label), itdMessage); } private static final Pattern P_STATION_NAME_WHITESPACE = Pattern.compile("\\s+"); protected String normalizeLocationName(final String name) { if (name == null || name.length() == 0) return null; return P_STATION_NAME_WHITESPACE.matcher(name).replaceAll(" "); } protected static double latLonToDouble(final int value) { return (double) value / 1000000; } protected String xsltTripRequestParameters(final Location from, final Location via, final Location to, final Date time, final boolean dep, final Collection products, final WalkSpeed walkSpeed, final Accessibility accessibility, final Set