diff --git a/src/it/reyboz/bustorino/backend/FiveTScraperFetcher.java b/src/it/reyboz/bustorino/backend/FiveTScraperFetcher.java
index 94e0071..776f17c 100644
--- a/src/it/reyboz/bustorino/backend/FiveTScraperFetcher.java
+++ b/src/it/reyboz/bustorino/backend/FiveTScraperFetcher.java
@@ -1,200 +1,200 @@
/*
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 org.jsoup.Jsoup;
+import org.jsoup.nodes.Document;
+import org.jsoup.nodes.Element;
+import org.jsoup.select.Elements;
+
import java.net.URL;
import java.net.URLEncoder;
import java.util.concurrent.atomic.AtomicReference;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
-
-import org.jsoup.Jsoup;
-import org.jsoup.nodes.Document;
-import org.jsoup.nodes.Element;
-import org.jsoup.select.Elements;
//import android.util.Log;
/**
* Contains large chunks of code taken from the old GTTSiteSucker, AsyncWget and AsyncWgetBusStopFromBusStopID classes.
*
* «BusTO, because sucking happens»
*
* @author Valerio Bozzolan
*/
public class FiveTScraperFetcher implements ArrivalsFetcher {
/**
* Execute regexes.
*
* @param needle Regex
* @param haystack Entire string
* @return Matched string
*/
public static String grep(String needle, String haystack) {
String matched = null;
Matcher matcher = Pattern.compile(
needle).matcher(haystack);
if (matcher.find()) {
matched = matcher.group(1);
}
return matched;
}
@Override
public Palina ReadArrivalTimesAll(final String routeID, final AtomicReference res) {
Palina p = new Palina();
int routeIndex;
String responseInDOMFormatBecause5THaveAbsolutelyNoIdeaWhatJSONWas = null;
try {
responseInDOMFormatBecause5THaveAbsolutelyNoIdeaWhatJSONWas = networkTools.getDOM(new URL("http://www.5t.torino.it/5t/trasporto/arrival-times-byline.jsp?action=getTransitsByLine&shortName=" + URLEncoder.encode(routeID, "utf-8")), res);
} catch (Exception e) {
res.set(result.PARSER_ERROR);
}
if(responseInDOMFormatBecause5THaveAbsolutelyNoIdeaWhatJSONWas == null) {
// result already set in getDOM()
return p;
}
Document doc = Jsoup.parse(responseInDOMFormatBecause5THaveAbsolutelyNoIdeaWhatJSONWas);
Element span = doc.select("span").first();
String busStopID = grep("^(.+) ", span.html());
if (busStopID == null) {
//Log.e("BusStop", "Empty busStopID from " + span.html());
res.set(result.EMPTY_RESULT_SET);
return p;
}
// this also appears when no stops are found, but that case has already been handled above
Element error = doc.select("p.errore").first();
if (error != null) {
res.set(result.SERVER_ERROR);
return p;
}
String busStopName = grep("^.+ (.+)", span.html()); // The first "dot" is the single strange space character in the middle of "39{HERE→} {←HERE}PORTA NUOVA"
if (busStopName == null) {
//Log.e("BusStop", "Empty busStopName from " + span.html());
res.set(result.SERVER_ERROR);
return p;
}
p.setStopName(busStopName.trim());
// Every table row is a busLine
Elements trs = doc.select("table tr");
for (Element tr : trs) {
Element line = tr.select("td.line a").first();
if (!line.hasText()) {
res.set(result.SERVER_ERROR);
return p;
}
String busLineName = line.text();
// this is yet another ID, that has no known use so we can safely ignore it
// Integer busLineID = string2Integer(
// grep(
// "([0-9]+)$",
// line.attr("href")
// )
// );
if (busLineName == null) {
res.set(result.SERVER_ERROR);
return p;
}
// this fetcher doesn't support railways and probably they've removed METRO too, but anyway...
if(busLineName.equals("METRO")) {
routeIndex = p.addRoute(busLineName, "", Route.Type.METRO);
} else {
if(busLineName.length() >= 4) {
boolean isExtraurbano = true;
for(int ch = 0; ch < busLineName.length(); ch++) {
if(!Character.isDigit(busLineName.charAt(ch))) {
isExtraurbano = false;
break;
}
}
if(isExtraurbano) {
routeIndex = p.addRoute(busLineName, "", Route.Type.LONG_DISTANCE_BUS);
} else {
routeIndex = p.addRoute(busLineName, "", Route.Type.BUS);
}
} else {
routeIndex = p.addRoute(busLineName, "", Route.Type.BUS);
}
}
// Every busLine have passages
Elements tds = tr.select("td:not(.line)");
for (Element td : tds) {
//boolean isInRealTime = td.select("i").size() > 0;
//td.select("i").remove(); // Stripping "*"
String time = td.text().trim();
if (time.equals("")) {
// Yes... Sometimes there is an EMPTY td ._.
continue;
}
p.addPassaggio(time, routeIndex);
}
}
p.sortRoutes();
res.set(result.OK);
return p;
}
// preserved for future generations:
// /*
// * I've sent many emails to the public email info@5t.torino.it to write down something like:
// * «YOUR SITE EXPLODE IF I USE **YOUR** BUS LINE IDs STARTING WITH ZERO!!!!!»
// * So, waiting for a response, I must purge the busStopID from "0"s .__.
// * IN YOUR FACE 5T/GTT. IN YOUR FACE.
// *
// * @param busStopID
// * @return parseInt(busStopID)
// * @antifeatured yep
// * @notabug yep
// * @wontfix yep
// */
// protected final String getFilteredBusStopID(String busStopID) {
// /*
// * OK leds me ezplain why 'm dong this shot of shittt. OK zo swhy?
// * Bhumm thads because the GTT/5T site-"developer" ids obviusli drunk.
// */
// String enableGTTDeveloperSimulator = "on"; // DRUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUNK
// final char ZZZZZZZEEEEROOOOOO = '0'; // DRUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUNK
// char[] cinquettiBarraGtt = busStopID.toCharArray(); // DRUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUNK
// int merda = 0; // DRUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUNK
// while (merda < cinquettiBarraGtt.length && cinquettiBarraGtt[merda] == ZZZZZZZEEEEROOOOOO) {
// // COMPLETELELELLELEEELY DRUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUNK
// Log.i("AsyncWgetBusStop", "scimmie ubriache assunte per tirar su il sito 5T/GTT"); // DR
// merda++; // DRUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUNK
// } // DRUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUNK
// String trenoDiMerda = ""; // DRUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUNK
// for (; merda < cinquettiBarraGtt.length; merda++) { // DRUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUNK
// trenoDiMerda += cinquettiBarraGtt[merda]; // DRUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUNK
// } // DRUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUNK
// enableGTTDeveloperSimulator = "off"; // DRUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUNK
//
// return trenoDiMerda;
// }
}
diff --git a/src/it/reyboz/bustorino/backend/FiveTStopsFetcher.java b/src/it/reyboz/bustorino/backend/FiveTStopsFetcher.java
index fa1657f..3e574ab 100644
--- a/src/it/reyboz/bustorino/backend/FiveTStopsFetcher.java
+++ b/src/it/reyboz/bustorino/backend/FiveTStopsFetcher.java
@@ -1,110 +1,114 @@
/*
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.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
+import java.util.Collections;
import java.util.List;
import java.util.concurrent.atomic.AtomicReference;
/**
* Once was asynchronous BusStop[] fetcher from a query, code mostly taken from
* AsyncWgetBusStopSuggestions (by Valerio Bozzolan)
*
* @see FiveTScraperFetcher
*/
public class FiveTStopsFetcher implements StopsFinderByName {
@Override
public List FindByName(String name, AtomicReference res) {
- ArrayList busStops = new ArrayList<>();
+ // TODO: limit?
+ ArrayList busStops = new ArrayList<>(15);
String stopID;
String stopName;
String stopLocation;
//Stop busStop;
if(name.length() < 3) {
res.set(result.QUERY_TOO_SHORT);
return busStops;
}
String responseInDOMFormatBecause5THaveAbsolutelyNoIdeaWhatJSONWas;
URL u;
try {
u = new URL("http://www.5t.torino.it/5t/trasporto/stop-lookup.jsp?action=search&stopShortName=" + URLEncoder.encode(name, "utf-8"));
} catch(Exception e) {
res.set(Fetcher.result.PARSER_ERROR);
return busStops;
}
responseInDOMFormatBecause5THaveAbsolutelyNoIdeaWhatJSONWas = networkTools.getDOM(u, res);
if (responseInDOMFormatBecause5THaveAbsolutelyNoIdeaWhatJSONWas == null) {
// result already set in getDOM()
return busStops;
}
Document doc = Jsoup.parse(responseInDOMFormatBecause5THaveAbsolutelyNoIdeaWhatJSONWas);
// Find bus stops
Elements lis = doc.getElementsByTag("li");
for(Element li : lis) {
Elements spans = li.getElementsByTag("span");
// busStopID
try {
stopID = FiveTNormalizer.FiveTNormalizeRoute(spans.eq(0).text());
} catch(Exception e) {
//Log.e("Suggestions", "Empty busStopID");
stopID = "";
}
// busStopName
try {
stopName = spans.eq(1).text();
} catch(Exception e) {
//Log.e("Suggestions", "Empty busStopName");
stopName = "";
}
// busStopLocation
try {
stopLocation = (spans.eq(2).text());
} catch(Exception e) {
//Log.e("Suggestions", "Empty busStopLocation");
stopLocation = null;
}
busStops.add(new Stop(stopName, stopID, stopLocation, null));
}
if(busStops.size() == 0) {
res.set(result.EMPTY_RESULT_SET);
} else {
res.set(result.OK);
}
+ Collections.sort(busStops);
+
return busStops;
}
}
diff --git a/src/it/reyboz/bustorino/backend/GTTStopsFetcher.java b/src/it/reyboz/bustorino/backend/GTTStopsFetcher.java
index 497a88c..594082f 100644
--- a/src/it/reyboz/bustorino/backend/GTTStopsFetcher.java
+++ b/src/it/reyboz/bustorino/backend/GTTStopsFetcher.java
@@ -1,124 +1,184 @@
/*
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 org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.net.URL;
import java.net.URLEncoder;
-import java.util.LinkedList;
+import java.util.ArrayList;
+import java.util.Collections;
import java.util.List;
import java.util.concurrent.atomic.AtomicReference;
public class GTTStopsFetcher implements StopsFinderByName {
@Override @NonNull
public List FindByName(String name, AtomicReference res) {
URL url;
- List s = new LinkedList<>();
+ // sorting an ArrayList should be faster than a LinkedList and the API is limited to 15 results
+ List s = new ArrayList<>(15);
+ List s2 = new ArrayList<>(15);
String fullname;
String content;
String bacino;
String localita;
Route.Type type;
JSONArray json;
int howManyStops, i;
JSONObject thisstop;
if(name.length() < 3) {
res.set(result.QUERY_TOO_SHORT);
return s;
}
try {
url = new URL("http://www.gtt.to.it/cms/components/com_gtt/views/palinejson/view.html.php?term=" + URLEncoder.encode(name, "utf-8"));
} catch (Exception e) {
res.set(result.PARSER_ERROR);
return s;
}
content = networkTools.queryURL(url, res);
if(content == null) {
return s;
}
try {
json = new JSONArray(content);
} catch(JSONException e) {
if(content.contains("[]")) {
// when no results are found, server returns a PHP Warning and an empty array. In case they fix the warning, we're looking for the array.
res.set(result.EMPTY_RESULT_SET);
} else {
res.set(result.PARSER_ERROR);
}
return s;
}
howManyStops = json.length();
if(howManyStops == 0) {
res.set(result.EMPTY_RESULT_SET);
return s;
}
try {
for(i = 0; i < howManyStops; i++) {
thisstop = json.getJSONObject(i);
fullname = thisstop.getString("data");
try {
localita = thisstop.getString("localita");
if(localita.equals("[MISSING]")) {
localita = null;
}
} catch(JSONException e) {
localita = null;
}
try {
bacino = thisstop.getString("bacino");
} catch (JSONException ignored) {
bacino = "U";
}
if(fullname.startsWith("Metro ")) {
type = Route.Type.METRO;
} else if(fullname.length() >= 6 && fullname.startsWith("S00")) {
type = Route.Type.RAILWAY;
} else if(fullname.startsWith("ST")) {
type = Route.Type.RAILWAY;
} else {
type = FiveTNormalizer.decodeType("", bacino);
}
s.add(new Stop(fullname, thisstop.getString("value"), localita, type));
}
} catch (JSONException e) {
res.set(result.PARSER_ERROR);
return s;
}
+ if(s.size() < 1) {
+ // shouldn't happen but prevents the next part from catching fire
+ res.set(result.EMPTY_RESULT_SET);
+ return s;
+ }
+
+ Collections.sort(s);
+
+ // the next loop won't work with less than 2 items
+ if(s.size() < 2) {
+ res.set(result.OK);
+ return s;
+ }
+
+ /* There are some duplicate stops returned by this API.
+ * Long distance buses have stop IDs with 5 digits. Always. They are zero-padded if there
+ * aren't enough. E.g. stop 631 becomes 00631.
+ *
+ * Unfortunately you can't use padded stops to query any API.
+ * Fortunately, unpadded stops return both normal and long distance bus timetables.
+ * FiveTNormalizer is already removing padding (there may be some padded stops for which the
+ * API doesn't return an unpadded equivalent), here we'll remove duplicates by skipping
+ * padded stops, which also never have a location.
+ *
+ * I had to draw a finite state machine on a piece of paper to understand how to implement
+ * this loop.
+ */
+ for(i = 1; i < howManyStops; ) {
+ Stop current = s.get(i);
+ Stop previous = s.get(i-1);
+
+ // same stop: let's see which one to keep...
+ if(current.ID.equals(previous.ID)) {
+ if(previous.location == null) {
+ // previous one is useless: discard it, increment
+ i++;
+ } else if(current.location == null) {
+ // this one is useless: add previous and skip one
+ s2.add(previous);
+ i += 2;
+ } else {
+ // they aren't really identical: to err on the side of caution, keep them both.
+ s2.add(previous);
+ i++;
+ }
+ } else {
+ // different: add previous, increment
+ s2.add(previous);
+ i++;
+ }
+ }
+
+ // unless the last one was garbage (i would be howManyStops+1 in that case), add it
+ if(i == howManyStops) {
+ s2.add(s.get(i-1));
+ }
+
res.set(result.OK);
- return s;
+ return s2;
}
}
diff --git a/src/it/reyboz/bustorino/backend/Palina.java b/src/it/reyboz/bustorino/backend/Palina.java
index f28124b..a60b606 100644
--- a/src/it/reyboz/bustorino/backend/Palina.java
+++ b/src/it/reyboz/bustorino/backend/Palina.java
@@ -1,226 +1,226 @@
/*
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.ArrayList;
import java.util.Collections;
import java.util.List;
-import java.util.ArrayList;
/**
* 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 {
//private final String stopID;
private String stopName = "";
private ArrayList routes = new ArrayList<>();
// public Palina(String stopID) {
// this.stopID = stopID;
// }
public final void setStopName(String name) {
this.stopName = name;
}
public final String getStopName() {
return stopName;
}
/**
* 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
}
/**
* 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);
}
// /**
// * 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 4a95844..fe4eefd 100644
--- a/src/it/reyboz/bustorino/backend/Route.java
+++ b/src/it/reyboz/bustorino/backend/Route.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;
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;
- @Override
- public int compareTo(@NonNull Route other) {
- int res;
-
- res = this.name.compareTo(other.name);
- if(res != 0) {
- return res;
- }
-
- res = this.destinazione.compareTo(other.destinazione);
- if(res != 0) {
- return res;
- }
-
- if(this.type != other.type) {
- // ordinal() is evil or whatever, who cares.
- return this.type.ordinal() - other.type.ordinal();
- }
-
- return 0;
- }
-
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;
}
/**
* 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));
}
+
+ @Override
+ public int compareTo(@NonNull Route other) {
+ int res;
+
+ res = this.name.compareTo(other.name);
+ if(res != 0) {
+ return res;
+ }
+
+ res = this.destinazione.compareTo(other.destinazione);
+ if(res != 0) {
+ return res;
+ }
+
+ 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/Stop.java b/src/it/reyboz/bustorino/backend/Stop.java
index db2edca..e365117 100644
--- a/src/it/reyboz/bustorino/backend/Stop.java
+++ b/src/it/reyboz/bustorino/backend/Stop.java
@@ -1,37 +1,63 @@
/*
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 android.support.annotation.Nullable;
-public class Stop {
+public class Stop implements Comparable {
public final @NonNull String ID;
public final @NonNull String name;
public final @Nullable String location;
public final @Nullable Route.Type type;
public Stop(final @NonNull String name, final @NonNull String ID, @Nullable final String location, @Nullable final Route.Type type) {
this.ID = ID;
this.name = name;
this.location = (location != null && location.length() == 0) ? null : location;
this.type = type;
}
+
+ @Override
+ public int compareTo(@NonNull Stop other) {
+ int res;
+ int thisAsInt = networkTools.failsafeParseInt(this.ID);
+ int otherAsInt = networkTools.failsafeParseInt(other.ID);
+
+ // numeric stop IDs
+ if(thisAsInt != 0 && otherAsInt != 0) {
+ return thisAsInt - otherAsInt;
+ } else {
+ // non-numeric
+ res = this.ID.compareTo(other.ID);
+ if (res != 0) {
+ return res;
+ }
+ }
+
+ // try with name, then
+
+ res = this.name.compareTo(other.name);
+
+ // and give up
+
+ return res;
+ }
}
diff --git a/src/it/reyboz/bustorino/backend/networkTools.java b/src/it/reyboz/bustorino/backend/networkTools.java
index 5f4e0a7..9600460 100644
--- a/src/it/reyboz/bustorino/backend/networkTools.java
+++ b/src/it/reyboz/bustorino/backend/networkTools.java
@@ -1,115 +1,123 @@
/*
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.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.CLIENT_OFFLINE);
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.PARSER_ERROR);
return null;
}
res.set(Fetcher.result.SERVER_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) {
HttpURLConnection urlConnection;
InputStream in = null;
String s;
try {
urlConnection = (HttpURLConnection) url.openConnection();
} catch(IOException e) {
res.set(Fetcher.result.SERVER_ERROR); // TODO: can we assume this is CLIENT_OFFLINE?
return null;
}
res.set(Fetcher.result.PARSER_ERROR); // will be set to OK later
try {
in = urlConnection.getInputStream();
} catch (Exception e) {
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() : "";
}
+
+ static int failsafeParseInt(String str) {
+ try {
+ return Integer.parseInt(str);
+ } catch(NumberFormatException e) {
+ return 0;
+ }
+ }
}