diff --git a/src/it/reyboz/bustorino/backend/FiveTNormalizer.java b/src/it/reyboz/bustorino/backend/FiveTNormalizer.java index f3c68b0..104390f 100644 --- a/src/it/reyboz/bustorino/backend/FiveTNormalizer.java +++ b/src/it/reyboz/bustorino/backend/FiveTNormalizer.java @@ -1,252 +1,236 @@ /* 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; /** * Converts some weird stop IDs found on the 5T website to the form used everywhere else (including GTT website). *

* A stop ID in normalized form is:
* - a string containing a number without leading zeros
* - a string beginning with "ST" and then a number
* - whatever the GTT website uses.
*

* A bus route ID in normalized form is:
* - a string containing a number and optionally: "B", "CS", "CD", "N", "S", "C" at the end
* - the string "METRO"
* - "ST1" or "ST2" (Star 1 and Star 2)
* - a string beginning with E, N, S or W, followed by two digits (with a leading zero)
* - "RV2", "OB1"
* - "CAN" or "FTC" (railway lines)
* - ...screw it, let's just hope all the websites and APIs return something sane as route IDs.
*

* This class exists because Java doesn't support traits.
*
* Note: this class also just became useless, as 5T now uses the same format as GTT website. */ public abstract class FiveTNormalizer { public static String FiveTNormalizeRoute(String RouteID) { while (RouteID.startsWith("0")) { RouteID = RouteID.substring(1); } return RouteID; } public static String FiveTNormalizeStop(String StopID) { StopID = FiveTNormalizeRoute(StopID); // is this faster than a regex? if (StopID.length() == 5 && StopID.startsWith("ST") && Character.isLetter(StopID.charAt(2)) && Character.isLetter(StopID.charAt(3)) && Character.isLetter(StopID.charAt(4))) { switch (StopID) { case "STFER": return "8210"; case "STPAR": return "8211"; case "STMAR": return "8212"; case "STMAS": return "8213"; case "STPOS": return "8214"; case "STMGR": return "8215"; case "STRIV": return "8216"; case "STRAC": return "8217"; case "STBER": return "8218"; case "STPDA": return "8219"; case "STDOD": return "8220"; case "STPSU": return "8221"; case "STVIN": return "8222"; case "STREU": return "8223"; case "STPNU": return "8224"; case "STMCI": return "8225"; case "STNIZ": return "8226"; case "STDAN": return "8227"; case "STCAR": return "8228"; case "STSPE": return "8229"; case "STLGO": return "8230"; } } return StopID; } public static String NormalizedToFiveT(final String StopID) { if(StopID.startsWith("82") && StopID.length() == 4) { switch (StopID) { case "8230": return "STLGO"; case "8229": return "STSPE"; case "8228": return "STCAR"; case "8227": return "STDAN"; case "8226": return "STNIZ"; case "8225": return "STMCI"; case "8224": return "STPNU"; case "8223": return "STREU"; case "8222": return "STVIN"; case "8221": return "STPSU"; case "8220": return "STDOD"; case "8219": return "STPDA"; case "8218": return "STBER"; case "8217": return "STRAC"; case "8216": return "STRIV"; case "8215": return "STMGR"; case "8214": return "STPOS"; case "8213": return "STMAS"; case "8212": return "STMAR"; case "8211": return "STPAR"; case "8210": return "STFER"; } } return StopID; } public static Route.Type decodeType(final String routename, final String bacino) { if(routename.equals("METRO")) { return Route.Type.METRO; + } else if(routename.equals("79")) { + return Route.Type.RAILWAY; } switch (bacino) { case "U": return Route.Type.BUS; case "F": return Route.Type.RAILWAY; case "E": return Route.Type.LONG_DISTANCE_BUS; default: return Route.Type.BUS; } } /** * Converts a route ID from internal format to display format, returns null if it has the same name. * * @param routeID ID in "internal" and normalized format * @return string with display name, null if unchanged */ - public static String routeInternalToDisplay(String routeID) { + public static String routeInternalToDisplay(final String routeID) { + if(routeID.length() == 3 && routeID.charAt(2) == 'B') { + return routeID.substring(0,2).concat("/"); + } + switch(routeID) { case "1C": return "1 Chieri"; case "1N": return "1 Nichelino"; case "OB1": return "1 Orbassano"; case "2C": return "2 Chieri"; case "RV2": return "2 Rivalta"; - case "5B": - return "5 /"; case "CO1": return "Circolare Collegno"; case "79": return "Cremagliera Sassi-Superga"; case "W01": return "Night Buster 1 arancio"; case "N10": return "Night Buster 10 gialla"; case "W15": return "Night Buster 15 rosa"; case "S18": return "Night Buster 18 blu"; case "S04": return "Night Buster 4 azzurra"; case "N4": return "Night Buster 4 rossa"; case "N57": return "Night Buster 57 oro"; case "W60": return "Night Buster 60 argento"; case "E68": return "Night Buster verde 68"; case "S05": return "Night Buster viola 5"; case "ST1": return "Star 1"; case "ST2": return "Star 2"; case "10N": return "10 navetta"; - case "17B": - return "17 /"; case "35N": return "35 navetta"; case "36N": return "36 navetta"; - case "45B": - return "45 /"; case "46N": return "46 navetta"; - case "58B": - return "58 /"; - case "59B": - return "59 /"; - case "63B": - return "63 /"; - case "72B": - return "72 /"; - case "79B": - return "79 /"; - case "93B": - return "93 /"; - case "101": - return "101 Metrobus"; - case "95B": - return "95 /"; default: return null; } } } diff --git a/src/it/reyboz/bustorino/backend/FiveTScraperFetcher.java b/src/it/reyboz/bustorino/backend/FiveTScraperFetcher.java index d130b00..94e0071 100644 --- a/src/it/reyboz/bustorino/backend/FiveTScraperFetcher.java +++ b/src/it/reyboz/bustorino/backend/FiveTScraperFetcher.java @@ -1,199 +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 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/GTTJSONFetcher.java b/src/it/reyboz/bustorino/backend/GTTJSONFetcher.java index 4f5cf45..1d0fde8 100644 --- a/src/it/reyboz/bustorino/backend/GTTJSONFetcher.java +++ b/src/it/reyboz/bustorino/backend/GTTJSONFetcher.java @@ -1,122 +1,123 @@ /* 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.concurrent.atomic.AtomicReference; public class GTTJSONFetcher implements ArrivalsFetcher { @Override @NonNull public Palina ReadArrivalTimesAll(String routeID, AtomicReference res) { URL url; Palina p = new Palina(); String routename; String bacino; String content; JSONArray json; int howManyRoutes, howManyPassaggi, i, j, pos; // il misto inglese-italiano è un po' ridicolo ma tanto vale... JSONObject thisroute; JSONArray passaggi; try { url = new URL("http://www.gtt.to.it/cms/index.php?option=com_gtt&task=palina.getTransiti&palina=" + URLEncoder.encode(routeID, "utf-8") + "&realtime=true"); } catch (Exception e) { res.set(result.PARSER_ERROR); return p; } content = networkTools.queryURL(url, res); if(content == null) { return p; } try { json = new JSONArray(content); } catch(JSONException e) { res.set(result.PARSER_ERROR); return p; } try { // returns [{"PassaggiRT":[],"Passaggi":[]}] for non existing stops! json.getJSONObject(0).getString("Linea"); // if we can get this, then there's something useful in the array. } catch(JSONException e) { res.set(result.EMPTY_RESULT_SET); return p; } howManyRoutes = json.length(); if(howManyRoutes == 0) { res.set(result.EMPTY_RESULT_SET); return p; } try { for(i = 0; i < howManyRoutes; i++) { thisroute = json.getJSONObject(i); routename = thisroute.getString("Linea"); try { bacino = thisroute.getString("Bacino"); } catch (JSONException ignored) { // if "Bacino" gets removed... bacino = "U"; } pos = p.addRoute(routename, thisroute.getString("Direzione"), FiveTNormalizer.decodeType(routename, bacino)); /* * Okay, this is just absurd. * The underground always has 4 non-real-time timetable entries; however, the first * two are old\stale\bogus, as they're in the past. The other two are exactly the * same ones that appear on the screens in the stations. */ if(routename.equals("METRO")) { j = 2; } else { j = 0; } passaggi = thisroute.getJSONArray("PassaggiRT"); howManyPassaggi = passaggi.length(); for(; j < howManyPassaggi; j++) { p.addPassaggio(passaggi.getString(j).concat("*"), pos); } passaggi = thisroute.getJSONArray("Passaggi"); // now the non-real-time ones howManyPassaggi = passaggi.length(); for(; j < howManyPassaggi; j++) { p.addPassaggio(passaggi.getString(j), pos); } } } catch (JSONException e) { res.set(result.PARSER_ERROR); return p; } + p.sortRoutes(); res.set(result.OK); return p; } } diff --git a/src/it/reyboz/bustorino/backend/Palina.java b/src/it/reyboz/bustorino/backend/Palina.java index 324d1ab..f28124b 100644 --- a/src/it/reyboz/bustorino/backend/Palina.java +++ b/src/it/reyboz/bustorino/backend/Palina.java @@ -1,221 +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.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/Passaggio.java b/src/it/reyboz/bustorino/backend/Passaggio.java index 79b256f..90f3518 100644 --- a/src/it/reyboz/bustorino/backend/Passaggio.java +++ b/src/it/reyboz/bustorino/backend/Passaggio.java @@ -1,103 +1,103 @@ /* BusTO (backend components) Copyright (C) 2016 Ludovico Pavesi This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see . */ package it.reyboz.bustorino.backend; import android.support.annotation.NonNull; public final class Passaggio implements Comparable { public final String hh; public final String mm; public final boolean isInRealTime; /** * Constructs a time (passaggio) for the timetable. * * @param TimeGTT time in GTT format (e.g. "11:22*"), already trimmed from whitespace. * @throws IllegalArgumentException if nothing reasonable can be extracted from the string */ public Passaggio(@NonNull String TimeGTT) { String[] parts = TimeGTT.split(":"); if(parts.length != 2) { //throw new IllegalArgumentException("The string " + TimeGTT + " doesn't follow the sacred format of time according to GTT!"); this.hh = "??"; this.mm = "??"; this.isInRealTime = false; return; } this.hh = parts[0]; if(parts[1].endsWith("*")) { this.mm = parts[1].substring(0, parts[1].length() - 1); this.isInRealTime = true; } else { this.mm = parts[1]; this.isInRealTime = false; } } @Override public int compareTo(@NonNull Passaggio altro) { int diff; diff = failsafeParseInt(altro.hh) - failsafeParseInt(this.hh); - // an attempt to correctly sort times around midnight (e.g. 23.59 should come before 00.01) + // an attempt to correctly sortRoutes times around midnight (e.g. 23.59 should come before 00.01) if(diff > 12) { // TODO: see if this works in practice diff = -(24 - diff); } else if(diff < -12) { diff = -(diff + 24); } diff *= 60; diff += failsafeParseInt(altro.mm) - failsafeParseInt(this.mm); // we should take into account if one is in real time and the other isn't, shouldn't we? if(altro.isInRealTime) { ++diff; } if(this.isInRealTime) { --diff; } return diff; } @Override public String toString() { String resultString = (this.hh).concat(":").concat(this.mm); if(this.isInRealTime) { return resultString.concat("*"); } else { return resultString; } } /** * Parses without blowing up. * * @param str the number as a string * @return the number as an integer */ private static int failsafeParseInt(String str) { try { return Integer.parseInt(str); } catch(NumberFormatException e) { return 0; } } } \ No newline at end of file diff --git a/src/it/reyboz/bustorino/backend/Route.java b/src/it/reyboz/bustorino/backend/Route.java index bc56a03..4a95844 100644 --- a/src/it/reyboz/bustorino/backend/Route.java +++ b/src/it/reyboz/bustorino/backend/Route.java @@ -1,65 +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 { +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)); } }