diff --git a/src/it/reyboz/bustorino/backend/ArrivalsFetcher.java b/src/it/reyboz/bustorino/backend/ArrivalsFetcher.java index b847570..ed9d368 100644 --- a/src/it/reyboz/bustorino/backend/ArrivalsFetcher.java +++ b/src/it/reyboz/bustorino/backend/ArrivalsFetcher.java @@ -1,42 +1,50 @@ /* BusTO (backend components) Copyright (C) 2016 Ludovico Pavesi 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 it.reyboz.bustorino.backend; // "arrivals" è più usato di "transit" o simili, e chi sono io per mettermi a dibattere con gli inglesi? -public interface ArrivalsFetcher { +import java.util.concurrent.atomic.AtomicInteger; + +public interface ArrivalsFetcher extends Fetcher { /** * Reads arrival times from a (hopefully) real-time source, e.g. the GTT website. + * Don't call this in UI thread! * * @param stopID stop ID, in normalized form. * @param routeID route ID, in normalized form. + * @param res result code (will be set by this method) * @return arrival times + * @see it.reyboz.bustorino.backend.Fetcher.resultCodes * @see FiveTNormalizer */ - Palina ReadArrivalTimesLine(String stopID, String routeID); + Palina ReadArrivalTimesRoute(String stopID, String routeID, AtomicInteger res); /** * Reads arrival times from a (hopefully) real-time source, e.g. the GTT website. + * Don't call this in UI thread! * * @param routeID route ID, in normalized form. + * @param res result code (will be set by this method) * @return arrival times + * @see it.reyboz.bustorino.backend.Fetcher.resultCodes * @see FiveTNormalizer */ - Palina ReadArrivalTimesAll(String routeID); + Palina ReadArrivalTimesAll(String routeID, AtomicInteger res); } diff --git a/src/it/reyboz/bustorino/backend/Fetcher.java b/src/it/reyboz/bustorino/backend/Fetcher.java new file mode 100644 index 0000000..c76a065 --- /dev/null +++ b/src/it/reyboz/bustorino/backend/Fetcher.java @@ -0,0 +1,44 @@ +/* + BusTO (backend components) + Copyright (C) 2016 Ludovico Pavesi + + 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 it.reyboz.bustorino.backend; + +import java.util.concurrent.atomic.AtomicInteger; + +public interface Fetcher { + /** + * Status codes, convert to int with resultCodes.OK.ordinal() and the like. + * + * NULL: still haven't started + * OK: got a response, parsed correctly, obtained some data + * CLIENT_OFFLINE: can't connect to the internet + * SERVER_OFFLINE: the server is down for maintenance (apparently sometimes happens to the 5T website and they put a message on the home page, that can be parsed to set this state) + * SERVER_ERROR: the server replied anything other than HTTP 200, basically + * PARSER_ERROR: the server replied something that can't be parsed, probably it's not the data we're looking for (e.g. "PHP: Fatal Error") + * NO_RESULTS: like OK, but there's an empty array (no stops\routes\"passaggi" found) + */ + enum resultCodes { + NULL, OK, CLIENT_OFFLINE, SERVER_OFFLINE, SERVER_ERROR, PARSER_ERROR, NOT_FOUND, EMPTY_RESULT_SET + } + + // moved to AsyncFetcher since shouldn't be reused on different runs + /* + * Reading this before doing anything is a bad idea, probably. + */ + //AtomicInteger result = new AtomicInteger(resultCodes.NULL.ordinal()); // how does this even work in an interface is a mystery to me. +} diff --git a/src/it/reyboz/bustorino/backend/GTTJSONFetcher.java b/src/it/reyboz/bustorino/backend/GTTJSONFetcher.java new file mode 100644 index 0000000..c4dcf93 --- /dev/null +++ b/src/it/reyboz/bustorino/backend/GTTJSONFetcher.java @@ -0,0 +1,119 @@ +/* + BusTO (backend components) + Copyright (C) 2016 Ludovico Pavesi + + 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 it.reyboz.bustorino.backend; + +import org.json.JSONArray; +import org.json.JSONException; +import org.json.JSONObject; + +import java.io.IOException; +import java.io.InputStream; +import java.net.HttpURLConnection; +import java.net.MalformedURLException; +import java.net.URL; +import java.util.Scanner; +import java.util.concurrent.atomic.AtomicInteger; + +public class GTTJSONFetcher implements ArrivalsFetcher { + @Override + public Palina ReadArrivalTimesRoute(String stopID, String routeID, AtomicInteger res) { + return this.ReadArrivalTimesAll(routeID, res); // TODO: finish implementation + } + + @Override + public Palina ReadArrivalTimesAll(String routeID, AtomicInteger res) { + HttpURLConnection urlConnection; + URL url; + Palina p = new Palina(); + JSONArray json; + int howManyRoutes, howManyPassaggi, i, j, pos; // il misto inglese-italiano è un po' ridicolo ma tanto vale... + JSONObject thisroute; + JSONArray passaggi; + + try { + url = new URL("http://www.gtt.to.it/cms/index.php?option=com_gtt&task=palina.getTransiti&palina=" + routeID + "&realtime=true"); + } catch (MalformedURLException e) { + res.set(resultCodes.PARSER_ERROR.ordinal()); + return p; + } + + try { + urlConnection = (HttpURLConnection) url.openConnection(); + } catch(IOException e) { + res.set(resultCodes.SERVER_OFFLINE.ordinal()); // TODO: can we assume this is CLIENT_OFFLINE? + return p; + } + + try { + InputStream in = urlConnection.getInputStream(); + json = new JSONArray(streamToString(in)); + } catch (Exception e) { + res.set(resultCodes.PARSER_ERROR.ordinal()); + return p; + } finally { + urlConnection.disconnect(); + } + + howManyRoutes = json.length(); + if(howManyRoutes == 0) { + res.set(resultCodes.EMPTY_RESULT_SET.ordinal()); + return p; + } + + try { + // returns [{"PassaggiRT":[],"Passaggi":[]}] for non existing stops + json.getJSONObject(0).getString("Linea"); // if we can get this, then there's something useful in the array. + } catch(JSONException e) { + res.set(resultCodes.EMPTY_RESULT_SET.ordinal()); // could also use NOT_FOUND + return p; + } + + try { // TODO: split this to reuse other part in ReadArrivalTimesRoute + for(i = 0; i < howManyRoutes; i++) { + thisroute = json.getJSONObject(i); + pos = p.addRoute(thisroute.getString("Linea"), thisroute.getString("Direzione")); + + passaggi = thisroute.getJSONArray("PassaggiRT"); + howManyPassaggi = passaggi.length(); + for(j = 0; j < howManyPassaggi; i++) { + p.addPassaggio(passaggi.getString(j).concat("*"), pos); + } + + passaggi = thisroute.getJSONArray("Passaggi"); // now the non-real-time ones + howManyPassaggi = passaggi.length(); + for(j = 0; j < howManyPassaggi; i++) { + p.addPassaggio(passaggi.getString(j), pos); + } + } + } catch (JSONException e) { + res.set(resultCodes.PARSER_ERROR.ordinal()); + return p; + } + + res.set(resultCodes.OK.ordinal()); + return p; + } + + // https://stackoverflow.com/a/14585883 + private static String streamToString(InputStream is) { + Scanner s = new Scanner(is); // TODO: test this + return s.hasNext() ? s.next() : ""; + } + +} diff --git a/src/it/reyboz/bustorino/backend/Passaggio.java b/src/it/reyboz/bustorino/backend/Passaggio.java index ba90b61..6796af9 100644 --- a/src/it/reyboz/bustorino/backend/Passaggio.java +++ b/src/it/reyboz/bustorino/backend/Passaggio.java @@ -1,90 +1,90 @@ /* BusTO (backend components) Copyright (C) 2016 Ludovico Pavesi 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 it.reyboz.bustorino.backend; import android.support.annotation.NonNull; public final class Passaggio implements Comparable { public final String hh; public final String mm; public final boolean isInRealTime; /** * Constructs a time (passaggio) for the timetable. * * @param TimeGTT time in GTT format (e.g. "11:22*"), already trimmed from whitespace. * @throws IllegalArgumentException if nothing reasonable can be extracted from the string */ - public Passaggio(String TimeGTT) { + public Passaggio(@NonNull String TimeGTT) { String[] parts = TimeGTT.split(":"); if(parts.length != 2) { // TODO: messaggio d'errore meno ridicolo throw new IllegalArgumentException("The string " + TimeGTT + " doesn't follow the sacred format of time according to GTT!"); } this.hh = parts[0]; if(parts[1].endsWith("*")) { this.mm = parts[1].substring(0, parts[1].length() - 1); this.isInRealTime = true; } else { this.mm = parts[1]; this.isInRealTime = false; } } @Override public int compareTo(@NonNull Passaggio altro) { int diff; diff = failsafeParseInt(altro.hh) - failsafeParseInt(this.hh); // an attempt to correctly sort times around midnight (e.g. 23.59 should come before 00.01) if(diff > 12) { // TODO: see if this works in practice diff = -(24 - diff); } else if(diff < -12) { diff = -(diff + 24); } diff *= 60; diff += failsafeParseInt(altro.mm) - failsafeParseInt(this.mm); // we should take into account if one is in real time and the other isn't, shouldn't we? if(altro.isInRealTime) { ++diff; } if(this.isInRealTime) { --diff; } return diff; } /** * Parses without blowing up. * * @param str the number as a string * @return the number as an integer */ private static int failsafeParseInt(String str) { try { return Integer.parseInt(str); } catch(NumberFormatException e) { return 0; } } } \ No newline at end of file diff --git a/src/it/reyboz/bustorino/backend/StopsFinderByName.java b/src/it/reyboz/bustorino/backend/StopsFinderByName.java index f4bf6a4..32661f8 100644 --- a/src/it/reyboz/bustorino/backend/StopsFinderByName.java +++ b/src/it/reyboz/bustorino/backend/StopsFinderByName.java @@ -1,32 +1,32 @@ /* BusTO (backend components) Copyright (C) 2016 Ludovico Pavesi 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 it.reyboz.bustorino.backend; import java.util.List; -public interface StopsFinderByName { +public interface StopsFinderByName extends Fetcher { /** - * Finds stops by name. + * Finds stops by name. Don't call this in UI thread! * * @param name the string to search for * @return list of stops, in normalized form. * @see FiveTNormalizer */ List FindByName(String name); } diff --git a/src/it/reyboz/bustorino/backend/StopsFinderByRoute.java b/src/it/reyboz/bustorino/backend/StopsFinderByRoute.java index 97e66c1..7fc5176 100644 --- a/src/it/reyboz/bustorino/backend/StopsFinderByRoute.java +++ b/src/it/reyboz/bustorino/backend/StopsFinderByRoute.java @@ -1,32 +1,32 @@ /* BusTO (backend components) Copyright (C) 2016 Ludovico Pavesi 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 it.reyboz.bustorino.backend; import java.util.List; -public interface StopsFinderByRoute { +public interface StopsFinderByRoute extends Fetcher { /** - * Finds every stop in a route. + * Finds every stop in a route. Don't call this in UI thread! * * @param routeID route ID, in normalized form. * @return list of stops, in normalized form. * @see FiveTNormalizer */ List FindByRoute(String routeID); } \ No newline at end of file diff --git a/src/it/reyboz/bustorino/lab/asyncwget/AsyncWgetBusStopSuggestions.java b/src/it/reyboz/bustorino/lab/asyncwget/AsyncWgetBusStopSuggestions.java index 07d2287..959d226 100644 --- a/src/it/reyboz/bustorino/lab/asyncwget/AsyncWgetBusStopSuggestions.java +++ b/src/it/reyboz/bustorino/lab/asyncwget/AsyncWgetBusStopSuggestions.java @@ -1,126 +1,124 @@ /* BusTO - Arrival times for Turin public transports. Copyright (C) 2014 Valerio Bozzolan 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 it.reyboz.bustorino.lab.asyncwget; import android.util.Log; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import org.jsoup.select.Elements; import java.io.UnsupportedEncodingException; import java.net.URLEncoder; import java.util.ArrayList; import it.reyboz.bustorino.lab.GTTSiteSucker.BusStop; -import it.reyboz.bustorino.lab.GTTSiteSucker; - /** * Asynchronous BusStop[] fetcher from a query. * * @author Valerio Bozzolan */ public class AsyncWgetBusStopSuggestions extends AsyncWget { public final static int ERROR_NONE = 0; public final static int ERROR_EMPTY_DOM = 1; public final static int ERROR_DOM = 2; /** * Like Ajax * * @param query Part of the busStopName * @throws UnsupportedEncodingException */ public AsyncWgetBusStopSuggestions(String query) throws UnsupportedEncodingException { super.execute(getURL(query)); } protected final String getURL(String busStopName) throws UnsupportedEncodingException { return "http://www.5t.torino.it/5t/trasporto/stop-lookup.jsp?action=search&stopShortName=" + URLEncoder.encode(busStopName, "utf-8"); } /** * See http://www.5t.torino.it/5t/trasporto/stop-lookup.jsp?action=search&stopShortName=carducci * * @param responseInDOMFormatBecause5THaveAbsolutelyNoIdeaWhatJSONWas * @Override */ protected void onPostExecute(String responseInDOMFormatBecause5THaveAbsolutelyNoIdeaWhatJSONWas) { ArrayList busStops = new ArrayList(); if (responseInDOMFormatBecause5THaveAbsolutelyNoIdeaWhatJSONWas == null) { onReceivedBusStopNames(null, ERROR_EMPTY_DOM); return; } Document doc = Jsoup.parse(responseInDOMFormatBecause5THaveAbsolutelyNoIdeaWhatJSONWas); // Find bus stops Elements lis = doc.getElementsByTag("li"); for(Element li : lis) { Elements spans = li.getElementsByTag("span"); BusStop busStop; // busStopID try { busStop = new BusStop(spans.eq(0).text()); } catch(Exception e) { Log.e("Suggestions", "Empty busStopID"); onReceivedBusStopNames(null, ERROR_DOM); return; } // busStopName try { busStop.setBusStopName(spans.eq(1).text()); } catch(Exception e) { Log.e("Suggestions", "Empty busStopName"); onReceivedBusStopNames(null, ERROR_DOM); return; } // busStopLocation try { busStop.setBusStopLocality(spans.eq(2).text()); } catch(Exception e) { Log.e("Suggestions", "Empty busStopLocation"); onReceivedBusStopNames(null, ERROR_DOM); return; } busStops.add( busStop ); } onReceivedBusStopNames( busStops.toArray(new BusStop[busStops.size()]), ERROR_NONE ); } /** * Overload this! * * @param busStops Suggestions * @param status Error status if any */ public void onReceivedBusStopNames(BusStop[] busStops, int status) { // Do something here } } \ No newline at end of file diff --git a/src/it/reyboz/bustorino/backend/StopsFinderByName.java b/src/it/reyboz/bustorino/middleware/AsyncArrivalsFetcherAll.java similarity index 51% copy from src/it/reyboz/bustorino/backend/StopsFinderByName.java copy to src/it/reyboz/bustorino/middleware/AsyncArrivalsFetcherAll.java index f4bf6a4..9a76bf6 100644 --- a/src/it/reyboz/bustorino/backend/StopsFinderByName.java +++ b/src/it/reyboz/bustorino/middleware/AsyncArrivalsFetcherAll.java @@ -1,32 +1,42 @@ /* BusTO (backend components) Copyright (C) 2016 Ludovico Pavesi 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 it.reyboz.bustorino.backend; - -import java.util.List; - -public interface StopsFinderByName { - /** - * Finds stops by name. - * - * @param name the string to search for - * @return list of stops, in normalized form. - * @see FiveTNormalizer - */ - List FindByName(String name); +package it.reyboz.bustorino.middleware; + +import it.reyboz.bustorino.backend.ArrivalsFetcher; +import it.reyboz.bustorino.backend.Palina; + +import android.os.AsyncTask; +import android.support.annotation.NonNull; + +import java.util.concurrent.atomic.AtomicInteger; + +public class AsyncArrivalsFetcherAll extends AsyncTask { + ArrivalsFetcher af; + AtomicInteger result; + String stopID; + + public AsyncArrivalsFetcherAll(@NonNull ArrivalsFetcher af, @NonNull String stopID) { + this.af = af; + this.stopID = stopID; + } + + @Override protected Palina doInBackground(Void... useless) { + return af.ReadArrivalTimesAll(this.stopID, this.result); + } }