diff --git a/build.gradle b/build.gradle index 3918e06..811024b 100644 --- a/build.gradle +++ b/build.gradle @@ -1,52 +1,58 @@ buildscript { repositories { mavenCentral() jcenter() } dependencies { classpath 'com.android.tools.build:gradle:2.3.1' } } apply plugin: 'com.android.application' android { compileSdkVersion 25 buildToolsVersion '25.0.2' compileOptions { sourceCompatibility JavaVersion.VERSION_1_7 targetCompatibility JavaVersion.VERSION_1_7 } sourceSets { main { manifest.srcFile 'AndroidManifest.xml' java.srcDirs = ['src'] resources.srcDirs = ['src'] aidl.srcDirs = ['src'] renderscript.srcDirs = ['src'] res.srcDirs = ['res'] assets.srcDirs = ['assets'] } } + buildTypes{ + debug{ + applicationIdSuffix ".debug" + versionNameSuffix "-dev" + } + } lintOptions { abortOnError false } repositories { mavenCentral() mavenLocal() } dependencies { compile 'com.android.support:support-v4:25.3.1' compile 'com.android.support:appcompat-v7:25.3.1' compile 'com.android.support:design:25.3.1' compile 'org.jsoup:jsoup:1.7.3' compile 'com.readystatesoftware.sqliteasset:sqliteassethelper:2.0.1' } } dependencies { } diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar index 8c0fb64..7a3265e 100755 Binary files a/gradle/wrapper/gradle-wrapper.jar and b/gradle/wrapper/gradle-wrapper.jar differ diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties index 795352f..f16d266 100755 --- a/gradle/wrapper/gradle-wrapper.properties +++ b/gradle/wrapper/gradle-wrapper.properties @@ -1,6 +1,5 @@ -#Mon Oct 10 12:36:51 CEST 2016 distributionBase=GRADLE_USER_HOME distributionPath=wrapper/dists zipStoreBase=GRADLE_USER_HOME zipStorePath=wrapper/dists -distributionUrl=https\://services.gradle.org/distributions/gradle-2.14.1-all.zip +distributionUrl=https\://services.gradle.org/distributions/gradle-4.1-bin.zip diff --git a/gradlew b/gradlew index 91a7e26..cccdd3d 100755 --- a/gradlew +++ b/gradlew @@ -1,164 +1,172 @@ -#!/usr/bin/env bash +#!/usr/bin/env sh ############################################################################## ## ## Gradle start up script for UN*X ## ############################################################################## -# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. -DEFAULT_JVM_OPTS="" +# Attempt to set APP_HOME +# Resolve links: $0 may be a link +PRG="$0" +# Need this for relative symlinks. +while [ -h "$PRG" ] ; do + ls=`ls -ld "$PRG"` + link=`expr "$ls" : '.*-> \(.*\)$'` + if expr "$link" : '/.*' > /dev/null; then + PRG="$link" + else + PRG=`dirname "$PRG"`"/$link" + fi +done +SAVED="`pwd`" +cd "`dirname \"$PRG\"`/" >/dev/null +APP_HOME="`pwd -P`" +cd "$SAVED" >/dev/null APP_NAME="Gradle" APP_BASE_NAME=`basename "$0"` +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS="" + # Use the maximum available, or set MAX_FD != -1 to use that value. MAX_FD="maximum" -warn ( ) { +warn () { echo "$*" } -die ( ) { +die () { echo echo "$*" echo exit 1 } # OS specific support (must be 'true' or 'false'). cygwin=false msys=false darwin=false +nonstop=false case "`uname`" in CYGWIN* ) cygwin=true ;; Darwin* ) darwin=true ;; MINGW* ) msys=true ;; + NONSTOP* ) + nonstop=true + ;; esac -# For Cygwin, ensure paths are in UNIX format before anything is touched. -if $cygwin ; then - [ -n "$JAVA_HOME" ] && JAVA_HOME=`cygpath --unix "$JAVA_HOME"` -fi - -# Attempt to set APP_HOME -# Resolve links: $0 may be a link -PRG="$0" -# Need this for relative symlinks. -while [ -h "$PRG" ] ; do - ls=`ls -ld "$PRG"` - link=`expr "$ls" : '.*-> \(.*\)$'` - if expr "$link" : '/.*' > /dev/null; then - PRG="$link" - else - PRG=`dirname "$PRG"`"/$link" - fi -done -SAVED="`pwd`" -cd "`dirname \"$PRG\"`/" >&- -APP_HOME="`pwd -P`" -cd "$SAVED" >&- - CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar # Determine the Java command to use to start the JVM. if [ -n "$JAVA_HOME" ] ; then if [ -x "$JAVA_HOME/jre/sh/java" ] ; then # IBM's JDK on AIX uses strange locations for the executables JAVACMD="$JAVA_HOME/jre/sh/java" else JAVACMD="$JAVA_HOME/bin/java" fi if [ ! -x "$JAVACMD" ] ; then die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME Please set the JAVA_HOME variable in your environment to match the location of your Java installation." fi else JAVACMD="java" which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. Please set the JAVA_HOME variable in your environment to match the location of your Java installation." fi # Increase the maximum file descriptors if we can. -if [ "$cygwin" = "false" -a "$darwin" = "false" ] ; then +if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then MAX_FD_LIMIT=`ulimit -H -n` if [ $? -eq 0 ] ; then if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then MAX_FD="$MAX_FD_LIMIT" fi ulimit -n $MAX_FD if [ $? -ne 0 ] ; then warn "Could not set maximum file descriptor limit: $MAX_FD" fi else warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" fi fi # For Darwin, add options to specify how the application appears in the dock if $darwin; then GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" fi # For Cygwin, switch paths to Windows format before running java if $cygwin ; then APP_HOME=`cygpath --path --mixed "$APP_HOME"` CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` + JAVACMD=`cygpath --unix "$JAVACMD"` # We build the pattern for arguments to be converted via cygpath ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` SEP="" for dir in $ROOTDIRSRAW ; do ROOTDIRS="$ROOTDIRS$SEP$dir" SEP="|" done OURCYGPATTERN="(^($ROOTDIRS))" # Add a user-defined pattern to the cygpath arguments if [ "$GRADLE_CYGPATTERN" != "" ] ; then OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" fi # Now convert the arguments - kludge to limit ourselves to /bin/sh i=0 for arg in "$@" ; do CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` else eval `echo args$i`="\"$arg\"" fi i=$((i+1)) done case $i in (0) set -- ;; (1) set -- "$args0" ;; (2) set -- "$args0" "$args1" ;; (3) set -- "$args0" "$args1" "$args2" ;; (4) set -- "$args0" "$args1" "$args2" "$args3" ;; (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; esac fi -# Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules -function splitJvmOpts() { - JVM_OPTS=("$@") +# Escape application args +save () { + for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done + echo " " } -eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS -JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME" +APP_ARGS=$(save "$@") + +# Collect all arguments for the java command, following the shell quoting and substitution rules +eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS" + +# by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong +if [ "$(uname)" = "Darwin" ] && [ "$HOME" = "$PWD" ]; then + cd "$(dirname "$0")" +fi -exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@" +exec "$JAVACMD" "$@" diff --git a/gradlew.bat b/gradlew.bat index aec9973..e95643d 100755 --- a/gradlew.bat +++ b/gradlew.bat @@ -1,90 +1,84 @@ @if "%DEBUG%" == "" @echo off @rem ########################################################################## @rem @rem Gradle startup script for Windows @rem @rem ########################################################################## @rem Set local scope for the variables with windows NT shell if "%OS%"=="Windows_NT" setlocal -@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. -set DEFAULT_JVM_OPTS= - set DIRNAME=%~dp0 if "%DIRNAME%" == "" set DIRNAME=. set APP_BASE_NAME=%~n0 set APP_HOME=%DIRNAME% +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS= + @rem Find java.exe if defined JAVA_HOME goto findJavaFromJavaHome set JAVA_EXE=java.exe %JAVA_EXE% -version >NUL 2>&1 if "%ERRORLEVEL%" == "0" goto init echo. echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. echo. echo Please set the JAVA_HOME variable in your environment to match the echo location of your Java installation. goto fail :findJavaFromJavaHome set JAVA_HOME=%JAVA_HOME:"=% set JAVA_EXE=%JAVA_HOME%/bin/java.exe if exist "%JAVA_EXE%" goto init echo. echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% echo. echo Please set the JAVA_HOME variable in your environment to match the echo location of your Java installation. goto fail :init -@rem Get command-line arguments, handling Windowz variants +@rem Get command-line arguments, handling Windows variants if not "%OS%" == "Windows_NT" goto win9xME_args -if "%@eval[2+2]" == "4" goto 4NT_args :win9xME_args @rem Slurp the command line arguments. set CMD_LINE_ARGS= set _SKIP=2 :win9xME_args_slurp if "x%~1" == "x" goto execute set CMD_LINE_ARGS=%* -goto execute - -:4NT_args -@rem Get arguments from the 4NT Shell from JP Software -set CMD_LINE_ARGS=%$ :execute @rem Setup the command line set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar @rem Execute Gradle "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% :end @rem End local scope for the variables with windows NT shell if "%ERRORLEVEL%"=="0" goto mainEnd :fail rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of rem the _cmd.exe /c_ return code! if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 exit /b 1 :mainEnd if "%OS%"=="Windows_NT" endlocal :omega diff --git a/src/it/reyboz/bustorino/backend/Fetcher.java b/src/it/reyboz/bustorino/backend/Fetcher.java index 5af6198..789fdd9 100644 --- a/src/it/reyboz/bustorino/backend/Fetcher.java +++ b/src/it/reyboz/bustorino/backend/Fetcher.java @@ -1,35 +1,36 @@ /* 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; public interface Fetcher { /** * Status codes.
*
* OK: got a response, parsed correctly, obtained some data
* CLIENT_OFFLINE: can't connect to the internet
* SERVER_ERROR: the server replied anything other than HTTP 200, basically
+ * for 404 special constant (see @FiveTAPIFetcher) * 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")
* EMPTY_RESULT_SET: the response is valid and indicates there are no stops\routes\"passaggi"\results for your query
* QUERY_TOO_SHORT: input more characters and retry. */ enum result { - OK, CLIENT_OFFLINE, SERVER_ERROR, PARSER_ERROR, EMPTY_RESULT_SET, QUERY_TOO_SHORT + OK, CLIENT_OFFLINE, SERVER_ERROR, PARSER_ERROR, EMPTY_RESULT_SET, QUERY_TOO_SHORT,SERVER_ERROR_404 } } diff --git a/src/it/reyboz/bustorino/backend/FiveTAPIFetcher.java b/src/it/reyboz/bustorino/backend/FiveTAPIFetcher.java new file mode 100644 index 0000000..1dd7833 --- /dev/null +++ b/src/it/reyboz/bustorino/backend/FiveTAPIFetcher.java @@ -0,0 +1,188 @@ +package it.reyboz.bustorino.backend; + +import android.support.annotation.Nullable; +import android.util.Log; +import org.json.JSONArray; +import org.json.JSONException; +import org.json.JSONObject; + +import java.io.UnsupportedEncodingException; +import java.net.MalformedURLException; +import java.net.URL; +import java.net.URLEncoder; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.ArrayList; +import java.util.Date; +import java.util.Hashtable; +import java.util.concurrent.atomic.AtomicReference; + +public class FiveTAPIFetcher implements ArrivalsFetcher { + + private static final String SECRET_KEY="759C97DC7D115966C30FD9169BB200D9"; + private static final String DEBUG_NAME = "FiveTAPIFetcher"; + + @Override + public Palina ReadArrivalTimesAll(String stopID, AtomicReference res) { + //set the date for the request as now + + Palina p = new Palina(stopID); + + //request parameters + String response = performAPIRequest(QueryType.ARRIVALS,stopID,res); + if(response==null){ + //an error has occured, details in res.get() + return p; + } + + /* + Slight problem: + "longName": ==> DESCRIPTION + "name": "13N", + "departures": [ + { + "arrivalTimeInt": 1272, + "time": "21:12", + "rt": false + }] + "lineType": "URBANO" ==> URBANO can be either bus or tram or METRO + */ + JSONArray arr; + try{ + arr = new JSONArray(response); + String type; + Route.Type routetype; + for(int i =0; i res){ + Date d = new Date(); + URL u; + Hashtable param = new Hashtable<>(); + + try { + String address = getURLForOperation(t,stopID); + param.put("TOKEN",getAccessToken(address,d)); + param.put("TIMESTAMP",String.valueOf(d.getTime())); + param.put("Accept-Encoding","gzip"); + param.put("Connection","Keep-Alive"); + u = new URL(address); + } catch (UnsupportedEncodingException | NoSuchAlgorithmException |MalformedURLException e) { + e.printStackTrace(); + res.set(result.PARSER_ERROR); + return null; + } + String response = networkTools.queryURL(u,res,param); + if(response==null) { + if(res.get()==result.SERVER_ERROR_404) { + Log.w(DEBUG_NAME,"Got 404, either the server failed, or the stop was not found, or the hack is not working anymore"); + res.set(result.EMPTY_RESULT_SET); + }; + } + return response; + } + + /** + * Get the Token needed to access the API + * @param URL the URL of the request + * @return token + * @throws NoSuchAlgorithmException if the system doesn't support MD5 + * @throws UnsupportedEncodingException if we made mistakes in writing utf-8 + */ + static String getAccessToken(String URL,Date d) throws NoSuchAlgorithmException,UnsupportedEncodingException{ + MessageDigest md = MessageDigest.getInstance("MD5"); + String strippedQuery = URL.replace("http://www.5t.torino.it/proxyws",""); + //return the time in milliseconds + long timeMilli = d.getTime(); + StringBuilder sb = new StringBuilder(); + sb.append(strippedQuery); + sb.append(timeMilli); + sb.append(SECRET_KEY); + String stringToBeHashed = sb.toString(); + md.reset(); + byte[] data = md.digest(stringToBeHashed.getBytes("UTF-8")); + sb = new StringBuilder(); + for (byte b : data){ + sb.append(String.format("%02x",b)); + } + String result = sb.toString(); + Log.d(DEBUG_NAME,"getting token:\n\treduced URL: "+strippedQuery+"\n\ttimestamp: "+timeMilli+"\nTOKEN:"+result.toLowerCase()); + return result.toLowerCase(); + } + + /** + * Get the right url for the operation you are doing, to be fed into the queryURL method + * @param t type of operation + * @param stopID stop on which you are working on + * @return the Url to go to + * @throws UnsupportedEncodingException if it cannot be converted to utf-8 + */ + public static String getURLForOperation(QueryType t,@Nullable String stopID) throws UnsupportedEncodingException { + final StringBuilder sb = new StringBuilder(); + sb.append("http://www.5t.torino.it/proxyws/ws2.1/rest/stops/"); + switch (t){ + case ARRIVALS: + sb.append(URLEncoder.encode(stopID,"utf-8")); + sb.append("/departures"); + break; + case DETAILS: + sb.append(URLEncoder.encode(stopID,"utf-8")); + sb.append("/branches/details"); + break; + case STOPS: + sb.append("all"); + break; + case STOPS_VERSION: + sb.append("version"); + break; + } + return sb.toString(); + } + + enum QueryType { + ARRIVALS, DETAILS,STOPS, STOPS_VERSION + } +} diff --git a/src/it/reyboz/bustorino/backend/Palina.java b/src/it/reyboz/bustorino/backend/Palina.java index 813c279..015faed 100644 --- a/src/it/reyboz/bustorino/backend/Palina.java +++ b/src/it/reyboz/bustorino/backend/Palina.java @@ -1,218 +1,234 @@ /* 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; import java.util.ArrayList; import java.util.Collections; import java.util.List; /** * Timetable for multiple routes.
*
* Apparently "palina" and a bunch of other terms can't really be translated into English.
* Not in a way that makes sense and keeps the code readable, at least. */ public class Palina extends Stop { private ArrayList routes = new ArrayList<>(); public Palina(String stopID) { super(stopID); } /** * Adds a route to the timetable. * * @param routeID name * @param type bus, underground, railway, ... * @param destinazione end of line\terminus (underground stations have the same ID for both directions) * @return array index for this route */ public int addRoute(String routeID, String destinazione, Route.Type type) { this.routes.add(new Route(routeID, destinazione, type, new ArrayList(6))); return this.routes.size() - 1; // last inserted element and pray that direct access to ArrayList elements really is direct } + public int addRoute(Route r){ + this.routes.add(r); + return this.routes.size()-1; + } /** * Adds a timetable entry to a route. * * @param TimeGTT time in GTT format (e.g. "11:22*") * @param arrayIndex position in the array for this route (returned by addRoute) */ public void addPassaggio(String TimeGTT, int arrayIndex) { this.routes.get(arrayIndex).addPassaggio(TimeGTT); } + /** + * Count routes with missing directions + * @return number + */ + public int countRoutesWithMissingDirections(){ + int i = 0; + for (Route r : routes){ + if(r.destinazione==null||r.destinazione.equals("")) + i++; + } + return i; + } // /** // * Clears a route timetable (or creates an empty route) and returns its index // * // * @param routeID name // * @param destinazione end of line\terminus // * @return array index for this route // */ // public int updateRoute(String routeID, String destinazione) { // int s = this.routes.size(); // RouteInternal r; // // for(int i = 0; i < s; i++) { // r = routes.get(i); // if(r.name.compareTo(routeID) == 0 && r.destinazione.compareTo(destinazione) == 0) { // // capire se è possibile che ci siano stessa linea e stessa destinazione su 2 righe diverse del sito e qui una sovrascrive l'altra (probabilmente no) // r.updateFlag(); // r.deletePassaggio(); // return i; // } // } // // return this.addRoute(routeID, destinazione); // } // // /** // * Deletes routes marked as "not updated" (= disappeared from the GTT website\API\whatever). // * Sets all remaining routes to "not updated" because that's how this contraption works. // */ // public void finishUpdatingRoutes() { // RouteInternal r; // // for(Iterator itr = this.routes.iterator(); itr.hasNext(); ) { // r = itr.next(); // if(r.unupdateFlag()) { // itr.remove(); // } // } // } // /** // * Gets the current timetable for a route. Returns null if the route doesn't exist. // * This is slower than queryRouteByIndex. // * // * @return timetable (passaggi) // */ // public List queryRoute(String routeID) { // for(Route r : this.routes) { // if(routeID.equals(r.name)) { // return r.getPassaggi(); // } // } // // return null; // } // // /** // * Gets the current timetable for this route, from its index in the array. // * // * @return timetable (passaggi) // */ // public List queryRouteByIndex(int index) { // return this.routes.get(index).getPassaggi(); // } /** * Gets every route and its timetable. * * @return routes and timetables. */ public List queryAllRoutes() { return this.routes; } public void sortRoutes() { Collections.sort(this.routes); } // /** // * Route with terminus (destinazione) and timetables (passaggi), internal implementation. // * // * Contains mostly the same data as the Route public class, but methods are quite different and extending Route doesn't really work, here. // */ // private final class RouteInternal { // public final String name; // public final String destinazione; // private boolean updated; // private List passaggi; // // /** // * Creates a new route and marks it as "updated", since it's new. // * // * @param routeID name // * @param destinazione end of line\terminus // */ // public RouteInternal(String routeID, String destinazione) { // this.name = routeID; // this.destinazione = destinazione; // this.passaggi = new LinkedList<>(); // this.updated = true; // } // // /** // * Adds a time (passaggio) to the timetable for this route // * // * @param TimeGTT time in GTT format (e.g. "11:22*") // */ // public void addPassaggio(String TimeGTT) { // this.passaggi.add(new Passaggio(TimeGTT)); // } // // /** // * Deletes al times (passaggi) from the timetable. // */ // public void deletePassaggio() { // this.passaggi = new LinkedList<>(); // this.updated = true; // } // // /** // * Sets the "updated" flag to false. // * // * @return previous state // */ // public boolean unupdateFlag() { // if(this.updated) { // this.updated = false; // return true; // } else { // return false; // } // } // // /** // * Sets the "updated" flag to true. // * // * @return previous state // */ // public boolean updateFlag() { // if(this.updated) { // return true; // } else { // this.updated = true; // return false; // } // } // // /** // * Exactly what it says on the tin. // * // * @return times from the timetable // */ // public List getPassaggi() { // return this.passaggi; // } // } } \ No newline at end of file diff --git a/src/it/reyboz/bustorino/backend/Route.java b/src/it/reyboz/bustorino/backend/Route.java index ab62767..ad48be7 100644 --- a/src/it/reyboz/bustorino/backend/Route.java +++ b/src/it/reyboz/bustorino/backend/Route.java @@ -1,111 +1,140 @@ /* 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; +import java.util.ArrayList; import java.util.List; public class Route implements Comparable { public final String name; public final String destinazione; public final List passaggi; public final Type type; + public final String description; public enum Type { // "long distance" sono gli extraurbani. BUS, LONG_DISTANCE_BUS, METRO, RAILWAY, TRAM } /** * Constructor. * * @param name route ID * @param destinazione terminus\end of line * @param type bus, long distance bus, underground, and so on * @param passaggi timetable, a good choice is an ArrayList of size 6 * @see Palina Palina.addRoute() method */ public Route(String name, String destinazione, Type type, List passaggi) { this.name = name; this.destinazione = destinazione; this.passaggi = passaggi; this.type = type; + this.description = null; + } + + /** + * Constructor used by the new Api + * @param name stop Name + * @param t optional type + * @param description line rough description + */ + public Route(String name,Type t,String description){ + this.name = name; + this.type = t; + this.passaggi = new ArrayList<>(); + this.destinazione = null; + this.description = description; } /** * Exactly what it says on the tin. * * @return times from the timetable */ public List getPassaggi() { return this.passaggi; } /** * Adds a time (passaggio) to the timetable for this route * * @param TimeGTT time in GTT format (e.g. "11:22*") */ public void addPassaggio(String TimeGTT) { this.passaggi.add(new Passaggio(TimeGTT)); } + public static String getPassageString(String input,boolean realtime){ + String time = input.trim(); + if(time.contains("*")){ + if(realtime) return time; + else return time.substring(0,time.length()-1); + } else{ + if(realtime) return time.concat("*"); + else return time; + } + } + @Override public int compareTo(@NonNull Route other) { int res; int thisAsInt, otherAsInt; // sorting by numbers alone yields a far more "natural" result (36N goes before 2024, 95B next to 95, and the like) thisAsInt = networkTools.failsafeParseInt(this.name.replaceAll("[^0-9]", "")); otherAsInt = networkTools.failsafeParseInt(other.name.replaceAll("[^0-9]", "")); // compare. // numeric route IDs if(thisAsInt != 0 && otherAsInt != 0) { res = thisAsInt - otherAsInt; if(res != 0) { return res; } } else { // non-numeric res = this.name.compareTo(other.name); if (res != 0) { return res; } } // try comparing their destination - - res = this.destinazione.compareTo(other.destinazione); - if(res != 0) { - return res; + if(this.destinazione!=null){ + res = this.destinazione.compareTo(other.destinazione); + if(res != 0) { + return res; + } } // probably useless, but... last attempt. if(this.type != other.type) { // ordinal() is evil or whatever, who cares. return this.type.ordinal() - other.type.ordinal(); } return 0; } } diff --git a/src/it/reyboz/bustorino/backend/networkTools.java b/src/it/reyboz/bustorino/backend/networkTools.java index 1cc552d..6109b60 100644 --- a/src/it/reyboz/bustorino/backend/networkTools.java +++ b/src/it/reyboz/bustorino/backend/networkTools.java @@ -1,126 +1,163 @@ /* 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.backend; import android.support.annotation.Nullable; import java.io.BufferedInputStream; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; +import java.util.Map; import java.util.Scanner; import java.util.concurrent.atomic.AtomicReference; public abstract class networkTools { static String getDOM(final URL url, final AtomicReference res) { //Log.d("asyncwget", "Catching URL in background: " + uri[0]); HttpURLConnection urlConnection; StringBuilder result = null; try { urlConnection = (HttpURLConnection) url.openConnection(); } catch(IOException e) { res.set(Fetcher.result.SERVER_ERROR); return null; } try { InputStream in = new BufferedInputStream( urlConnection.getInputStream()); BufferedReader reader = new BufferedReader( new InputStreamReader(in)); result = new StringBuilder(); String line; while ((line = reader.readLine()) != null) { result.append(line); } } catch (Exception e) { //Log.e("asyncwget", e.getMessage()); } finally { if (urlConnection != null) { urlConnection.disconnect(); } } if (result == null) { res.set(Fetcher.result.SERVER_ERROR); return null; } res.set(Fetcher.result.PARSER_ERROR); // will be set to "OK" later, this is a safety net in case StringBuilder returns null, the website returns an HTTP 204 or something like that. return result.toString(); } - @Nullable - static String queryURL(URL url, AtomicReference res) { + static String queryURL(URL url, AtomicReference res){ + return queryURL(url,res,null); + } + @Nullable + static String queryURL(URL url, AtomicReference res, Map headers) { HttpURLConnection urlConnection; InputStream in; String s; try { urlConnection = (HttpURLConnection) url.openConnection(); } catch(IOException e) { res.set(Fetcher.result.SERVER_ERROR); // even when offline, urlConnection works fine. WHY. return null; } // TODO: make this configurable? urlConnection.setConnectTimeout(5000); urlConnection.setReadTimeout(10000); + if(headers!= null){ + for(String key : headers.keySet()){ + urlConnection.setRequestProperty(key,headers.get(key)); + } + } res.set(Fetcher.result.SERVER_ERROR); // will be set to OK later try { in = urlConnection.getInputStream(); } catch (Exception e) { + try { + if(urlConnection.getResponseCode()==404) + res.set(Fetcher.result.SERVER_ERROR_404); + } catch (IOException e2) { + e2.printStackTrace(); + } return null; + } s = streamToString(in); try { in.close(); } catch(Exception ignored) {} try { urlConnection.disconnect(); } catch(Exception ignored) {} if(s.length() == 0) { return null; } else { return s; } } // https://stackoverflow.com/a/5445161 static String streamToString(InputStream is) { Scanner s = new Scanner(is, "UTF-8").useDelimiter("\\A"); return s.hasNext() ? s.next() : ""; } + /** + * New method, maybe faster, to read inputStream + * also see https://stackoverflow.com/a/5445161 + * @param is what to read + * @return the String Read + * @throws IOException from the InputStreamReader + */ + static String parseStreamToString(InputStream is) throws IOException{ + final int bufferSize = 1024; + final char[] buffer = new char[bufferSize]; + final StringBuilder out = new StringBuilder(); + InputStreamReader in = new InputStreamReader(is, "UTF-8"); + int rsz= in.read(buffer, 0, buffer.length); + while( rsz >0) { + out.append(buffer, 0, rsz); + rsz = in.read(buffer, 0, buffer.length); + } + return out.toString(); + + } + static int failsafeParseInt(String str) { try { return Integer.parseInt(str); } catch(NumberFormatException e) { return 0; } } } diff --git a/src/it/reyboz/bustorino/fragments/FragmentHelper.java b/src/it/reyboz/bustorino/fragments/FragmentHelper.java index 3dfcdf7..aae64c4 100644 --- a/src/it/reyboz/bustorino/fragments/FragmentHelper.java +++ b/src/it/reyboz/bustorino/fragments/FragmentHelper.java @@ -1,212 +1,212 @@ /* BusTO (fragments) Copyright (C) 2018 Fabio Mazza 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.fragments; import android.database.sqlite.SQLiteDatabase; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentTransaction; import android.support.v4.widget.SwipeRefreshLayout; import android.util.Log; import it.reyboz.bustorino.R; import it.reyboz.bustorino.backend.Fetcher; import it.reyboz.bustorino.backend.Palina; import it.reyboz.bustorino.backend.Stop; import it.reyboz.bustorino.middleware.*; import java.util.List; /** * Helper class to manage the fragments and their needs */ public class FragmentHelper { GeneralActivity act; private Stop lastSuccessfullySearchedBusStop; + //support for multiple frames private int primaryFrameLayout,secondaryFrameLayout, swipeRefID; public static final int NO_FRAME = -3; UserDB userDB; StopsDB stopsDB; public FragmentHelper(GeneralActivity act, int swipeRefID, int mainFrame) { this(act,swipeRefID,mainFrame,NO_FRAME); } public FragmentHelper(GeneralActivity act, int swipeRefID, int primaryFrameLayout, int secondaryFrameLayout) { this.act = act; this.swipeRefID = swipeRefID; this.primaryFrameLayout = primaryFrameLayout; this.secondaryFrameLayout = secondaryFrameLayout; stopsDB = new StopsDB(act); userDB = new UserDB(act); } public Stop getLastSuccessfullySearchedBusStop() { return lastSuccessfullySearchedBusStop; } public void setLastSuccessfullySearchedBusStop(Stop stop) { this.lastSuccessfullySearchedBusStop = stop; } /** * Called when you need to create a fragment for a specified Palina * @param p the Stop that needs to be displayed */ public void createOrUpdateStopFragment(Palina p){ boolean refreshing; ResultListFragment listFragment; if(act==null) { //SOMETHING WENT VERY WRONG return; } SwipeRefreshLayout srl = (SwipeRefreshLayout) act.findViewById(swipeRefID); FragmentManager fm = act.getSupportFragmentManager(); - //DON'T UNDERSTAND WHY BUT IT SAYS IT'S NULL REFERENCE if(srl.isRefreshing()) refreshing=true; else if(fm.findFragmentById(R.id.resultFrame) instanceof ResultListFragment) { listFragment = (ResultListFragment) fm.findFragmentById(R.id.resultFrame); refreshing = listFragment.isFragmentForTheSameStop(p); } else refreshing = false; setLastSuccessfullySearchedBusStop(p); if(!refreshing) { //set the String to be displayed on the fragment String displayName = p.getStopDisplayName(); String displayStuff; if (displayName != null && displayName.length() > 0) { displayStuff = p.ID.concat(" - ").concat(displayName); } else { displayStuff = p.ID; } listFragment = ResultListFragment.newInstance(ResultListFragment.TYPE_LINES,displayStuff); attachFragmentToContainer(fm,listFragment,true,ResultListFragment.getFragmentTag(p)); } else { Log.d("BusTO", "Same bus stop, accessing existing fragment"); listFragment = (ResultListFragment) fm.findFragmentById(R.id.resultFrame); } listFragment.setListAdapter(new PalinaAdapter(act.getApplicationContext(),p)); act.hideKeyboard(); if (act instanceof FragmentListener) ((FragmentListener) act).readyGUIfor(ResultListFragment.TYPE_LINES); toggleSpinner(false); } /** * Called when you need to display the results of a search of stops * @param resultList the List of stops found * @param query String queried */ public void createFragmentFor(List resultList,String query){ act.hideKeyboard(); ResultListFragment listfragment = ResultListFragment.newInstance(ResultListFragment.TYPE_STOPS); attachFragmentToContainer(act.getSupportFragmentManager(),listfragment,false,"search_"+query); if (act instanceof FragmentListener) ((FragmentListener) act).readyGUIfor(ResultListFragment.TYPE_STOPS); listfragment.setListAdapter(new StopAdapter(act.getApplicationContext(), resultList)); toggleSpinner(false); } /** * Wrapper for toggleSpinner in Activity * @param on new status of spinner system */ public void toggleSpinner(boolean on){ if (act instanceof FragmentListener) ((FragmentListener) act).toggleSpinner(on); else { SwipeRefreshLayout srl = (SwipeRefreshLayout) act.findViewById(swipeRefID); srl.setRefreshing(false); } } /** * Attach a new fragment to a cointainer * @param fm the FragmentManager * @param fragment the Fragment * @param sendToSecondaryFrame needs to be displayed in secondary frame or not * @param tag tag for the fragment */ private void attachFragmentToContainer(FragmentManager fm,Fragment fragment, boolean sendToSecondaryFrame, String tag){ FragmentTransaction ft = fm.beginTransaction(); if(sendToSecondaryFrame && secondaryFrameLayout!=NO_FRAME) ft.replace(secondaryFrameLayout,fragment,tag); else ft.replace(primaryFrameLayout,fragment,tag); ft.addToBackStack("state_"+tag); ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_CLOSE); ft.commit(); //fm.executePendingTransactions(); } /* Set of methods to "wrap" database operations */ //Find a way to open databases public void openStopsDB(){ stopsDB.openIfNeeded(); } public String getLocationFromDB(Stop p){ return stopsDB.getLocationFromID(p.ID); } public List getStopRoutesFromDB(String stopID){ return stopsDB.getRoutesByStop(stopID); } public void closeDBIfNeeded(){ stopsDB.closeIfNeeded(); } public String getStopNamefromDB(String stopID){ return stopsDB.getNameFromID(stopID); } /** * Wrapper to show the errors/status that happened * @param res result from Fetcher */ public void showErrorMessage(Fetcher.result res){ //TODO: implement a common set of errors for all fragments switch (res){ case OK: break; case CLIENT_OFFLINE: act.showMessage(R.string.network_error); break; case SERVER_ERROR: if (act.isConnected()) { act.showMessage(R.string.parsing_error); } else { act.showMessage(R.string.network_error); } case PARSER_ERROR: default: act.showMessage(R.string.internal_error); break; case QUERY_TOO_SHORT: act.showMessage(R.string.query_too_short); break; case EMPTY_RESULT_SET: act.showMessage(R.string.no_bus_stop_have_this_name); break; } } } diff --git a/src/it/reyboz/bustorino/fragments/ResultListFragment.java b/src/it/reyboz/bustorino/fragments/ResultListFragment.java index ad000d3..570c03e 100644 --- a/src/it/reyboz/bustorino/fragments/ResultListFragment.java +++ b/src/it/reyboz/bustorino/fragments/ResultListFragment.java @@ -1,358 +1,358 @@ /* BusTO - Fragments components Copyright (C) 2016 Fabio Mazza 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.fragments; import android.content.Context; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v4.widget.SwipeRefreshLayout; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.*; import android.support.design.widget.FloatingActionButton; import it.reyboz.bustorino.ActivityMain; import it.reyboz.bustorino.R; import it.reyboz.bustorino.backend.FiveTNormalizer; import it.reyboz.bustorino.backend.Palina; import it.reyboz.bustorino.backend.Route; import it.reyboz.bustorino.backend.Stop; import it.reyboz.bustorino.middleware.AsyncAddToFavorites; import it.reyboz.bustorino.middleware.PalinaAdapter; /** * This is a generalized fragment that can be used both for * * */ public class ResultListFragment extends Fragment { // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER private static final String LIST_TYPE = "list-type"; private static final String STOP_TITLE = "messageExtra"; public static final String TYPE_LINES ="lines"; public static final String TYPE_STOPS = "fermate"; private static final String MESSAGE_TEXT_VIEW ="message_text_view"; private String adapterType; private boolean adapterSet = false; private ResultFragmentListener mListener; private TextView messageTextView; FloatingActionButton fabutton; private ListView resultsListView; ListAdapter mListAdapter = null; boolean listShown; public ResultListFragment() { // Required empty public constructor } public ListView getResultsListView() { return resultsListView; } /** * Use this factory method to create a new instance of * this fragment using the provided parameters. * * @param listType whether the list is used for STOPS or LINES (Orari) * @return A new instance of fragment ResultListFragment. */ public static ResultListFragment newInstance(String listType,String eventualStopTitle) { ResultListFragment fragment = new ResultListFragment(); Bundle args = new Bundle(); args.putString(LIST_TYPE, listType); if(eventualStopTitle!=null) args.putString(STOP_TITLE,eventualStopTitle); fragment.setArguments(args); return fragment; } public static ResultListFragment newInstance(String listType){ return newInstance(listType,null); } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (getArguments() != null) { adapterType = getArguments().getString(LIST_TYPE); } } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { hideMyFAB mInterface = new hideMyFAB() { @Override public void showFloatingActionButton(boolean show) { if (fabutton!=null){ if(show) fabutton.show(); else fabutton.hide(); } } }; View root = inflater.inflate(R.layout.fragment_list_view, container, false); messageTextView = (TextView) root.findViewById(R.id.messageTextView); if(adapterType!=null) { resultsListView = (ListView) root.findViewById(R.id.resultsListView); if(adapterType.equals(TYPE_STOPS)) { resultsListView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView parent, View view, int position, long id) { /* * Casting because of Javamerda * @url http://stackoverflow.com/questions/30549485/androids-list-view-parameterized-type-in-adapterview-onitemclicklistener */ Stop busStop = (Stop) parent.getItemAtPosition(position); mListener.createFragmentForStop(busStop.ID); } }); resultsListView.setOnScrollListener(new ListFragmentScrollListener(false,mInterface)); //set the textviewMessage setTextViewMessage(getString(R.string.results)); } else if(adapterType.equals(TYPE_LINES)) { resultsListView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView parent, View view, int position, long id) { String routeName; Route r = (Route) parent.getItemAtPosition(position); routeName = FiveTNormalizer.routeInternalToDisplay(r.name); if (routeName == null) { routeName = r.name; } if (r.destinazione == null || r.destinazione.length() == 0) { Toast.makeText(getContext(), getString(R.string.route_towards_unknown, routeName), Toast.LENGTH_SHORT).show(); } else { Toast.makeText(getContext(), getString(R.string.route_towards_destination, routeName, r.destinazione), Toast.LENGTH_SHORT).show(); } } }); String displayName = getArguments().getString(STOP_TITLE); setTextViewMessage(String.format( getString(R.string.passages), displayName)); resultsListView.setOnScrollListener(new ListFragmentScrollListener(true,mInterface)); } String probablemessage = getArguments().getString(MESSAGE_TEXT_VIEW); if(probablemessage!=null) { //Log.d("BusTO fragment " + this.getTag(), "We have a possible message here in the savedInstaceState: " + probablemessage); messageTextView.setText(probablemessage); messageTextView.setVisibility(View.VISIBLE); } } else Log.d(getString(R.string.list_fragment_debug), "No content root for fragment"); return root; } public boolean isFragmentForTheSameStop(Palina p){ return adapterType.equals(TYPE_LINES) && getTag().equals(getFragmentTag(p)); } public static String getFragmentTag(Palina p){ return p.ID; } @Override public void onResume() { super.onResume(); //Log.d(getString(R.string.list_fragment_debug),"Fragment restored, saved listAdapter is "+(mListAdapter)); if(mListAdapter!=null){ ListAdapter adapter = mListAdapter; mListAdapter = null; setListAdapter(adapter); } mListener.readyGUIfor(adapterType); } @Override public void onPause() { if(adapterType.equals(TYPE_LINES)) { SwipeRefreshLayout reflay = (SwipeRefreshLayout) getActivity().findViewById(R.id.listRefreshLayout); reflay.setEnabled(false); Log.d("BusTO Fragment " + this.getTag(), "RefreshLayout disabled"); } super.onPause(); } @Override public void onAttach(Context context) { super.onAttach(context); if (context instanceof ResultFragmentListener) { mListener = (ResultFragmentListener) context; fabutton = (FloatingActionButton) getActivity().findViewById(R.id.floatingActionButton); } else { throw new RuntimeException(context.toString() + " must implement ResultFragmentListener"); } } @Override public void onDetach() { mListener = null; if(fabutton!=null) fabutton.show(); super.onDetach(); } @Override public void onDestroyView() { resultsListView = null; //Log.d(getString(R.string.list_fragment_debug), "called onDestroyView"); getArguments().putString(MESSAGE_TEXT_VIEW, messageTextView.getText().toString()); super.onDestroyView(); } public void setListAdapter(ListAdapter adapter) { boolean hadAdapter = mListAdapter != null; mListAdapter = adapter; if (resultsListView != null) { resultsListView.setAdapter(adapter); resultsListView.setVisibility(View.VISIBLE); } } /** * This method attaches the FloatingActionButton to the current ListView */ /* TODO REWORKING public void attachFABToListView(){ if(resultsListView!=null) switch(adapterType){ case TYPE_LINES: fabutton.attachToListView(resultsListView, null, new ListFragmentScrollListener()); break; default: fabutton.attachToListView(resultsListView); break; } } */ public void setTextViewMessage(String message){ messageTextView.setText(message); switch (adapterType){ case TYPE_LINES: final ActivityMain activ = (ActivityMain) getActivity(); messageTextView.setClickable(true); messageTextView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { mListener.addLastStopToFavorites(); } }); break; case TYPE_STOPS: messageTextView.setClickable(false); break; } messageTextView.setVisibility(View.VISIBLE); } /** * This methods sets both the adapter and the textviewMessage * Do not call when the fragment shows a list of stops * @param p the palina to get the info from * TODO: overload it so that it can be used also by the STOPS */ /** * This interface is useful for communicating with the activity * The name has been automatically generated (do not blame me) */ public interface ResultFragmentListener extends FragmentListener { /** * Houston, we need another fragment! * * @param ID the Stop ID */ void createFragmentForStop(String ID); void addLastStopToFavorites(); } /** * Classe per gestire gli scroll * */ class ListFragmentScrollListener implements AbsListView.OnScrollListener{ boolean enableRefreshLayout,lastScrollUp=false; int mLastFirstVisibleItem; hideMyFAB fabInterface; public ListFragmentScrollListener(boolean enableRefreshLayout, hideMyFAB iface){ this.enableRefreshLayout = enableRefreshLayout; this.fabInterface = iface; } @Override public void onScrollStateChanged(AbsListView view, int scrollState) { /* * This seems to be a totally useless method */ } @Override public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) { if (firstVisibleItem!=0) { if (mLastFirstVisibleItem < firstVisibleItem) { Log.i("Busto", "Scrolling DOWN"); fabInterface.showFloatingActionButton(false); //lastScrollUp = true; } else if (mLastFirstVisibleItem > firstVisibleItem) { Log.i("Busto", "Scrolling UP"); fabInterface.showFloatingActionButton(true); //lastScrollUp = false; } mLastFirstVisibleItem = firstVisibleItem; } if(enableRefreshLayout){ SwipeRefreshLayout refreshLayout = (SwipeRefreshLayout) getActivity().findViewById(R.id.listRefreshLayout); boolean enable = false; if(view != null && view.getChildCount() > 0){ // check if the first item of the list is visible boolean firstItemVisible = view.getFirstVisiblePosition() == 0; // check if the top of the first item is visible boolean topOfFirstItemVisible = view.getChildAt(0).getTop() == 0; // enabling or disabling the refresh layout enable = firstItemVisible && topOfFirstItemVisible; } refreshLayout.setEnabled(enable); - Log.d(getString(R.string.list_fragment_debug),"onScroll active, first item visible: "+firstVisibleItem+", refreshlayout enabled: "+enable); + //Log.d(getString(R.string.list_fragment_debug),"onScroll active, first item visible: "+firstVisibleItem+", refreshlayout enabled: "+enable); }} } } interface hideMyFAB { void showFloatingActionButton(boolean show); } diff --git a/src/it/reyboz/bustorino/middleware/AsyncDataDownload.java b/src/it/reyboz/bustorino/middleware/AsyncDataDownload.java index bab5f68..0fa2157 100644 --- a/src/it/reyboz/bustorino/middleware/AsyncDataDownload.java +++ b/src/it/reyboz/bustorino/middleware/AsyncDataDownload.java @@ -1,256 +1,254 @@ /* BusTO (middleware) Copyright (C) 2018 Fabio Mazza 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.middleware; import android.database.sqlite.SQLiteDatabase; import android.os.AsyncTask; import android.support.v7.app.AppCompatActivity; import android.util.Log; import it.reyboz.bustorino.R; import it.reyboz.bustorino.backend.*; import it.reyboz.bustorino.fragments.FragmentHelper; import java.lang.ref.WeakReference; import java.util.List; import java.util.concurrent.atomic.AtomicReference; /** * This should be used to download data, but not to display it */ public class AsyncDataDownload extends AsyncTask{ private static final String TAG = "BusTO-DataDownload"; private boolean failedAll = false; private AtomicReference res; private RequestType t; private String query; WeakReference helperRef; public AsyncDataDownload(RequestType type,FragmentHelper fh) { t = type; helperRef = new WeakReference<>(fh); res = new AtomicReference<>(); } @Override protected Object doInBackground(String... params) { RecursionHelper r; boolean success=false; Object result; switch (t){ case ARRIVALS: - r = new RecursionHelper<>(new ArrivalsFetcher[] {new GTTJSONFetcher(), new FiveTScraperFetcher()}); + r = new RecursionHelper<>(new ArrivalsFetcher[] {new FiveTAPIFetcher(),new GTTJSONFetcher(), new FiveTScraperFetcher()}); break; case STOPS: r = new RecursionHelper<>(new StopsFinderByName[] {new GTTStopsFetcher(), new FiveTStopsFetcher()}); break; default: //TODO put error message cancel(true); return null; } - //res.get()!= Fetcher.result.OK FragmentHelper fh = helperRef.get(); + //If the FragmentHelper is null, that means the activity doesn't exist anymore if (fh == null){ - cancel(true); return null; } //Log.d(TAG,"refresh layout reference is: "+fh.isRefreshLayoutReferenceTrue()); while(r.valid()) { - //If the FragmentHelper is null, that means the activity doesn't exist anymore if(this.isCancelled()) { return null; } //get the data from the fetcher switch (t){ case ARRIVALS: ArrivalsFetcher f = (ArrivalsFetcher) r.getAndMoveForward(); Stop lastSearchedBusStop = fh.getLastSuccessfullySearchedBusStop(); Palina p; if(params.length>0) p = f.ReadArrivalTimesAll(params[0],res); //(it's a Palina) else if(lastSearchedBusStop!=null) p = f.ReadArrivalTimesAll(lastSearchedBusStop.ID,res); //(it's a Palina) else { publishProgress(Fetcher.result.QUERY_TOO_SHORT); return null; } publishProgress(res.get()); //Try to find the name of the stop inside StopsDB fh.openStopsDB(); if(p.getStopDisplayName() == null){ p.setStopName(fh.getStopNamefromDB(p.ID)); } fh.closeDBIfNeeded(); //TODO: use ContentProvider when ready /* if(lastSearchedBusStop != null && res.get()== Fetcher.result.OK) { // check that we don't have the same stop if(!lastSearchedBusStop.ID.equals(p.ID)) { // remove it, get new name getNameOrGetRekt(); } else { // searched and it's the same String sn = lastSearchedBusStop.getStopDisplayName(); if(sn == null) { // something really bad happened, start from scratch getNameOrGetRekt(); } else { // "merge" Stop over Palina and we're good to go p.mergeNameFrom(lastSearchedBusStop); } } } else if(res.get()== Fetcher.result.OK) { // we haven't searched anything yet getNameOrGetRekt(); } */ result = p; Log.d(TAG,"Using the ArrivalsFetcher: "+f.getClass()); //TODO: find a way to avoid overloading the user with toasts break; case STOPS: StopsFinderByName finder = (StopsFinderByName) r.getAndMoveForward(); List resultList= finder.FindByName(params[0], this.res); //it's a List fh.openStopsDB(); for (Stop stop : resultList){ if(stop.location == null) stop.location = fh.getLocationFromDB(stop); stop.setRoutesThatStopHere(fh.getStopRoutesFromDB(stop.ID)); } fh.closeDBIfNeeded(); Log.d(TAG,"Using the StopFinderByName: "+finder.getClass()); query =params[0]; result = resultList; //dummy result break; default: result = null; } //find if it went well if(res.get()== Fetcher.result.OK) { return result; } } //at this point, we are sure that the result has been negative failedAll=true; return null; } @Override protected void onProgressUpdate(Fetcher.result... values) { FragmentHelper fh = helperRef.get(); if (fh!=null) for (Fetcher.result r : values){ //TODO: make Toast fh.showErrorMessage(r); } else { Log.w(TAG,"We had to show some progress but activity was destroyed"); } } @Override protected void onPostExecute(Object o) { FragmentHelper fh = helperRef.get(); if(failedAll || o == null || fh == null){ //everything went bad if(fh!=null) fh.toggleSpinner(false); cancel(true); return; } switch (t){ case ARRIVALS: Palina palina = (Palina) o; fh.createOrUpdateStopFragment(palina); break; case STOPS: //this should never be a problem List stopList = (List) o; if(query!=null) fh.createFragmentFor(stopList,query); else Log.e(TAG,"QUERY NULL, COULD NOT CREATE FRAGMENT"); break; case DBUPDATE: break; } } @Override protected void onCancelled() { FragmentHelper fh = helperRef.get(); if (fh!=null) fh.toggleSpinner(false); } @Override protected void onPreExecute() { FragmentHelper fh = helperRef.get(); if (fh!=null) fh.toggleSpinner(true); } public enum RequestType { ARRIVALS,STOPS,DBUPDATE } /** * Run this in a background thread.
* Sets a stop name for this.palina, guaranteed not to be null! **/ //TODO:Implement this /* private void getNameOrGetRekt(Palina p) { String nameMaybe; SQLiteDatabase udb = uDB.getReadableDatabase(); // does it already have a name (for fetchers that support it, or already got from favorites)? nameMaybe = p.getStopDisplayName(); if(nameMaybe != null && nameMaybe.length() > 0) { return; } // ok, let's search favorites. String usernameMaybe = UserDB.getStopUserName(udb, this.p.ID); if(usernameMaybe != null && usernameMaybe.length() > 0) { p.setStopUserName(usernameMaybe); return; } // let's try StopsDB, then. db.openIfNeeded(); nameMaybe = db.getNameFromID(this.p.ID); db.closeIfNeeded(); if(nameMaybe != null && nameMaybe.length() > 0) { p.setStopName(nameMaybe); return; } // no name to be found anywhere, don't bother searching it next time p.setStopName(""); }*/ } diff --git a/src/it/reyboz/bustorino/middleware/PalinaAdapter.java b/src/it/reyboz/bustorino/middleware/PalinaAdapter.java index 83e324e..6a46366 100644 --- a/src/it/reyboz/bustorino/middleware/PalinaAdapter.java +++ b/src/it/reyboz/bustorino/middleware/PalinaAdapter.java @@ -1,149 +1,149 @@ /* 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.middleware; import android.content.Context; import android.support.annotation.NonNull; import android.util.TypedValue; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.TextView; import java.util.List; import it.reyboz.bustorino.R; import it.reyboz.bustorino.backend.Palina; import it.reyboz.bustorino.backend.Passaggio; import it.reyboz.bustorino.backend.Route; /** * This once was a ListView Adapter for BusLine[]. * * Thanks to Framentos developers for the guide: * http://www.framentos.com/en/android-tutorial/2012/07/16/listview-in-android-using-custom-listadapter-and-viewcache/# * * @author Valerio Bozzolan * @author Ludovico Pavesi */ public class PalinaAdapter extends ArrayAdapter { private LayoutInflater li; private static int row_layout = R.layout.entry_bus_line_passage; private static final int metroBg = R.drawable.route_background_metro; private static final int busBg = R.drawable.route_background_bus; private static final int extraurbanoBg = R.drawable.route_background_bus_long_distance; private static final int busIcon = R.drawable.bus; private static final int trainIcon = R.drawable.subway; private static final int tramIcon = R.drawable.tram; //private static final int cityIcon = R.drawable.city; // hey look, a pattern! private static class ViewHolder { TextView rowStopIcon; TextView rowRouteDestination; TextView rowRouteTimetable; } public PalinaAdapter(Context context, Palina p) { super(context, row_layout, p.queryAllRoutes()); li = LayoutInflater.from(context); } /** * Some parts taken from the AdapterBusLines class.
* Some parts inspired by these enlightening tutorials:
* http://www.simplesoft.it/android/guida-agli-adapter-e-le-listview-in-android.html
* https://www.codeofaninja.com/2013/09/android-viewholder-pattern-example.html
* And some other bits and bobs TIRATI FUORI DAL NULLA CON L'INTUIZIONE INTELLETTUALE PERCHÉ * SEMBRA CHE NESSUNO ABBIA LA MINIMA IDEA DI COME FUNZIONA UN ADAPTER SU ANDROID. */ @NonNull @Override public View getView(int position, View convertView, @NonNull ViewGroup parent) { ViewHolder vh; if(convertView == null) { // INFLATE! // setting a parent here is not supported and causes a fatal exception, apparently. convertView = li.inflate(row_layout, null); // STORE TEXTVIEWS! vh = new ViewHolder(); vh.rowStopIcon = (TextView) convertView.findViewById(R.id.routeID); vh.rowRouteDestination = (TextView) convertView.findViewById(R.id.routeDestination); vh.rowRouteTimetable = (TextView) convertView.findViewById(R.id.routesThatStopHere); // STORE VIEWHOLDER IN\ON\OVER\UNDER\ABOVE\BESIDE THE VIEW! convertView.setTag(vh); } else { // RECOVER THIS STUFF! vh = (ViewHolder) convertView.getTag(); } Route route = getItem(position); vh.rowStopIcon.setText(route.name); - if(route.destinazione.length() == 0) { + if(route.destinazione==null || route.destinazione.length() == 0) { vh.rowRouteDestination.setVisibility(View.GONE); } else { // View Holder Pattern(R) renders each element from a previous one: if the other one had an invisible rowRouteDestination, we need to make it visible. vh.rowRouteDestination.setVisibility(View.VISIBLE); vh.rowRouteDestination.setText(route.destinazione); } switch (route.type) { case BUS: default: // convertView could contain another background, reset it vh.rowStopIcon.setBackgroundResource(busBg); vh.rowRouteDestination.setCompoundDrawablesWithIntrinsicBounds(busIcon, 0, 0, 0); break; case LONG_DISTANCE_BUS: vh.rowStopIcon.setBackgroundResource(extraurbanoBg); vh.rowRouteDestination.setCompoundDrawablesWithIntrinsicBounds(busIcon, 0, 0, 0); break; case METRO: vh.rowStopIcon.setTextSize(TypedValue.COMPLEX_UNIT_SP, 14); vh.rowStopIcon.setBackgroundResource(metroBg); vh.rowRouteDestination.setCompoundDrawablesWithIntrinsicBounds(trainIcon, 0, 0, 0); break; case RAILWAY: vh.rowStopIcon.setBackgroundResource(busBg); vh.rowRouteDestination.setCompoundDrawablesWithIntrinsicBounds(trainIcon, 0, 0, 0); break; case TRAM: // never used but whatever. vh.rowStopIcon.setBackgroundResource(busBg); vh.rowRouteDestination.setCompoundDrawablesWithIntrinsicBounds(tramIcon, 0, 0, 0); break; } List passaggi = route.passaggi; if(passaggi.size() == 0) { vh.rowRouteTimetable.setText(R.string.no_passages); } else { String resultString = ""; for(Passaggio passaggio : passaggi) { // "+" calls concat() and some other stuff internally, this should be faster resultString = resultString.concat(passaggio.toString()).concat(" "); } vh.rowRouteTimetable.setText(resultString); } return convertView; } } diff --git a/src/it/reyboz/bustorino/middleware/RecursionHelper.java b/src/it/reyboz/bustorino/middleware/RecursionHelper.java index 5b4614a..4024297 100644 --- a/src/it/reyboz/bustorino/middleware/RecursionHelper.java +++ b/src/it/reyboz/bustorino/middleware/RecursionHelper.java @@ -1,61 +1,69 @@ /* 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.middleware; /** * Holds some global data used by recursive methods to try every fetcher until you get some data.
* Well, those methods are now iterative but the name stuck... * * @param ArrivalsFetcher, StopsFinder, ... */ public class RecursionHelper { private int pos = 0; private final int len; private final FetcherKind[] fetchers; public RecursionHelper(FetcherKind[] fetchers) { this.fetchers = fetchers; this.len = fetchers.length; } /** * Go back to square one. Or zero since arrays are zero-indexed. */ public void reset() { this.pos = 0; } /** * Can you give me a valid Fetcher without throwing exceptions? * * @return boolean */ public boolean valid() { return this.pos < len; } + /** + * Have we reached the end of the fetchers + * @return + */ + public boolean isLast(){ + return this.pos ==len-1; + } + /** * Give me a fetcher (use valid() to check that it exists BEFORE requesting it), move to next * * @return the fetcher\finder\whatever */ public FetcherKind getAndMoveForward() { return fetchers[this.pos++]; } } \ No newline at end of file