From a507a41fbf468d115d1878986c6b791aabd34360 Mon Sep 17 00:00:00 2001 From: Michael Angelo Reyes Date: Wed, 6 Nov 2024 00:42:03 +0800 Subject: [PATCH 01/25] Rename .java to .kt --- .../com/skedgo/geocoding/{GCBoundingBox.java => GCBoundingBox.kt} | 0 .../main/java/com/skedgo/geocoding/{GCResult.java => GCResult.kt} | 0 .../geocoding/{GeocodeUtilities.java => GeocodeUtilities.kt} | 0 .../geocoding/{GroupScoringResult.java => GroupScoringResult.kt} | 0 .../com/skedgo/geocoding/{ScoringResult.java => ScoringResult.kt} | 0 .../{GCAppResultInterface.java => GCAppResultInterface.kt} | 0 .../{GCBoundingBoxInterface.java => GCBoundingBoxInterface.kt} | 0 ...rsquareResultInterface.java => GCFoursquareResultInterface.kt} | 0 .../{GCGoogleResultInterface.java => GCGoogleResultInterface.kt} | 0 .../agregator/{GCQueryInterface.java => GCQueryInterface.kt} | 0 .../agregator/{GCResultInterface.java => GCResultInterface.kt} | 0 .../{GCSkedGoResultInterface.java => GCSkedGoResultInterface.kt} | 0 .../agregator/{MGAResultInterface.java => MGAResultInterface.kt} | 0 ...GeocodingAggregator.java => MultiSourceGeocodingAggregator.kt} | 0 14 files changed, 0 insertions(+), 0 deletions(-) rename TripKitAndroid/src/main/java/com/skedgo/geocoding/{GCBoundingBox.java => GCBoundingBox.kt} (100%) rename TripKitAndroid/src/main/java/com/skedgo/geocoding/{GCResult.java => GCResult.kt} (100%) rename TripKitAndroid/src/main/java/com/skedgo/geocoding/{GeocodeUtilities.java => GeocodeUtilities.kt} (100%) rename TripKitAndroid/src/main/java/com/skedgo/geocoding/{GroupScoringResult.java => GroupScoringResult.kt} (100%) rename TripKitAndroid/src/main/java/com/skedgo/geocoding/{ScoringResult.java => ScoringResult.kt} (100%) rename TripKitAndroid/src/main/java/com/skedgo/geocoding/agregator/{GCAppResultInterface.java => GCAppResultInterface.kt} (100%) rename TripKitAndroid/src/main/java/com/skedgo/geocoding/agregator/{GCBoundingBoxInterface.java => GCBoundingBoxInterface.kt} (100%) rename TripKitAndroid/src/main/java/com/skedgo/geocoding/agregator/{GCFoursquareResultInterface.java => GCFoursquareResultInterface.kt} (100%) rename TripKitAndroid/src/main/java/com/skedgo/geocoding/agregator/{GCGoogleResultInterface.java => GCGoogleResultInterface.kt} (100%) rename TripKitAndroid/src/main/java/com/skedgo/geocoding/agregator/{GCQueryInterface.java => GCQueryInterface.kt} (100%) rename TripKitAndroid/src/main/java/com/skedgo/geocoding/agregator/{GCResultInterface.java => GCResultInterface.kt} (100%) rename TripKitAndroid/src/main/java/com/skedgo/geocoding/agregator/{GCSkedGoResultInterface.java => GCSkedGoResultInterface.kt} (100%) rename TripKitAndroid/src/main/java/com/skedgo/geocoding/agregator/{MGAResultInterface.java => MGAResultInterface.kt} (100%) rename TripKitAndroid/src/main/java/com/skedgo/geocoding/agregator/{MultiSourceGeocodingAggregator.java => MultiSourceGeocodingAggregator.kt} (100%) diff --git a/TripKitAndroid/src/main/java/com/skedgo/geocoding/GCBoundingBox.java b/TripKitAndroid/src/main/java/com/skedgo/geocoding/GCBoundingBox.kt similarity index 100% rename from TripKitAndroid/src/main/java/com/skedgo/geocoding/GCBoundingBox.java rename to TripKitAndroid/src/main/java/com/skedgo/geocoding/GCBoundingBox.kt diff --git a/TripKitAndroid/src/main/java/com/skedgo/geocoding/GCResult.java b/TripKitAndroid/src/main/java/com/skedgo/geocoding/GCResult.kt similarity index 100% rename from TripKitAndroid/src/main/java/com/skedgo/geocoding/GCResult.java rename to TripKitAndroid/src/main/java/com/skedgo/geocoding/GCResult.kt diff --git a/TripKitAndroid/src/main/java/com/skedgo/geocoding/GeocodeUtilities.java b/TripKitAndroid/src/main/java/com/skedgo/geocoding/GeocodeUtilities.kt similarity index 100% rename from TripKitAndroid/src/main/java/com/skedgo/geocoding/GeocodeUtilities.java rename to TripKitAndroid/src/main/java/com/skedgo/geocoding/GeocodeUtilities.kt diff --git a/TripKitAndroid/src/main/java/com/skedgo/geocoding/GroupScoringResult.java b/TripKitAndroid/src/main/java/com/skedgo/geocoding/GroupScoringResult.kt similarity index 100% rename from TripKitAndroid/src/main/java/com/skedgo/geocoding/GroupScoringResult.java rename to TripKitAndroid/src/main/java/com/skedgo/geocoding/GroupScoringResult.kt diff --git a/TripKitAndroid/src/main/java/com/skedgo/geocoding/ScoringResult.java b/TripKitAndroid/src/main/java/com/skedgo/geocoding/ScoringResult.kt similarity index 100% rename from TripKitAndroid/src/main/java/com/skedgo/geocoding/ScoringResult.java rename to TripKitAndroid/src/main/java/com/skedgo/geocoding/ScoringResult.kt diff --git a/TripKitAndroid/src/main/java/com/skedgo/geocoding/agregator/GCAppResultInterface.java b/TripKitAndroid/src/main/java/com/skedgo/geocoding/agregator/GCAppResultInterface.kt similarity index 100% rename from TripKitAndroid/src/main/java/com/skedgo/geocoding/agregator/GCAppResultInterface.java rename to TripKitAndroid/src/main/java/com/skedgo/geocoding/agregator/GCAppResultInterface.kt diff --git a/TripKitAndroid/src/main/java/com/skedgo/geocoding/agregator/GCBoundingBoxInterface.java b/TripKitAndroid/src/main/java/com/skedgo/geocoding/agregator/GCBoundingBoxInterface.kt similarity index 100% rename from TripKitAndroid/src/main/java/com/skedgo/geocoding/agregator/GCBoundingBoxInterface.java rename to TripKitAndroid/src/main/java/com/skedgo/geocoding/agregator/GCBoundingBoxInterface.kt diff --git a/TripKitAndroid/src/main/java/com/skedgo/geocoding/agregator/GCFoursquareResultInterface.java b/TripKitAndroid/src/main/java/com/skedgo/geocoding/agregator/GCFoursquareResultInterface.kt similarity index 100% rename from TripKitAndroid/src/main/java/com/skedgo/geocoding/agregator/GCFoursquareResultInterface.java rename to TripKitAndroid/src/main/java/com/skedgo/geocoding/agregator/GCFoursquareResultInterface.kt diff --git a/TripKitAndroid/src/main/java/com/skedgo/geocoding/agregator/GCGoogleResultInterface.java b/TripKitAndroid/src/main/java/com/skedgo/geocoding/agregator/GCGoogleResultInterface.kt similarity index 100% rename from TripKitAndroid/src/main/java/com/skedgo/geocoding/agregator/GCGoogleResultInterface.java rename to TripKitAndroid/src/main/java/com/skedgo/geocoding/agregator/GCGoogleResultInterface.kt diff --git a/TripKitAndroid/src/main/java/com/skedgo/geocoding/agregator/GCQueryInterface.java b/TripKitAndroid/src/main/java/com/skedgo/geocoding/agregator/GCQueryInterface.kt similarity index 100% rename from TripKitAndroid/src/main/java/com/skedgo/geocoding/agregator/GCQueryInterface.java rename to TripKitAndroid/src/main/java/com/skedgo/geocoding/agregator/GCQueryInterface.kt diff --git a/TripKitAndroid/src/main/java/com/skedgo/geocoding/agregator/GCResultInterface.java b/TripKitAndroid/src/main/java/com/skedgo/geocoding/agregator/GCResultInterface.kt similarity index 100% rename from TripKitAndroid/src/main/java/com/skedgo/geocoding/agregator/GCResultInterface.java rename to TripKitAndroid/src/main/java/com/skedgo/geocoding/agregator/GCResultInterface.kt diff --git a/TripKitAndroid/src/main/java/com/skedgo/geocoding/agregator/GCSkedGoResultInterface.java b/TripKitAndroid/src/main/java/com/skedgo/geocoding/agregator/GCSkedGoResultInterface.kt similarity index 100% rename from TripKitAndroid/src/main/java/com/skedgo/geocoding/agregator/GCSkedGoResultInterface.java rename to TripKitAndroid/src/main/java/com/skedgo/geocoding/agregator/GCSkedGoResultInterface.kt diff --git a/TripKitAndroid/src/main/java/com/skedgo/geocoding/agregator/MGAResultInterface.java b/TripKitAndroid/src/main/java/com/skedgo/geocoding/agregator/MGAResultInterface.kt similarity index 100% rename from TripKitAndroid/src/main/java/com/skedgo/geocoding/agregator/MGAResultInterface.java rename to TripKitAndroid/src/main/java/com/skedgo/geocoding/agregator/MGAResultInterface.kt diff --git a/TripKitAndroid/src/main/java/com/skedgo/geocoding/agregator/MultiSourceGeocodingAggregator.java b/TripKitAndroid/src/main/java/com/skedgo/geocoding/agregator/MultiSourceGeocodingAggregator.kt similarity index 100% rename from TripKitAndroid/src/main/java/com/skedgo/geocoding/agregator/MultiSourceGeocodingAggregator.java rename to TripKitAndroid/src/main/java/com/skedgo/geocoding/agregator/MultiSourceGeocodingAggregator.kt From f2997ff3b6d268e1f0f0bbf33b284cfb04ee3f4b Mon Sep 17 00:00:00 2001 From: Michael Angelo Reyes Date: Wed, 6 Nov 2024 00:42:03 +0800 Subject: [PATCH 02/25] [22682] - [TripKit] convert GCAppResultInterface.java to kotlin - [TripKit] convert GCBoundingBox.java to kotlin - [TripKit] convert GCBoundingBoxInterface.java to kotlin - [TripKit] convert GCFoursquareResultInterface.java to kotlin - [TripKit] convert GCGoogleResultInterface.java to kotlin - [TripKit] convert GCQueryInterface.java to kotlin - [TripKit] convert GCResult.java to kotlin - [TripKit] convert GCResultInterface.java to kotlin - [TripKit] convert GCSkedGoResultInterface.java to kotlin - [TripKit] convert GeocodeUtilities.java to kotlin - [TripKit] convert GroupScoringResult.java to kotlin - [TripKit] convert MGAResultInterface.java to kotlin - [TripKit] convert MultiSourceGeocodingAggregator.java to kotlin - [TripKit] convert ScoringResult.java to kotlin - [TripKitUI] convert AppResultLocationAdapter.java to kotlin - [TripKitUI] convert FoursquareResultLocationAdapter.java to kotlin - [TripKitUI] convert GoogleResultLocationAdapter.java to kotlin - [TripKitUI] convert SkedgoResultLocationAdapter.java to kotlin --- .../com/skedgo/geocoding/GCBoundingBox.kt | 160 ++++---- .../java/com/skedgo/geocoding/GCResult.kt | 53 +-- .../com/skedgo/geocoding/GeocodeUtilities.kt | 290 +++++++------- .../skedgo/geocoding/GroupScoringResult.kt | 89 ++--- .../com/skedgo/geocoding/ScoringResult.kt | 158 ++------ .../agregator/GCAppResultInterface.kt | 21 +- .../agregator/GCBoundingBoxInterface.kt | 23 +- .../agregator/GCFoursquareResultInterface.kt | 17 +- .../agregator/GCGoogleResultInterface.kt | 9 +- .../geocoding/agregator/GCQueryInterface.kt | 19 +- .../geocoding/agregator/GCResultInterface.kt | 23 +- .../agregator/GCSkedGoResultInterface.kt | 22 +- .../geocoding/agregator/MGAResultInterface.kt | 40 +- .../MultiSourceGeocodingAggregator.kt | 371 +++++++----------- 14 files changed, 516 insertions(+), 779 deletions(-) diff --git a/TripKitAndroid/src/main/java/com/skedgo/geocoding/GCBoundingBox.kt b/TripKitAndroid/src/main/java/com/skedgo/geocoding/GCBoundingBox.kt index 8c9d4734..54f5b5fa 100644 --- a/TripKitAndroid/src/main/java/com/skedgo/geocoding/GCBoundingBox.kt +++ b/TripKitAndroid/src/main/java/com/skedgo/geocoding/GCBoundingBox.kt @@ -1,115 +1,99 @@ -package com.skedgo.geocoding; - - -import com.skedgo.geocoding.agregator.GCBoundingBoxInterface; - -import java.util.ArrayList; -import java.util.List; - -public class GCBoundingBox implements GCBoundingBoxInterface { - - public static final GCBoundingBox World = new GCBoundingBox(85, -85, -180, 180); - public double lat1, lat2, lng1, lng2; - private double latitudeDelta = -1; - private double longitudeDelta = -1; +package com.skedgo.geocoding + +import com.skedgo.geocoding.agregator.GCBoundingBoxInterface +import kotlin.math.cos + + +class GCBoundingBox : GCBoundingBoxInterface { + override var latN: Double = 0.0 + override var latS: Double = 0.0 + override var lngW: Double = 0.0 + override var lngE: Double = 0.0 + var latitudeDelta: Double = -1.0 + get() { + if (field == -1.0) { + val latitudeSpan = latS - latN + field = latitudeSpan * Math.PI / 180 + } + return field + } + private set + var longitudeDelta: Double = -1.0 + get() { + if (field == -1.0) { + field = cos(latitudeDelta) * Math.PI / 180 + } + return field + } + private set - public GCBoundingBox(double lat1, double lat2, double lng1, double lng2) { + constructor(lat1: Double, lat2: Double, lng1: Double, lng2: Double) { if (lat1 < lat2) { - this.lat1 = lat1; - this.lat2 = lat2; + this.latN = lat1 + this.latS = lat2 } else { - this.lat1 = lat2; - this.lat2 = lat1; + this.latN = lat2 + this.latS = lat1 } if (lng1 < lng2) { - this.lng1 = lng1; - this.lng2 = lng2; + this.lngW = lng1 + this.lngE = lng2 } else { - this.lng1 = lng2; - this.lng2 = lng1; + this.lngW = lng2 + this.lngE = lng1 } } - public GCBoundingBox(GCBoundingBoxInterface bb) { - if (bb.getLatN() < bb.getLatS()) { - this.lat1 = bb.getLatN(); - this.lat2 = bb.getLatS(); + constructor(bb: GCBoundingBoxInterface) { + if (bb.latN < bb.latS) { + this.latN = bb.latN + this.latS = bb.latS } else { - this.lat1 = bb.getLatS(); - this.lat2 = bb.getLatN(); + this.latN = bb.latS + this.latS = bb.latN } - if (bb.getLngW() < bb.getLngE()) { - this.lng1 = bb.getLngW(); - this.lng2 = bb.getLngE(); + if (bb.lngW < bb.lngE) { + this.lngW = bb.lngW + this.lngE = bb.lngE } else { - this.lng1 = bb.getLngE(); - this.lng2 = bb.getLngW(); + this.lngW = bb.lngE + this.lngE = bb.lngW } } - public GCBoundingBox(//@NotNull - GCBoundingBox other) { - lat1 = other.lat1; - lat2 = other.lat2; - lng1 = other.lng1; - lng2 = other.lng2; + constructor( //@NotNull + other: GCBoundingBox + ) { + latN = other.latN + latS = other.latS + lngW = other.lngW + lngE = other.lngE } - public int height() { + fun height(): Int { // This constant is valid for all locations on Earth, since lines of latitude are equally spaced. - return (int) ((lat2 - lat1) * 110852); - } - - public LatLng center() { - return new LatLng(((lat2 - lat1) / 2) + lat1, ((lng2 - lng1) / 2) + lng1); - } - - public GCBoundingBox getBoundingBox() { - return this; + return ((latS - latN) * 110852).toInt() } - public List getLatLngs() { - List result = new ArrayList<>(); - result.add(new LatLng(lat1, lng1)); - result.add(new LatLng(lat1, lng2)); - result.add(new LatLng(lat2, lng2)); - result.add(new LatLng(lat2, lng1)); - return result; + fun center(): LatLng { + return LatLng(((latS - latN) / 2) + this.latN, ((lngE - lngW) / 2) + this.lngW) } - public double getLatitudeDelta() { - if (latitudeDelta == -1) { - double latitudeSpan = lat2 - lat1; - latitudeDelta = latitudeSpan * Math.PI / 180; + val boundingBox: GCBoundingBox + get() = this + + val latLngs: List + get() { + val result: MutableList = ArrayList() + result.add(LatLng(latN, lngW)) + result.add(LatLng(latN, lngE)) + result.add(LatLng(latS, lngE)) + result.add(LatLng(latS, lngW)) + return result } - return latitudeDelta; - } - - public double getLongitudeDelta() { - if (longitudeDelta == -1) { - longitudeDelta = Math.cos(getLatitudeDelta()) * Math.PI / 180; - } - return longitudeDelta; - } - - @Override - public double getLatN() { - return lat1; - } - - @Override - public double getLatS() { - return lat2; - } - - @Override - public double getLngW() { - return lng1; - } - @Override - public double getLngE() { - return lng2; + companion object { + val World: GCBoundingBox = GCBoundingBox(85.0, -85.0, -180.0, 180.0) } } diff --git a/TripKitAndroid/src/main/java/com/skedgo/geocoding/GCResult.kt b/TripKitAndroid/src/main/java/com/skedgo/geocoding/GCResult.kt index 09bbc782..a0a65fad 100644 --- a/TripKitAndroid/src/main/java/com/skedgo/geocoding/GCResult.kt +++ b/TripKitAndroid/src/main/java/com/skedgo/geocoding/GCResult.kt @@ -1,49 +1,10 @@ -package com.skedgo.geocoding; +package com.skedgo.geocoding +import com.skedgo.geocoding.agregator.GCResultInterface -import com.skedgo.geocoding.agregator.GCResultInterface; -import org.jetbrains.annotations.NotNull; - -public class GCResult implements GCResultInterface { - - @NotNull - private String name; - private Double lat; - private Double lng; - - public GCResult(@NotNull String name, Double lat, Double lng) { - this.name = name; - this.lat = lat; - this.lng = lng; - } - - public GCResult() { - - } - - @NotNull - public String getName() { - return name; - } - - public void setName(@NotNull String name) { - this.name = name; - } - - public Double getLat() { - return lat; - } - - public void setLat(Double lat) { - this.lat = lat; - } - - public Double getLng() { - return lng; - } - - public void setLng(Double lng) { - this.lng = lng; - } -} +open class GCResult( + override var name: String = "", + override var lat: Double? = null, + override var lng: Double? = null +) : GCResultInterface diff --git a/TripKitAndroid/src/main/java/com/skedgo/geocoding/GeocodeUtilities.kt b/TripKitAndroid/src/main/java/com/skedgo/geocoding/GeocodeUtilities.kt index 339d46fc..5f4d0a40 100644 --- a/TripKitAndroid/src/main/java/com/skedgo/geocoding/GeocodeUtilities.kt +++ b/TripKitAndroid/src/main/java/com/skedgo/geocoding/GeocodeUtilities.kt @@ -1,234 +1,224 @@ -package com.skedgo.geocoding; - -import com.skedgo.geocoding.agregator.GCAppResultInterface; -import com.skedgo.geocoding.agregator.GCFoursquareResultInterface; -import com.skedgo.geocoding.agregator.GCResultInterface; -import com.skedgo.geocoding.agregator.GCSkedGoResultInterface; -import com.skedgo.geocoding.agregator.MGAResultInterface; - -import java.util.Collections; -import java.util.Comparator; -import java.util.List; - - -public class GeocodeUtilities { - - public static int scoreBasedOnNameMatchBetweenSearchTerm(String searchTerm, String candidate) { - searchTerm = stringForScoringOfString(searchTerm); - candidate = stringForScoringOfString(candidate); - - return scoreBetweenSearchTerm(searchTerm, candidate); +package com.skedgo.geocoding + +import com.skedgo.geocoding.agregator.GCAppResultInterface +import com.skedgo.geocoding.agregator.GCFoursquareResultInterface +import com.skedgo.geocoding.agregator.GCResultInterface +import com.skedgo.geocoding.agregator.GCSkedGoResultInterface +import com.skedgo.geocoding.agregator.MGAResultInterface +import java.util.Collections +import java.util.Locale +import kotlin.math.abs +import kotlin.math.ceil +import kotlin.math.sqrt + +object GeocodeUtilities { + fun scoreBasedOnNameMatchBetweenSearchTerm(searchTerm: String, candidate: String): Int { + var searchTerm = searchTerm + var candidate = candidate + searchTerm = stringForScoringOfString(searchTerm) + candidate = stringForScoringOfString(candidate) + + return scoreBetweenSearchTerm(searchTerm, candidate) } - public static String stringForScoringOfString(String term) { - String updatedTerm = ""; - if (term != null) - updatedTerm = term.trim(); + fun stringForScoringOfString(term: String?): String { + var updatedTerm = "" + if (term != null) updatedTerm = term.trim { it <= ' ' } - updatedTerm = updatedTerm.replaceAll("\\s+", " "); - String result = ""; - for (Character character : updatedTerm.toCharArray()) { - if (isAlphanumeric(character)) - result += character.toString().toLowerCase(); + updatedTerm = updatedTerm.replace("\\s+".toRegex(), " ") + var result = "" + for (character in updatedTerm.toCharArray()) { + if (isAlphanumeric(character)) result += character.toString() + .lowercase(Locale.getDefault()) } - return result; + return result } - public static int scoreBetweenSearchTerm(String target, String candidate) { + fun scoreBetweenSearchTerm(target: String, candidate: String): Int { + if (target.isEmpty()) return if (candidate.isEmpty()) 100 else 0 - if (target.length() == 0) - return candidate.length() == 0 ? 100 : 0; + if (candidate.isEmpty()) return 100 // having typed yet means a perfect match of everything you've typed so far - if (candidate.length() == 0) - return 100; // having typed yet means a perfect match of everything you've typed so far - if (target.equalsIgnoreCase(candidate)) { - return 100; + if (target.equals(candidate, ignoreCase = true)) { + return 100 } - if (isAbbreviationFor(target, candidate)) - return 95; + if (isAbbreviationFor(target, candidate)) return 95 if (isAbbreviationFor(candidate, target)) { - return 90; + return 90 } - int excess = candidate.length() - target.length(); - int fullMatchRangeLocation = candidate.indexOf(target); + val excess = candidate.length - target.length + val fullMatchRangeLocation = candidate.indexOf(target) if (fullMatchRangeLocation == 0) { // matches right at start - return calculateScoring(100, excess, 75); + return calculateScoring(100, excess, 75) } else if (fullMatchRangeLocation != -1) { - String before = candidate.substring(fullMatchRangeLocation - 1, fullMatchRangeLocation); - if (before.matches("\\S")) { + val before = candidate.substring(fullMatchRangeLocation - 1, fullMatchRangeLocation) + return if (before.matches("\\S".toRegex())) { // matches beginning of word - return calculateScoring(75, fullMatchRangeLocation * 2 + excess, 33); + calculateScoring(75, fullMatchRangeLocation * 2 + excess, 33) } else { // in-word match - return calculateScoring(40, excess, 15); + calculateScoring(40, excess, 15) } } -// non-substring matches - String[] targetWords = target.split(" "); - int lastIndex = 0; - for (String targetWord : targetWords) { - int location = candidate.indexOf(targetWord); + // non-substring matches + val targetWords = target.split(" ".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray() + var lastIndex = 0 + for (targetWord in targetWords) { + val location = candidate.indexOf(targetWord) if (location == -1) { - return 0; // missing a word! + return 0 // missing a word! } else if (location >= lastIndex) { // still in order, keep going - lastIndex = location; + lastIndex = location } else { // wrong order, abort with penalty - return calculateScoring(10, excess, 0); + return calculateScoring(10, excess, 0) } } // contains all target words in order // do we have all the finished words - for (int i = 0; i < targetWords.length - 1; i++) { - String targetWord = targetWords[i]; - int after = candidate.indexOf(targetWord) + targetWord.length() + 1; - if (String.valueOf(candidate.charAt(after)).matches("\\S")) { + for (i in 0 until targetWords.size - 1) { + val targetWord = targetWords[i] + val after = candidate.indexOf(targetWord) + targetWord.length + 1 + if (candidate[after].toString().matches("\\S".toRegex())) { // full word match, continue with next } else { // candidate doesn't have a completed word - return calculateScoring(33, excess, 10); + return calculateScoring(33, excess, 10) } } - return calculateScoring(66, excess, 40); + return calculateScoring(66, excess, 40) } // It resolves abbreviations such as ("MOMA", "museum of modern art") - public static boolean isAbbreviationFor(String abbreviation, String text) { - - abbreviation = abbreviation.toLowerCase(); - text = text.toLowerCase(); - if (abbreviation.length() <= 2) { - return false; + fun isAbbreviationFor(abbreviation: String, text: String): Boolean { + var abbreviation = abbreviation + var text = text + abbreviation = abbreviation.lowercase(Locale.getDefault()) + text = text.lowercase(Locale.getDefault()) + if (abbreviation.length <= 2) { + return false } - String letter = abbreviation.substring(0, 1); - if (!text.startsWith(letter)) - return false; + var letter = abbreviation.substring(0, 1) + if (!text.startsWith(letter)) return false - String[] parts = text.split(" "); - if (parts.length != abbreviation.length()) - return false; + val parts = text.split(" ".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray() + if (parts.size != abbreviation.length) return false - for (int i = 1; i < abbreviation.length(); i++) { - letter = abbreviation.substring(i, i + 1); - String word = parts[i]; - if (!word.startsWith(letter)) - return false; + for (i in 1 until abbreviation.length) { + letter = abbreviation.substring(i, i + 1) + val word = parts[i] + if (!word.startsWith(letter)) return false } - return true; + return true } - private static int calculateScoring(int maximum, int penalty, int minimum) { - if (penalty > maximum - minimum) { - return minimum; + private fun calculateScoring(maximum: Int, penalty: Int, minimum: Int): Int { + return if (penalty > maximum - minimum) { + minimum } else { - return maximum - penalty; + maximum - penalty } } - public static int rangedScoreForScore(int score, int minimum, int maximum) { - if (score > 100) - score = 100; - int range = maximum - minimum; - float percentage = score / 100.f; - return (int) Math.ceil(percentage * range) + minimum; + fun rangedScoreForScore(score: Int, minimum: Int, maximum: Int): Int { + var score = score + if (score > 100) score = 100 + val range = maximum - minimum + val percentage = score / 100f + return ceil((percentage * range).toDouble()).toInt() + minimum } - public static int scoreBasedOnDistanceFromCoordinate(LatLng coordinate, GCBoundingBox region, LatLng regionCenter, boolean longDistance) { - -// That's covering the special case of passing in the whole world. In that case everything scores 100%. - GCBoundingBox worldRegion = GCBoundingBox.World; - if (region != null && (Math.abs(worldRegion.getLatitudeDelta() - region.getLatitudeDelta()) < 1 && - Math.abs(worldRegion.getLongitudeDelta() - region.getLongitudeDelta()) < 1)) - return 100; - - double meters = coordinate.distanceInMetres(regionCenter); - double zeroScoreDistance = longDistance ? 20000000 : 25000; + fun scoreBasedOnDistanceFromCoordinate( + coordinate: LatLng, + region: GCBoundingBox?, + regionCenter: LatLng, + longDistance: Boolean + ): Int { + // That's covering the special case of passing in the whole world. In that case everything scores 100%. + + val worldRegion = GCBoundingBox.World + if (region != null && (abs(worldRegion.latitudeDelta - region.latitudeDelta) < 1 && + abs(worldRegion.longitudeDelta - region.longitudeDelta) < 1) + ) return 100 + + val meters = coordinate.distanceInMetres(regionCenter) + val zeroScoreDistance = (if (longDistance) 20000000 else 25000).toDouble() if (meters >= zeroScoreDistance) { - return 0; + return 0 } - double match = longDistance ? Math.sqrt(meters) / Math.sqrt(zeroScoreDistance) : meters / zeroScoreDistance; - double proportion = 1.0 - match; - int max = 100; - int score = (int) (proportion * max); - return score; + val match = + if (longDistance) sqrt(meters) / sqrt(zeroScoreDistance) else meters / zeroScoreDistance + val proportion = 1.0 - match + val max = 100 + val score = (proportion * max).toInt() + return score } - private static boolean isAlphanumeric(char character) { - return (Character.isLetter(character) || Character.isDigit(character) || String.valueOf(character).matches("\\S")); + private fun isAlphanumeric(character: Char): Boolean { + return (Character.isLetter(character) || Character.isDigit(character) || character.toString() + .matches("\\S".toRegex())) } - public static boolean isSuburb(GCFoursquareResultInterface foursquareResult) { - boolean isSuburb = false; + fun isSuburb(foursquareResult: GCFoursquareResultInterface): Boolean { + var isSuburb = false - for (String categoryName : foursquareResult.getCategories()) { - if (categoryName.equalsIgnoreCase("States & Municipalities")) { - isSuburb = true; - break; + for (categoryName in foursquareResult.categories) { + if (categoryName.equals("States & Municipalities", ignoreCase = true)) { + isSuburb = true + break } } - return isSuburb; + return isSuburb } - public static List> sortByImportance(List> scoreResults) { - Collections.sort(scoreResults, new Comparator() { - @Override - public int compare(MGAResultInterface o1, MGAResultInterface o2) { - return compareInt(getRanking2Group(o2), getRanking2Group(o1)); - } - }); + fun sortByImportance(scoreResults: List>): List> { + Collections.sort(scoreResults) { o1, o2 -> + compareInt( + getRanking2Group(o2), + getRanking2Group(o1) + ) + } - return scoreResults; + return scoreResults } - public static List> sortByScore(List> scoreResults) { - Collections.sort(scoreResults, new Comparator() { - @Override - public int compare(MGAResultInterface o1, MGAResultInterface o2) { - return compareInt(o2.getScore(), o1.getScore()); - } - }); - return scoreResults; + fun sortByScore(scoreResults: List>): List> { + Collections.sort(scoreResults) { o1, o2 -> compareInt(o2.score, o1.score) } + return scoreResults } - public static int compareInt(int x, int y) { - return (x < y) ? -1 : ((x == y) ? 0 : 1); + fun compareInt(x: Int, y: Int): Int { + return if ((x < y)) -1 else (if ((x == y)) 0 else 1) } - private static int getRanking2Group(MGAResultInterface element) { - if (element.getResult() instanceof GCSkedGoResultInterface) - return 10; + private fun getRanking2Group(element: MGAResultInterface<*>): Int { + if (element.result is GCSkedGoResultInterface) return 10 - if (element.getResult() instanceof GCAppResultInterface) { - GCAppResultInterface appResult = (GCAppResultInterface) element.getResult(); - if (appResult.isFavourite()) - return 11; - else - return 9; + if (element.result is GCAppResultInterface) { + val appResult = element.result as GCAppResultInterface + return if (appResult.isFavourite) 11 + else 9 } - if (element.getResult() instanceof GCFoursquareResultInterface) { - GCFoursquareResultInterface foursquareResult = (GCFoursquareResultInterface) element.getResult(); - if (foursquareResult.isVerified()) - return 8; - else - return 6; + if (element.result is GCFoursquareResultInterface) { + val foursquareResult = element.result as GCFoursquareResultInterface + return if (foursquareResult.isVerified) 8 + else 6 } - return 7; + return 7 } - - } diff --git a/TripKitAndroid/src/main/java/com/skedgo/geocoding/GroupScoringResult.kt b/TripKitAndroid/src/main/java/com/skedgo/geocoding/GroupScoringResult.kt index 6350e292..e91899f8 100644 --- a/TripKitAndroid/src/main/java/com/skedgo/geocoding/GroupScoringResult.kt +++ b/TripKitAndroid/src/main/java/com/skedgo/geocoding/GroupScoringResult.kt @@ -1,77 +1,50 @@ -package com.skedgo.geocoding; +package com.skedgo.geocoding -import com.skedgo.geocoding.agregator.GCResultInterface; -import com.skedgo.geocoding.agregator.MGAResultInterface; - -import java.util.ArrayList; -import java.util.List; +import com.skedgo.geocoding.GeocodeUtilities.sortByImportance +import com.skedgo.geocoding.agregator.GCResultInterface +import com.skedgo.geocoding.agregator.MGAResultInterface /** * scored result with duplicates */ -public class GroupScoringResult implements MGAResultInterface { - - private List> duplicates = null; - - public GroupScoringResult() { - } +class GroupScoringResult : MGAResultInterface { + override var duplicates: MutableList>? = null + private set - @Override - public T getResult() { - return duplicates.get(0).getResult(); - } - - @Override - public int getScore() { - return duplicates.get(0).getScore(); - } + override val result: T + get() = duplicates!![0].result - @Override - public List> getDuplicates() { - return duplicates; - } + override val score: Int + get() = duplicates!![0].score - @Override - public MGAResultInterface getClassRepresentative() { - return duplicates.get(0); - } + override val classRepresentative: MGAResultInterface + get() = duplicates!![0] - @Override - public int getNameScore() { - return duplicates.get(0).getNameScore(); - } + override val nameScore: Int + get() = duplicates!![0].nameScore - @Override - public int getAddressScore() { - return duplicates.get(0).getAddressScore(); - } + override val addressScore: Int + get() = duplicates!![0].addressScore - @Override - public int getDistanceScore() { - return duplicates.get(0).getDistanceScore(); - } + override val distanceScore: Int + get() = duplicates!![0].distanceScore - @Override - public int getPopularityScore() { - return duplicates.get(0).getPopularityScore(); - } + override val popularityScore: Int + get() = duplicates!![0].popularityScore - public void addDuplicate(ScoringResult scoringResult) { - if (duplicates == null) - duplicates = new ArrayList<>(); - duplicates.add(scoringResult); - duplicates = GeocodeUtilities.sortByImportance(duplicates); + fun addDuplicate(scoringResult: ScoringResult) { + if (duplicates == null) duplicates = mutableListOf() + duplicates?.add(scoringResult) + duplicates = sortByImportance(duplicates!!).toMutableList() } - public void addDuplicates(List> scoringResults) { - if (duplicates == null) - duplicates = new ArrayList<>(); - duplicates.addAll(scoringResults); - duplicates = GeocodeUtilities.sortByImportance(duplicates); + fun addDuplicates(scoringResults: List>) { + if (duplicates == null) duplicates = mutableListOf() + duplicates?.addAll(scoringResults) + duplicates = sortByImportance(duplicates!!).toMutableList() } - public ScoringResult getScoringResult() { - return (ScoringResult) duplicates.get(0); - } + val scoringResult: ScoringResult + get() = duplicates!![0] as ScoringResult } diff --git a/TripKitAndroid/src/main/java/com/skedgo/geocoding/ScoringResult.kt b/TripKitAndroid/src/main/java/com/skedgo/geocoding/ScoringResult.kt index d8bf89fa..c2ebdde3 100644 --- a/TripKitAndroid/src/main/java/com/skedgo/geocoding/ScoringResult.kt +++ b/TripKitAndroid/src/main/java/com/skedgo/geocoding/ScoringResult.kt @@ -1,138 +1,62 @@ -package com.skedgo.geocoding; +package com.skedgo.geocoding +import com.skedgo.geocoding.agregator.GCAppResultInterface +import com.skedgo.geocoding.agregator.GCAppResultInterface.Source.Regions +import com.skedgo.geocoding.agregator.GCFoursquareResultInterface +import com.skedgo.geocoding.agregator.GCGoogleResultInterface +import com.skedgo.geocoding.agregator.GCResultInterface +import com.skedgo.geocoding.agregator.GCSkedGoResultInterface +import com.skedgo.geocoding.agregator.MGAResultInterface -import com.skedgo.geocoding.agregator.GCAppResultInterface; -import com.skedgo.geocoding.agregator.GCFoursquareResultInterface; -import com.skedgo.geocoding.agregator.GCGoogleResultInterface; -import com.skedgo.geocoding.agregator.GCResultInterface; -import com.skedgo.geocoding.agregator.GCSkedGoResultInterface; -import com.skedgo.geocoding.agregator.MGAResultInterface; - -import org.jetbrains.annotations.NotNull; - -import java.util.List; /** * scored single result - without duplicates */ -public class ScoringResult implements MGAResultInterface { - - private T providerResult; - private int score; +class ScoringResult( + private val providerResult: T +) : MGAResultInterface { - //-1 if the source not calculate the score - private int distanceScore = -1; - private int nameScore = -1; - private int addressScore = -1; - private int popularityScore = -1; + override var score: Int = 0 + override var distanceScore: Int = -1 + override var nameScore: Int = -1 + override var addressScore: Int = -1 + override var popularityScore: Int = -1 + override var duplicates: List>? = null + override var classRepresentative: MGAResultInterface?= null + override val result: T + get() = providerResult - public ScoringResult(T providerResult) { - this.providerResult = providerResult; + fun equals(element: MGAResultInterface): Boolean { + return isDuplicate(this, element) } - @NotNull - @Override - public T getResult() { - return providerResult; - } + private fun isDuplicate(mgaResult: MGAResultInterface, mgaResult1: MGAResultInterface): Boolean { + val result = mgaResult.result + val result1 = mgaResult1.result - @Override - public int getScore() { - return score; - } + if (isRegion(result) || isRegion(result1)) return false - public void setScore(int score) { - this.score = score; - } - - @Override - public List> getDuplicates() { - return null; - } + val mgaResultName = mgaResult.result.name + val mgaResult1Name = mgaResult1.result.name + val mgaResultLL = LatLng(mgaResult.result.lat ?: 0.0, mgaResult.result.lng ?: 0.0) + val mgaResult1LL = LatLng(mgaResult1.result.lat ?: 0.0, mgaResult.result.lng ?: 0.0) - @Override - public MGAResultInterface getClassRepresentative() { - return null; + return (mgaResultName.contains(mgaResult1Name) || mgaResult1Name.contains(mgaResultName)) && + (mgaResultLL.distanceInMetres(mgaResult1LL) < 10) } - @Override - public int getNameScore() { - return nameScore; + private fun isRegion(result: T): Boolean { + return result is GCAppResultInterface && result.appResultSource == GCAppResultInterface.Source.Regions } - public void setNameScore(int nameScore) { - this.nameScore = nameScore; + private fun isBHresult(result: T): Boolean { + return result is GCAppResultInterface || result is GCSkedGoResultInterface } - @Override - public int getAddressScore() { - return addressScore; + private fun isFromDifferentSource(result1: T, result2: T): Boolean { + return !((result1 is GCAppResultInterface && result2 is GCAppResultInterface) || + (result1 is GCSkedGoResultInterface && result2 is GCSkedGoResultInterface) || + (result1 is GCGoogleResultInterface && result2 is GCGoogleResultInterface) || + (result1 is GCFoursquareResultInterface && result2 is GCFoursquareResultInterface)) } - - public void setAddressScore(int addressScore) { - this.addressScore = addressScore; - } - - @Override - public int getDistanceScore() { - return distanceScore; - } - - public void setDistanceScore(int distanceScore) { - this.distanceScore = distanceScore; - } - - @Override - public int getPopularityScore() { - return popularityScore; - } - - public void setPopularityScore(int popularityScore) { - this.popularityScore = popularityScore; - } - - public boolean equals(MGAResultInterface element) { - return isDuplicate(this, element); - } - - private boolean isDuplicate(MGAResultInterface mgaResult, MGAResultInterface mgaResult1) { - T result = mgaResult.getResult(); - T result1 = mgaResult1.getResult(); - - if (isRegion(result) || isRegion(result1)) - return false; - else { - String mgaResultName = mgaResult.getResult().getName(); - String mgaResult1Name = mgaResult1.getResult().getName(); - LatLng mgaResultLL = new LatLng(mgaResult.getResult().getLat(), mgaResult.getResult().getLng()); - LatLng mgaResult1LL = new LatLng(mgaResult1.getResult().getLat(), mgaResult.getResult().getLng()); - - return (mgaResultName.contains(mgaResult1Name) || mgaResult1Name.contains(mgaResultName)) && (mgaResultLL.distanceInMetres(mgaResult1LL) < 10); - } - } - - - private boolean isRegion(T result) { - if (result instanceof GCAppResultInterface) { - GCAppResultInterface apiResultCandidate = (GCAppResultInterface) result; - return apiResultCandidate.getAppResultSource().equals(GCAppResultInterface.Source.Regions); - } else - return false; - } - - private boolean isBHresult(T result) { - return (result instanceof GCAppResultInterface || result instanceof GCSkedGoResultInterface); - } - - private boolean isFromDifferentSource(T result1, T result2) { - if ((result1 instanceof GCAppResultInterface && result2 instanceof GCAppResultInterface) || - (result1 instanceof GCSkedGoResultInterface && result2 instanceof GCSkedGoResultInterface) || - (result1 instanceof GCGoogleResultInterface && result2 instanceof GCGoogleResultInterface) || - (result1 instanceof GCFoursquareResultInterface && result2 instanceof GCFoursquareResultInterface)) - return false; - else - return true; - } - - } diff --git a/TripKitAndroid/src/main/java/com/skedgo/geocoding/agregator/GCAppResultInterface.kt b/TripKitAndroid/src/main/java/com/skedgo/geocoding/agregator/GCAppResultInterface.kt index 6c2238c3..37ab6c3a 100644 --- a/TripKitAndroid/src/main/java/com/skedgo/geocoding/agregator/GCAppResultInterface.kt +++ b/TripKitAndroid/src/main/java/com/skedgo/geocoding/agregator/GCAppResultInterface.kt @@ -1,25 +1,24 @@ -package com.skedgo.geocoding.agregator; +package com.skedgo.geocoding.agregator /** * Information that the user saves in the app */ -public interface GCAppResultInterface extends GCResultInterface { +interface GCAppResultInterface : GCResultInterface { - // address value - String getSubtitle(); + // Address value + val subtitle: String - // source that provides the result - Source getAppResultSource(); + // Source that provides the result + val appResultSource: Source - // is true if the result was set as favourite by the user false otherwise. - boolean isFavourite(); + // True if the result was set as favorite by the user, false otherwise + val isFavourite: Boolean - // source that provides the result - enum Source { + // Source that provides the result + enum class Source { AddressBook, Regions, Calendar, History } - } diff --git a/TripKitAndroid/src/main/java/com/skedgo/geocoding/agregator/GCBoundingBoxInterface.kt b/TripKitAndroid/src/main/java/com/skedgo/geocoding/agregator/GCBoundingBoxInterface.kt index ccab25d7..5ff58079 100644 --- a/TripKitAndroid/src/main/java/com/skedgo/geocoding/agregator/GCBoundingBoxInterface.kt +++ b/TripKitAndroid/src/main/java/com/skedgo/geocoding/agregator/GCBoundingBoxInterface.kt @@ -1,20 +1,19 @@ -package com.skedgo.geocoding.agregator; +package com.skedgo.geocoding.agregator /** * */ -public interface GCBoundingBoxInterface { +interface GCBoundingBoxInterface { - // north Latitude - double getLatN(); + // North Latitude + val latN: Double - // south Latitude - double getLatS(); + // South Latitude + val latS: Double - // west Longitude - double getLngW(); + // West Longitude + val lngW: Double - // east Longitude - double getLngE(); - -} + // East Longitude + val lngE: Double +} \ No newline at end of file diff --git a/TripKitAndroid/src/main/java/com/skedgo/geocoding/agregator/GCFoursquareResultInterface.kt b/TripKitAndroid/src/main/java/com/skedgo/geocoding/agregator/GCFoursquareResultInterface.kt index 83c13b01..62be2d5a 100644 --- a/TripKitAndroid/src/main/java/com/skedgo/geocoding/agregator/GCFoursquareResultInterface.kt +++ b/TripKitAndroid/src/main/java/com/skedgo/geocoding/agregator/GCFoursquareResultInterface.kt @@ -1,13 +1,10 @@ -package com.skedgo.geocoding.agregator; +package com.skedgo.geocoding.agregator -import java.util.List; +interface GCFoursquareResultInterface : GCResultInterface { -public interface GCFoursquareResultInterface extends GCResultInterface { + // Foursquare JSON verified field + val isVerified: Boolean - // foursquare json verified field - boolean isVerified(); - - // foursquare json categories names - List getCategories(); - -} + // Foursquare JSON categories names + val categories: List +} \ No newline at end of file diff --git a/TripKitAndroid/src/main/java/com/skedgo/geocoding/agregator/GCGoogleResultInterface.kt b/TripKitAndroid/src/main/java/com/skedgo/geocoding/agregator/GCGoogleResultInterface.kt index 945fdade..9c5414eb 100644 --- a/TripKitAndroid/src/main/java/com/skedgo/geocoding/agregator/GCGoogleResultInterface.kt +++ b/TripKitAndroid/src/main/java/com/skedgo/geocoding/agregator/GCGoogleResultInterface.kt @@ -1,8 +1,7 @@ -package com.skedgo.geocoding.agregator; +package com.skedgo.geocoding.agregator -public interface GCGoogleResultInterface extends GCResultInterface { - - // result address - String getAddress(); +interface GCGoogleResultInterface : GCResultInterface { + // Result address + val address: String } diff --git a/TripKitAndroid/src/main/java/com/skedgo/geocoding/agregator/GCQueryInterface.kt b/TripKitAndroid/src/main/java/com/skedgo/geocoding/agregator/GCQueryInterface.kt index 3cb9ddfa..ff4f4bb2 100644 --- a/TripKitAndroid/src/main/java/com/skedgo/geocoding/agregator/GCQueryInterface.kt +++ b/TripKitAndroid/src/main/java/com/skedgo/geocoding/agregator/GCQueryInterface.kt @@ -1,15 +1,10 @@ -package com.skedgo.geocoding.agregator; +package com.skedgo.geocoding.agregator -import org.jetbrains.annotations.NotNull; +interface GCQueryInterface { -public interface GCQueryInterface { + // User query + val queryText: String - // user query - @NotNull - String getQueryText(); - - // user bounding box - @NotNull - GCBoundingBoxInterface getBounds(); - -} + // User bounding box + val bounds: GCBoundingBoxInterface +} \ No newline at end of file diff --git a/TripKitAndroid/src/main/java/com/skedgo/geocoding/agregator/GCResultInterface.kt b/TripKitAndroid/src/main/java/com/skedgo/geocoding/agregator/GCResultInterface.kt index f6de5392..d59d747b 100644 --- a/TripKitAndroid/src/main/java/com/skedgo/geocoding/agregator/GCResultInterface.kt +++ b/TripKitAndroid/src/main/java/com/skedgo/geocoding/agregator/GCResultInterface.kt @@ -1,18 +1,13 @@ -package com.skedgo.geocoding.agregator; +package com.skedgo.geocoding.agregator -import org.jetbrains.annotations.NotNull; +interface GCResultInterface { -public interface GCResultInterface { + // Result name + val name: String - // result name - @NotNull - String getName(); + // Result latitude + val lat: Double? - // result latitude - Double getLat(); - - // result longitude - Double getLng(); - - -} + // Result longitude + val lng: Double? +} \ No newline at end of file diff --git a/TripKitAndroid/src/main/java/com/skedgo/geocoding/agregator/GCSkedGoResultInterface.kt b/TripKitAndroid/src/main/java/com/skedgo/geocoding/agregator/GCSkedGoResultInterface.kt index 3d4c9875..8e2bbccd 100644 --- a/TripKitAndroid/src/main/java/com/skedgo/geocoding/agregator/GCSkedGoResultInterface.kt +++ b/TripKitAndroid/src/main/java/com/skedgo/geocoding/agregator/GCSkedGoResultInterface.kt @@ -1,17 +1,13 @@ -package com.skedgo.geocoding.agregator; +package com.skedgo.geocoding.agregator -import java.util.List; +interface GCSkedGoResultInterface : GCResultInterface { -import androidx.annotation.Nullable; + // Skedgo result class (class JSON field) + val resultClass: String -public interface GCSkedGoResultInterface extends GCResultInterface { + // Skedgo result popularity (popularity JSON field) + val popularity: Int - // skedgo result class (class json field) - String getResultClass(); - - // skedgo result popularity (popularity json field) - int getPopularity(); - - @Nullable - List getModeIdentifiers(); -} + // Nullable list of mode identifiers + val modeIdentifiers: List? +} \ No newline at end of file diff --git a/TripKitAndroid/src/main/java/com/skedgo/geocoding/agregator/MGAResultInterface.kt b/TripKitAndroid/src/main/java/com/skedgo/geocoding/agregator/MGAResultInterface.kt index 04eee7d2..5f117b95 100644 --- a/TripKitAndroid/src/main/java/com/skedgo/geocoding/agregator/MGAResultInterface.kt +++ b/TripKitAndroid/src/main/java/com/skedgo/geocoding/agregator/MGAResultInterface.kt @@ -1,35 +1,33 @@ -package com.skedgo.geocoding.agregator; +package com.skedgo.geocoding.agregator -import java.io.Serializable; -import java.util.List; +import java.io.Serializable /** * this class represents a scored result, it could be single or have duplicates */ -public interface MGAResultInterface extends Serializable { +interface MGAResultInterface : Serializable { - // returns query result - T getResult(); + // Returns query result + val result: T - // total score for the result - int getScore(); + // Total score for the result + val score: Int - // returns all duplicates for the result - List> getDuplicates(); + // Returns all duplicates for the result + val duplicates: List>? - // returns the scored result which is the class representative for the duplicate list - MGAResultInterface getClassRepresentative(); + // Returns the scored result which is the class representative for the duplicate list + val classRepresentative: MGAResultInterface? - //next was added to test -// name score value - int getNameScore(); + // Name score value + val nameScore: Int - // address score value - int getAddressScore(); + // Address score value + val addressScore: Int - // distance score value - int getDistanceScore(); + // Distance score value + val distanceScore: Int - // populariry score value - int getPopularityScore(); + // Popularity score value + val popularityScore: Int } diff --git a/TripKitAndroid/src/main/java/com/skedgo/geocoding/agregator/MultiSourceGeocodingAggregator.kt b/TripKitAndroid/src/main/java/com/skedgo/geocoding/agregator/MultiSourceGeocodingAggregator.kt index 6bae357b..b02ad575 100644 --- a/TripKitAndroid/src/main/java/com/skedgo/geocoding/agregator/MultiSourceGeocodingAggregator.kt +++ b/TripKitAndroid/src/main/java/com/skedgo/geocoding/agregator/MultiSourceGeocodingAggregator.kt @@ -1,13 +1,12 @@ -package com.skedgo.geocoding.agregator; +package com.skedgo.geocoding.agregator -import com.skedgo.geocoding.GCBoundingBox; -import com.skedgo.geocoding.GCQuery; -import com.skedgo.geocoding.GeocodeUtilities; -import com.skedgo.geocoding.LatLng; -import com.skedgo.geocoding.ScoringResult; - -import java.util.ArrayList; -import java.util.List; +import com.skedgo.geocoding.GCBoundingBox +import com.skedgo.geocoding.GCQuery +import com.skedgo.geocoding.GeocodeUtilities +import com.skedgo.geocoding.LatLng +import com.skedgo.geocoding.ScoringResult +import kotlin.math.max +import kotlin.math.min /** * Scoring formulas @@ -27,269 +26,197 @@ import java.util.List; * Suburb score: bonus score if result is a suburb * Popularity score: score based on popularity of result as determined by server */ +class MultiSourceGeocodingAggregator private constructor() { -public class MultiSourceGeocodingAggregator { - - private static MultiSourceGeocodingAggregator instance = null; + companion object { + private var instance: MultiSourceGeocodingAggregator<*>? = null - private MultiSourceGeocodingAggregator() { - } - - public static MultiSourceGeocodingAggregator getInstance() { - if (instance == null) - instance = new MultiSourceGeocodingAggregator<>(); - return instance; + @Suppress("UNCHECKED_CAST") + fun getInstance(): MultiSourceGeocodingAggregator { + if (instance == null) { + instance = MultiSourceGeocodingAggregator() + } + return instance as MultiSourceGeocodingAggregator + } } - public List> aggregate(GCQueryInterface userQuery, List> providersResults) { - GCQuery query; - List> scoredResults = new ArrayList<>(); - if (userQuery instanceof GCQuery) { - query = (GCQuery) userQuery; + fun aggregate(userQuery: GCQueryInterface, providersResults: List>): List> { + val query: GCQuery = if (userQuery is GCQuery) { + userQuery } else { - if (userQuery.getBounds() instanceof GCBoundingBox) { - query = new GCQuery(userQuery.getQueryText(), (GCBoundingBox) userQuery.getBounds()); + if (userQuery.bounds is GCBoundingBox) { + GCQuery(userQuery.queryText, userQuery.bounds as GCBoundingBox) } else { - query = new GCQuery(userQuery.getQueryText(), new GCBoundingBox(userQuery.getBounds())); + GCQuery(userQuery.queryText, GCBoundingBox(userQuery.bounds)) } } - for (List providerResults : providersResults) { - if (providerResults != null) { - for (T candidate : providerResults) { - ScoringResult scoringResult = calculateScore(query, candidate); - if (scoringResult != null && scoringResult.getScore() != 0) { - scoredResults.add(scoringResult); + val scoredResults = mutableListOf>() + providersResults.forEach { providerResults -> + providerResults.forEach { candidate -> + calculateScore(query, candidate)?.let { scoringResult -> + if (scoringResult.score != 0) { + scoredResults.add(scoringResult) } } } } - scoredResults = GeocodeUtilities.sortByScore(scoredResults); - return scoredResults; + return GeocodeUtilities.sortByScore(scoredResults) } - public List flattenAggregate(GCQueryInterface userQuery, List> providersResults) { - List> aggregates = aggregate(userQuery, providersResults); - List results = new ArrayList<>(); - for (MGAResultInterface result : aggregates) { - results.add(result.getResult()); - } - return results; + fun flattenAggregate(userQuery: GCQueryInterface, providersResults: List>): List { + val aggregates = aggregate(userQuery, providersResults) + return aggregates.map { it.result } } - - private ScoringResult calculateScore(GCQuery query, T candidate) { - - if (candidate instanceof GCGoogleResultInterface) - return selectGoogleScore(query, (GCGoogleResultInterface) candidate); - if (candidate instanceof GCFoursquareResultInterface) - return calculateFoursquareScoring(query, (GCFoursquareResultInterface) candidate); - if (candidate instanceof GCSkedGoResultInterface) - return calculateSkedGoScoring(query, (GCSkedGoResultInterface) candidate); - if (candidate instanceof GCAppResultInterface) { - GCAppResultInterface apiResultCandidate = (GCAppResultInterface) candidate; - switch (apiResultCandidate.getAppResultSource()) { - case History: - return calculateHistoryScoring(query, apiResultCandidate); - case Calendar: - return calculateCalendarScoring(query, apiResultCandidate); - case AddressBook: - return calculateAddressBookScoring(query, apiResultCandidate); - case Regions: - return calculateRegionsScoring(query, apiResultCandidate); + private fun calculateScore(query: GCQuery, candidate: T): ScoringResult? { + return when (candidate) { + is GCGoogleResultInterface -> selectGoogleScore(query, candidate) + is GCFoursquareResultInterface -> calculateFoursquareScoring(query, candidate) + is GCSkedGoResultInterface -> calculateSkedGoScoring(query, candidate) + is GCAppResultInterface -> when (candidate.appResultSource) { + GCAppResultInterface.Source.History -> calculateHistoryScoring(query, candidate) + GCAppResultInterface.Source.Calendar -> calculateCalendarScoring(query, candidate) + GCAppResultInterface.Source.AddressBook -> calculateAddressBookScoring(query, candidate) + GCAppResultInterface.Source.Regions -> calculateRegionsScoring(query, candidate) } + else -> null } - return null; } - private ScoringResult selectGoogleScore(GCQuery query, GCGoogleResultInterface candidate) { - if (candidate.getLat() != null && candidate.getLng() != null && candidate.getAddress() != null) { - return calculateGoogleScoring(query, candidate); + private fun selectGoogleScore(query: GCQuery, candidate: GCGoogleResultInterface): ScoringResult { + return if (candidate.lat != null && candidate.lng != null && candidate.address != null) { + calculateGoogleScoring(query, candidate) } else { - return calculateAutocompleteScore(query, candidate); + calculateAutocompleteScore(query, candidate) } } + @Suppress("UNCHECKED_CAST") + private fun calculateGoogleScoring(query: GCQuery, candidate: GCGoogleResultInterface): ScoringResult { + val scoringResult = ScoringResult(candidate as T) + val nameScore = GeocodeUtilities.scoreBasedOnNameMatchBetweenSearchTerm(query.queryText, candidate.name) + val addressScore = GeocodeUtilities.scoreBasedOnNameMatchBetweenSearchTerm(query.queryText, candidate.address) + val stringScore = maxOf(nameScore, addressScore) - private ScoringResult calculateGoogleScoring(GCQuery query, GCGoogleResultInterface candidate) { - ScoringResult scoringResult = new ScoringResult(candidate); - int nameScore = GeocodeUtilities.scoreBasedOnNameMatchBetweenSearchTerm(query.getQueryText(), candidate.getName()); - int addressScore = GeocodeUtilities.scoreBasedOnNameMatchBetweenSearchTerm(query.getQueryText(), candidate.getAddress()); - int stringScore = Math.max(nameScore, addressScore); - scoringResult.setNameScore(nameScore); - scoringResult.setAddressScore(addressScore); - - int distanceScore = 0; - if (candidate.getLat() != -1 && candidate.getLng() != -1) { - LatLng coordinate = new LatLng(candidate.getLat(), candidate.getLng()); - distanceScore = GeocodeUtilities.scoreBasedOnDistanceFromCoordinate(coordinate, query.getBounds(), query.getBounds().center(), false); - scoringResult.setDistanceScore(distanceScore); - } - int rawScore = (stringScore * 3 + distanceScore) / 4; - int min = 15; - int max = 75; - int totalScore = GeocodeUtilities.rangedScoreForScore(rawScore, min, max); - scoringResult.setScore(totalScore); - return scoringResult; - } + scoringResult.nameScore = nameScore + scoringResult.addressScore = addressScore + val distanceScore = if (candidate.lat != -1.0 && candidate.lng != -1.0) { + val coordinate = LatLng(candidate.lat ?: 0.0, candidate.lng ?: 0.0) + GeocodeUtilities.scoreBasedOnDistanceFromCoordinate(coordinate, query.bounds, query.bounds.center(), false).also { + scoringResult.distanceScore = it + } + } else 0 - private ScoringResult calculateAutocompleteScore(GCQuery query, GCGoogleResultInterface candidate) { - ScoringResult scoringResult = new ScoringResult(candidate); - int nameScore = GeocodeUtilities.scoreBasedOnNameMatchBetweenSearchTerm(query.getQueryText(), candidate.getName()); - int rawScore = (nameScore * 3) / 4; - int min = 15; - int max = 75; - int totalScore = GeocodeUtilities.rangedScoreForScore(rawScore, min, max); - scoringResult.setScore(totalScore); - return scoringResult; + val rawScore = (stringScore * 3 + distanceScore) / 4 + val totalScore = GeocodeUtilities.rangedScoreForScore(rawScore, 15, 75) + scoringResult.score = totalScore + return scoringResult } + @Suppress("UNCHECKED_CAST") + private fun calculateAutocompleteScore(query: GCQuery, candidate: GCGoogleResultInterface): ScoringResult { + val scoringResult = ScoringResult(candidate as T) + val nameScore = GeocodeUtilities.scoreBasedOnNameMatchBetweenSearchTerm(query.queryText, candidate.name) + val rawScore = (nameScore * 3) / 4 + val totalScore = GeocodeUtilities.rangedScoreForScore(rawScore, 15, 75) + scoringResult.score = totalScore + return scoringResult + } + @Suppress("UNCHECKED_CAST") + private fun calculateFoursquareScoring(query: GCQuery, candidate: GCFoursquareResultInterface): ScoringResult? { + if (!candidate.isVerified && (candidate.categories == null || candidate.categories.isEmpty())) return null - private ScoringResult calculateFoursquareScoring(GCQuery query, GCFoursquareResultInterface candidate) { - ScoringResult scoringResult = new ScoringResult(candidate); - - //discard uncategorized and not verified foursquare results - if (!candidate.isVerified() && (candidate.getCategories() == null || candidate.getCategories().isEmpty())) - return null; - - int titleScore = GeocodeUtilities.scoreBasedOnNameMatchBetweenSearchTerm(query.getQueryText(), candidate.getName()); - + val scoringResult = ScoringResult(candidate as T) + val titleScore = GeocodeUtilities.scoreBasedOnNameMatchBetweenSearchTerm(query.queryText, candidate.name) if (titleScore == 0) { - scoringResult.setScore(0); - scoringResult.setNameScore(0); - return scoringResult; - } - - LatLng coordinate = new LatLng(candidate.getLat(), candidate.getLng()); - int distanceScore = GeocodeUtilities.scoreBasedOnDistanceFromCoordinate(coordinate, query.getBounds(), query.getBounds().center(), false); - - int rawScore = (titleScore * 3 + distanceScore) / 4; - if (GeocodeUtilities.isSuburb(candidate)) { - rawScore *= 2; + scoringResult.score = 0 + scoringResult.nameScore = 0 + return scoringResult } - scoringResult.setNameScore(titleScore); - scoringResult.setDistanceScore(distanceScore); - // Even verified results can be not great matches, so we keep the maximum fixed, but - // raise the lower end. Overall, we want foursquare to have a lower maximum than - // Apple as Apple tends to provide better exact matches. - int minimum, maximum; - if (candidate.isVerified()) { - minimum = 33; - maximum = 66; - } else { - minimum = 15; - maximum = 66; - } + val coordinate = LatLng(candidate.lat ?: 0.0, candidate.lng ?: 0.0) + val distanceScore = GeocodeUtilities.scoreBasedOnDistanceFromCoordinate(coordinate, query.bounds, query.bounds.center(), false) + val rawScore = (titleScore * 3 + distanceScore) / 4 * if (GeocodeUtilities.isSuburb(candidate)) 2 else 1 - int totalScore = GeocodeUtilities.rangedScoreForScore(rawScore, minimum, maximum); - scoringResult.setScore(totalScore); + scoringResult.nameScore = titleScore + scoringResult.distanceScore = distanceScore - return scoringResult; + val (min, max) = if (candidate.isVerified) 33 to 66 else 15 to 66 + val totalScore = GeocodeUtilities.rangedScoreForScore(rawScore, min, max) + scoringResult.score = totalScore + return scoringResult } - private ScoringResult calculateSkedGoScoring(GCQuery query, GCSkedGoResultInterface candidate) { - ScoringResult scoringResult = new ScoringResult(candidate); - if (candidate.getResultClass().equalsIgnoreCase("StopLocation")) { - int GOOD_SCORE = 1000; - int popularity = candidate.getPopularity(); -// int popularityScore = (Math.min(popularity, GOOD_SCORE)) / (GOOD_SCORE / 100) - int popularityScore = ((Math.min(popularity, GOOD_SCORE)) / (GOOD_SCORE / 100)) * 2; - - popularityScore = (candidate.getModeIdentifiers() != null && !candidate.getModeIdentifiers().isEmpty()) ? - GeocodeUtilities.rangedScoreForScore(popularityScore, 50, 90) : - GeocodeUtilities.rangedScoreForScore(popularityScore, 30, 80); - - if (popularity > GOOD_SCORE) { - int moreThanGood = popularityScore / GOOD_SCORE; - int bonus = GeocodeUtilities.rangedScoreForScore(moreThanGood, 0, 10); - popularityScore += bonus; + @Suppress("UNCHECKED_CAST") + private fun calculateSkedGoScoring(query: GCQuery, candidate: GCSkedGoResultInterface): ScoringResult { + val scoringResult = ScoringResult(candidate as T) + val score = if (candidate.resultClass.equals("StopLocation", ignoreCase = true)) { + val GOOD_SCORE = 1000 + val popularityScore = ((minOf(candidate.popularity, GOOD_SCORE) / (GOOD_SCORE / 100)) * 2).let { + if (candidate.modeIdentifiers?.isNotEmpty() == true) + GeocodeUtilities.rangedScoreForScore(it, 50, 90) + else GeocodeUtilities.rangedScoreForScore(it, 30, 80) } - - scoringResult.setPopularityScore(candidate.getPopularity()); - scoringResult.setScore(popularityScore); - return scoringResult; + if (candidate.popularity > GOOD_SCORE) { + popularityScore + GeocodeUtilities.rangedScoreForScore(popularityScore / GOOD_SCORE, 0, 10) + } else popularityScore } else { - if (!query.getQueryText().isEmpty()) { - int nameScore = GeocodeUtilities.scoreBasedOnNameMatchBetweenSearchTerm(query.getQueryText(), candidate.getName()); - - int totalScore = (candidate.getModeIdentifiers() != null && !candidate.getModeIdentifiers().isEmpty()) ? - GeocodeUtilities.rangedScoreForScore(nameScore, 50, 90) : - GeocodeUtilities.rangedScoreForScore(nameScore, 0, 50); - scoringResult.setScore(totalScore); - scoringResult.setNameScore(nameScore); - return scoringResult; - } else { - int totalScore = GeocodeUtilities.rangedScoreForScore(candidate.getPopularity(), 0, 50); - scoringResult.setPopularityScore(candidate.getPopularity()); - scoringResult.setScore(totalScore); - return scoringResult; - } + if (query.queryText.isNotEmpty()) { + val nameScore = GeocodeUtilities.scoreBasedOnNameMatchBetweenSearchTerm(query.queryText, candidate.name) + if (candidate.modeIdentifiers?.isNotEmpty() == true) { + GeocodeUtilities.rangedScoreForScore(nameScore, 50, 90) + } else GeocodeUtilities.rangedScoreForScore(nameScore, 0, 50) + } else GeocodeUtilities.rangedScoreForScore(candidate.popularity, 0, 50) } + scoringResult.popularityScore = candidate.popularity + scoringResult.score = score + return scoringResult } - //favourites - searchHistory - private ScoringResult calculateHistoryScoring(GCQuery query, GCAppResultInterface candidate) { - ScoringResult scoringResult = new ScoringResult(candidate); - - int rawScore; - boolean matchAgainstString = query.getQueryText().length() > 0; - - if (matchAgainstString) { - int nameScore = GeocodeUtilities.scoreBasedOnNameMatchBetweenSearchTerm(query.getQueryText(), candidate.getName()); - int addressScore = GeocodeUtilities.scoreBasedOnNameMatchBetweenSearchTerm(query.getQueryText(), candidate.getSubtitle()); - scoringResult.setNameScore(nameScore); - scoringResult.setAddressScore(addressScore); - rawScore = Math.max(nameScore, addressScore); + @Suppress("UNCHECKED_CAST") + private fun calculateHistoryScoring(query: GCQuery, candidate: GCAppResultInterface): ScoringResult { + val scoringResult = ScoringResult(candidate as T) + val rawScore = if (query.queryText.isNotEmpty()) { + val nameScore = GeocodeUtilities.scoreBasedOnNameMatchBetweenSearchTerm(query.queryText, candidate.name) + val addressScore = GeocodeUtilities.scoreBasedOnNameMatchBetweenSearchTerm(query.queryText, candidate.subtitle) + scoringResult.nameScore = nameScore + scoringResult.addressScore = addressScore + maxOf(nameScore, addressScore) } else { - rawScore = 100; - scoringResult.setNameScore(rawScore); + scoringResult.nameScore = 100 + 100 } - - - int min = candidate.isFavourite() ? 90 : 50; - int max = candidate.isFavourite() ? 100 : 90; - int totalScore = GeocodeUtilities.rangedScoreForScore(rawScore, min, max); - scoringResult.setScore(totalScore); - - return scoringResult; - } - - private ScoringResult calculateCalendarScoring(GCQueryInterface query, GCAppResultInterface candidate) { - ScoringResult scoringResult = new ScoringResult(candidate); - String searchTerm = query.getQueryText(); - int nameScore = GeocodeUtilities.scoreBasedOnNameMatchBetweenSearchTerm(searchTerm, candidate.getName()); - int locationScore = GeocodeUtilities.scoreBasedOnNameMatchBetweenSearchTerm(searchTerm, candidate.getSubtitle()); - scoringResult.setNameScore(nameScore); - scoringResult.setAddressScore(locationScore); - - int rawScore = Math.min(100, (nameScore + locationScore) / 2); - - int min = 50; - int max = 90; - int totalScore = GeocodeUtilities.rangedScoreForScore(rawScore, min, max); - scoringResult.setScore(totalScore); - - return scoringResult; + val (min, max) = if (candidate.isFavourite) 90 to 100 else 50 to 90 + scoringResult.score = GeocodeUtilities.rangedScoreForScore(rawScore, min, max) + return scoringResult } - // address book & calendar use the same algorithm to calculate scoring - private ScoringResult calculateAddressBookScoring(GCQueryInterface query, GCAppResultInterface candidate) { - return calculateCalendarScoring(query, candidate); + @Suppress("UNCHECKED_CAST") + private fun calculateCalendarScoring(query: GCQueryInterface, candidate: GCAppResultInterface): ScoringResult { + val scoringResult = ScoringResult(candidate as T) + val nameScore = GeocodeUtilities.scoreBasedOnNameMatchBetweenSearchTerm(query.queryText, candidate.name) + val locationScore = GeocodeUtilities.scoreBasedOnNameMatchBetweenSearchTerm(query.queryText, candidate.subtitle) + scoringResult.nameScore = nameScore + scoringResult.addressScore = locationScore + + val rawScore = minOf(100, (nameScore + locationScore) / 2) + scoringResult.score = GeocodeUtilities.rangedScoreForScore(rawScore, 50, 90) + return scoringResult } - private ScoringResult calculateRegionsScoring(GCQuery query, GCAppResultInterface candidate) { - ScoringResult scoringResult = new ScoringResult(candidate); - LatLng coordinate = new LatLng(candidate.getLat(), candidate.getLng()); - int rawScore = GeocodeUtilities.scoreBasedOnDistanceFromCoordinate(coordinate, query.getBounds(), query.getBounds().center(), false); - scoringResult.setDistanceScore(rawScore); + private fun calculateAddressBookScoring(query: GCQueryInterface, candidate: GCAppResultInterface) = calculateCalendarScoring(query, candidate) - int min = 50; - int max = 90; - int totalScore = GeocodeUtilities.rangedScoreForScore(rawScore, min, max); - scoringResult.setScore(totalScore); + @Suppress("UNCHECKED_CAST") + private fun calculateRegionsScoring(query: GCQuery, candidate: GCAppResultInterface): ScoringResult { + val scoringResult = ScoringResult(candidate as T) + val coordinate = LatLng(candidate.lat ?: 0.0, candidate.lng ?: 0.0) + val rawScore = GeocodeUtilities.scoreBasedOnDistanceFromCoordinate(coordinate, query.bounds, query.bounds.center(), false) + scoringResult.distanceScore = rawScore - return scoringResult; + val totalScore = GeocodeUtilities.rangedScoreForScore(rawScore, 50, 90) + scoringResult.score = totalScore + return scoringResult } } From 94becb9969dffc03ef51b9dac68ba98d7c6fe4e5 Mon Sep 17 00:00:00 2001 From: Michael Angelo Reyes Date: Wed, 6 Nov 2024 02:31:35 +0800 Subject: [PATCH 03/25] Rename .java to .kt --- .../com/skedgo/geocoding/{GCAppResult.java => GCAppResult.kt} | 0 .../geocoding/{GCFoursquareResult.java => GCFoursquareResult.kt} | 0 .../skedgo/geocoding/{GCGoogleResult.java => GCGoogleResult.kt} | 0 .../main/java/com/skedgo/geocoding/{GCQuery.java => GCQuery.kt} | 0 .../skedgo/geocoding/{GCSkedgoResult.java => GCSkedgoResult.kt} | 0 .../src/main/java/com/skedgo/geocoding/{LatLng.java => LatLng.kt} | 0 .../tripkit/a2brouting/{A2bRoutingApi.java => A2bRoutingApi.kt} | 0 .../{FailoverA2bRoutingApi.java => FailoverA2bRoutingApi.kt} | 0 8 files changed, 0 insertions(+), 0 deletions(-) rename TripKitAndroid/src/main/java/com/skedgo/geocoding/{GCAppResult.java => GCAppResult.kt} (100%) rename TripKitAndroid/src/main/java/com/skedgo/geocoding/{GCFoursquareResult.java => GCFoursquareResult.kt} (100%) rename TripKitAndroid/src/main/java/com/skedgo/geocoding/{GCGoogleResult.java => GCGoogleResult.kt} (100%) rename TripKitAndroid/src/main/java/com/skedgo/geocoding/{GCQuery.java => GCQuery.kt} (100%) rename TripKitAndroid/src/main/java/com/skedgo/geocoding/{GCSkedgoResult.java => GCSkedgoResult.kt} (100%) rename TripKitAndroid/src/main/java/com/skedgo/geocoding/{LatLng.java => LatLng.kt} (100%) rename TripKitAndroid/src/main/java/com/skedgo/tripkit/a2brouting/{A2bRoutingApi.java => A2bRoutingApi.kt} (100%) rename TripKitAndroid/src/main/java/com/skedgo/tripkit/a2brouting/{FailoverA2bRoutingApi.java => FailoverA2bRoutingApi.kt} (100%) diff --git a/TripKitAndroid/src/main/java/com/skedgo/geocoding/GCAppResult.java b/TripKitAndroid/src/main/java/com/skedgo/geocoding/GCAppResult.kt similarity index 100% rename from TripKitAndroid/src/main/java/com/skedgo/geocoding/GCAppResult.java rename to TripKitAndroid/src/main/java/com/skedgo/geocoding/GCAppResult.kt diff --git a/TripKitAndroid/src/main/java/com/skedgo/geocoding/GCFoursquareResult.java b/TripKitAndroid/src/main/java/com/skedgo/geocoding/GCFoursquareResult.kt similarity index 100% rename from TripKitAndroid/src/main/java/com/skedgo/geocoding/GCFoursquareResult.java rename to TripKitAndroid/src/main/java/com/skedgo/geocoding/GCFoursquareResult.kt diff --git a/TripKitAndroid/src/main/java/com/skedgo/geocoding/GCGoogleResult.java b/TripKitAndroid/src/main/java/com/skedgo/geocoding/GCGoogleResult.kt similarity index 100% rename from TripKitAndroid/src/main/java/com/skedgo/geocoding/GCGoogleResult.java rename to TripKitAndroid/src/main/java/com/skedgo/geocoding/GCGoogleResult.kt diff --git a/TripKitAndroid/src/main/java/com/skedgo/geocoding/GCQuery.java b/TripKitAndroid/src/main/java/com/skedgo/geocoding/GCQuery.kt similarity index 100% rename from TripKitAndroid/src/main/java/com/skedgo/geocoding/GCQuery.java rename to TripKitAndroid/src/main/java/com/skedgo/geocoding/GCQuery.kt diff --git a/TripKitAndroid/src/main/java/com/skedgo/geocoding/GCSkedgoResult.java b/TripKitAndroid/src/main/java/com/skedgo/geocoding/GCSkedgoResult.kt similarity index 100% rename from TripKitAndroid/src/main/java/com/skedgo/geocoding/GCSkedgoResult.java rename to TripKitAndroid/src/main/java/com/skedgo/geocoding/GCSkedgoResult.kt diff --git a/TripKitAndroid/src/main/java/com/skedgo/geocoding/LatLng.java b/TripKitAndroid/src/main/java/com/skedgo/geocoding/LatLng.kt similarity index 100% rename from TripKitAndroid/src/main/java/com/skedgo/geocoding/LatLng.java rename to TripKitAndroid/src/main/java/com/skedgo/geocoding/LatLng.kt diff --git a/TripKitAndroid/src/main/java/com/skedgo/tripkit/a2brouting/A2bRoutingApi.java b/TripKitAndroid/src/main/java/com/skedgo/tripkit/a2brouting/A2bRoutingApi.kt similarity index 100% rename from TripKitAndroid/src/main/java/com/skedgo/tripkit/a2brouting/A2bRoutingApi.java rename to TripKitAndroid/src/main/java/com/skedgo/tripkit/a2brouting/A2bRoutingApi.kt diff --git a/TripKitAndroid/src/main/java/com/skedgo/tripkit/a2brouting/FailoverA2bRoutingApi.java b/TripKitAndroid/src/main/java/com/skedgo/tripkit/a2brouting/FailoverA2bRoutingApi.kt similarity index 100% rename from TripKitAndroid/src/main/java/com/skedgo/tripkit/a2brouting/FailoverA2bRoutingApi.java rename to TripKitAndroid/src/main/java/com/skedgo/tripkit/a2brouting/FailoverA2bRoutingApi.kt From 4c0f5b18dbcb249b8b9e3b634798ac3a97e38661 Mon Sep 17 00:00:00 2001 From: Michael Angelo Reyes Date: Wed, 6 Nov 2024 02:31:35 +0800 Subject: [PATCH 04/25] [22682] - [TripKit] convert A2bRoutingApi.java to kotlin - [TripKit] convert FailoverA2bRoutingApi.java to kotlin - [TripKit] convert GCAppResult.java to kotlin - [TripKit] convert GCFoursquareResult.java to kotlin - [TripKit] convert GCGoogleResult.java to kotlin - [TripKit] convert GCQuery.java to kotlin - [TripKit] convert GCSkedgoResult.java to kotlin - [TripKit] convert LatLng.java to kotlin - [TripGov5] ODIN specific fixes for the updated TripGoActionButtonHandler class on other WL --- .../java/com/skedgo/geocoding/GCAppResult.kt | 63 ++----- .../skedgo/geocoding/GCFoursquareResult.kt | 54 ++---- .../com/skedgo/geocoding/GCGoogleResult.kt | 34 ++-- .../main/java/com/skedgo/geocoding/GCQuery.kt | 48 +---- .../com/skedgo/geocoding/GCSkedgoResult.kt | 73 ++------ .../com/skedgo/geocoding/GeocodeUtilities.kt | 2 +- .../main/java/com/skedgo/geocoding/LatLng.kt | 55 +++--- .../agregator/GCGoogleResultInterface.kt | 2 +- .../com/skedgo/tripkit/RouteServiceImpl.kt | 12 +- .../tripkit/a2brouting/A2bRoutingApi.kt | 34 ++-- .../a2brouting/FailoverA2bRoutingApi.kt | 170 ++++++++---------- 11 files changed, 185 insertions(+), 362 deletions(-) diff --git a/TripKitAndroid/src/main/java/com/skedgo/geocoding/GCAppResult.kt b/TripKitAndroid/src/main/java/com/skedgo/geocoding/GCAppResult.kt index dd5b22e2..6614cc26 100644 --- a/TripKitAndroid/src/main/java/com/skedgo/geocoding/GCAppResult.kt +++ b/TripKitAndroid/src/main/java/com/skedgo/geocoding/GCAppResult.kt @@ -1,56 +1,19 @@ -package com.skedgo.geocoding; +package com.skedgo.geocoding -import com.skedgo.geocoding.agregator.GCAppResultInterface; - -import org.jetbrains.annotations.NotNull; +import com.skedgo.geocoding.agregator.GCAppResultInterface +import com.skedgo.geocoding.agregator.GCAppResultInterface.Source /** * Represents the the minimum information we need to calculate the score * for a result obtained from the information stored in the app by the user. */ -public class GCAppResult extends GCResult implements GCAppResultInterface { - - @NotNull -// address value - private String subtitle; - // is true if the result was set as favourite by the user false otherwise. - private boolean isFavourite; - @NotNull -// source that provides the result - private Source source; - - public GCAppResult(String name, double lat, double lng, @NotNull String address, boolean isFavourite, @NotNull Source source) { - super(name, lat, lng); - this.subtitle = address; - this.isFavourite = isFavourite; - this.source = source; - } - - @NotNull - @Override - public String getSubtitle() { - return subtitle; - } - - public void setSubtitle(@NotNull String subtitle) { - this.subtitle = subtitle; - } - - @Override - public Source getAppResultSource() { - return source; - } - - public void setAppResultSource(Source source) { - this.source = source; - } - - @Override - public boolean isFavourite() { - return isFavourite; - } - - public void setIsFavourite(boolean favourite) { - this.isFavourite = favourite; - } -} +class GCAppResult( + name: String, + lat: Double, + lng: Double, // address value + override var subtitle: String, // is true if the result was set as favourite by the user false otherwise. + override var isFavourite: Boolean, // source that provides the result + override var appResultSource: Source +) : GCResult( + name, lat, lng +), GCAppResultInterface diff --git a/TripKitAndroid/src/main/java/com/skedgo/geocoding/GCFoursquareResult.kt b/TripKitAndroid/src/main/java/com/skedgo/geocoding/GCFoursquareResult.kt index 2f1bb86b..f1801109 100644 --- a/TripKitAndroid/src/main/java/com/skedgo/geocoding/GCFoursquareResult.kt +++ b/TripKitAndroid/src/main/java/com/skedgo/geocoding/GCFoursquareResult.kt @@ -1,50 +1,16 @@ -package com.skedgo.geocoding; +package com.skedgo.geocoding -import com.skedgo.geocoding.agregator.GCFoursquareResultInterface; - -import org.jetbrains.annotations.NotNull; - -import java.util.List; +import com.skedgo.geocoding.agregator.GCFoursquareResultInterface /** * Represents the minimum information we need * to calculate the score for a foursquare result. */ -public class GCFoursquareResult extends GCResult implements GCFoursquareResultInterface { - - // value in verified field in foursquare's json - private boolean verified; - @NotNull -// each element for category is the value of each -// name field from each categories in foursquare's json - private List categories; - - // name is the value in name field in foursquare's json -// lat is the value in latitude field in on location field in foursquare's json -// lng is the value in longitude field in on location field in foursquare's json - public GCFoursquareResult(String name, double lat, double lng, boolean verified, @NotNull List categories) { - super(name, lat, lng); - this.verified = verified; - this.categories = categories; - } - - @Override - public boolean isVerified() { - return verified; - } - - @NotNull - @Override - public List getCategories() { - return categories; - } - - public void setCategories(@NotNull List categories) { - this.categories = categories; - } - - public void setIsVerified(boolean verified) { - this.verified = verified; - } - -} +class GCFoursquareResult + ( + name: String, // name is the value in name field in foursquare's json + lat: Double, // lat is the value in latitude field in on location field in foursquare's json + lng: Double, // lng is the value in longitude field in on location field in foursquare's json + override var isVerified: Boolean, // value in verified field in foursquare's json + override var categories: List // each element for category is the value of each +) : GCResult(name, lat, lng), GCFoursquareResultInterface diff --git a/TripKitAndroid/src/main/java/com/skedgo/geocoding/GCGoogleResult.kt b/TripKitAndroid/src/main/java/com/skedgo/geocoding/GCGoogleResult.kt index 255fc9d2..7a2463a9 100644 --- a/TripKitAndroid/src/main/java/com/skedgo/geocoding/GCGoogleResult.kt +++ b/TripKitAndroid/src/main/java/com/skedgo/geocoding/GCGoogleResult.kt @@ -1,32 +1,20 @@ -package com.skedgo.geocoding; +package com.skedgo.geocoding +import com.skedgo.geocoding.agregator.GCGoogleResultInterface -import com.skedgo.geocoding.agregator.GCGoogleResultInterface; - -public class GCGoogleResult extends GCResult implements GCGoogleResultInterface { +class GCGoogleResult : GCResult, GCGoogleResultInterface { // value in address field from google's json - private String address; + override var address: String? = null // name is the value in name field in google's json -// lat is the value on lat field in on location field in google's json -// lng is the value on lat field in on location field in google's json - public GCGoogleResult(String name, double lat, double lng, String address) { - super(name, lat, lng); - this.address = address; - } - - public GCGoogleResult(String name) { - super(name, null, null); - } - - @Override - public String getAddress() { - return address; - } - - public void setAddress(String address) { - this.address = address; + // lat is the value on lat field in on location field in google's json + // lng is the value on lat field in on location field in google's json + constructor(name: String?, lat: Double, lng: Double, address: String?) : super( + name!!, lat, lng + ) { + this.address = address } + constructor(name: String?) : super(name!!, null, null) } diff --git a/TripKitAndroid/src/main/java/com/skedgo/geocoding/GCQuery.kt b/TripKitAndroid/src/main/java/com/skedgo/geocoding/GCQuery.kt index 7e654a00..b86a4ac6 100644 --- a/TripKitAndroid/src/main/java/com/skedgo/geocoding/GCQuery.kt +++ b/TripKitAndroid/src/main/java/com/skedgo/geocoding/GCQuery.kt @@ -1,44 +1,8 @@ -package com.skedgo.geocoding; +package com.skedgo.geocoding -import com.skedgo.geocoding.agregator.GCQueryInterface; +import com.skedgo.geocoding.agregator.GCQueryInterface -import org.jetbrains.annotations.NotNull; - -public class GCQuery implements GCQueryInterface { - - @NotNull -// user search input - private String term; - @NotNull -// bounding box on user screen - private GCBoundingBox boundingBox; - - - public GCQuery(@NotNull String term, @NotNull GCBoundingBox boundsData) { - this.term = term; - this.boundingBox = boundsData; -// this.boundingBox = new GCBoundingBox(boundsData.getLatN(), boundsData.getLatS(), boundsData.getLngW(), boundsData.getLngE()); - } - - @NotNull - @Override - public String getQueryText() { - return term; - } - - public void setQueryText(String term) { - this.term = term; - } - - @NotNull - @Override - public GCBoundingBox getBounds() { - return boundingBox; - } - - public void setBounds(GCBoundingBox boundingBox) { - this.boundingBox = boundingBox; - } - - -} +class GCQuery( + override var queryText: String, + override var bounds: GCBoundingBox +) : GCQueryInterface diff --git a/TripKitAndroid/src/main/java/com/skedgo/geocoding/GCSkedgoResult.kt b/TripKitAndroid/src/main/java/com/skedgo/geocoding/GCSkedgoResult.kt index eecc188d..a483d645 100644 --- a/TripKitAndroid/src/main/java/com/skedgo/geocoding/GCSkedgoResult.kt +++ b/TripKitAndroid/src/main/java/com/skedgo/geocoding/GCSkedgoResult.kt @@ -1,65 +1,18 @@ -package com.skedgo.geocoding; +package com.skedgo.geocoding +import com.skedgo.geocoding.agregator.GCSkedGoResultInterface -import com.skedgo.geocoding.agregator.GCSkedGoResultInterface; -import org.jetbrains.annotations.NotNull; - -import java.util.List; - -import androidx.annotation.Nullable; - -public class GCSkedgoResult extends GCResult implements GCSkedGoResultInterface { - - @NotNull -// class json field from skedgo's json - private String resultClass; +class GCSkedgoResult( + name: String?, + lat: Double, + lng: Double, + // class json field from skedgo's json + override var resultClass: String, // popularity json field from skedgo's json - private int popularity; - - @Nullable - private List modeIdentifiers; - - public GCSkedgoResult( - String name, - double lat, - double lng, - @NotNull String resultClass, - Integer popularity, - @Nullable List modeIdentifiers - ) { - super(name, lat, lng); - this.popularity = popularity; - this.resultClass = resultClass; - this.modeIdentifiers = modeIdentifiers; - } - - @NotNull - @Override - public String getResultClass() { - return resultClass; - } - - public void setResultClass(@NotNull String resultClass) { - this.resultClass = resultClass; - } - - @Override - public int getPopularity() { - return popularity; - } - - public void setPopularity(int popularity) { - this.popularity = popularity; - } - - public boolean isStopLocation() { - return this.resultClass.equalsIgnoreCase("StopLocation"); - } - - @Nullable - @Override - public List getModeIdentifiers() { - return modeIdentifiers; - } + override var popularity: Int, + override val modeIdentifiers: List? +) : GCResult(name!!, lat, lng), GCSkedGoResultInterface { + val isStopLocation: Boolean + get() = resultClass.equals("StopLocation", ignoreCase = true) } diff --git a/TripKitAndroid/src/main/java/com/skedgo/geocoding/GeocodeUtilities.kt b/TripKitAndroid/src/main/java/com/skedgo/geocoding/GeocodeUtilities.kt index 5f4d0a40..77eaef92 100644 --- a/TripKitAndroid/src/main/java/com/skedgo/geocoding/GeocodeUtilities.kt +++ b/TripKitAndroid/src/main/java/com/skedgo/geocoding/GeocodeUtilities.kt @@ -12,7 +12,7 @@ import kotlin.math.ceil import kotlin.math.sqrt object GeocodeUtilities { - fun scoreBasedOnNameMatchBetweenSearchTerm(searchTerm: String, candidate: String): Int { + fun scoreBasedOnNameMatchBetweenSearchTerm(searchTerm: String, candidate: String?): Int { var searchTerm = searchTerm var candidate = candidate searchTerm = stringForScoringOfString(searchTerm) diff --git a/TripKitAndroid/src/main/java/com/skedgo/geocoding/LatLng.kt b/TripKitAndroid/src/main/java/com/skedgo/geocoding/LatLng.kt index 75423b3e..e1b4f35e 100644 --- a/TripKitAndroid/src/main/java/com/skedgo/geocoding/LatLng.kt +++ b/TripKitAndroid/src/main/java/com/skedgo/geocoding/LatLng.kt @@ -1,42 +1,45 @@ -package com.skedgo.geocoding; +package com.skedgo.geocoding +import kotlin.math.abs +import kotlin.math.cos +import kotlin.math.sqrt -import org.jetbrains.annotations.NotNull; -public class LatLng { +class LatLng { + var lat: Double = 0.0 + var lng: Double = 0.0 - public static final double NO_NUM = -3e11; - public static final double EarthRadius = 6371000; - static public final double radians = 3.14159 / 180; - @NotNull - public static LatLng nullLatLong = new LatLng(0, 0); - public double lat, lng; - - public LatLng() { - } + constructor() - public LatLng(double _lat, double _lng) { - lat = _lat; - lng = _lng; + constructor(_lat: Double, _lng: Double) { + lat = _lat + lng = _lng } - public LatLng(LatLng other) { - lat = other.lat; - lng = other.lng; + + constructor(other: LatLng) { + lat = other.lat + lng = other.lng } /** * This is the Equirectangular approximation. It's a little slower than the Region.distanceInMetres() * formula. */ - public double distanceInMetres(//@NotNull - LatLng other) { - double lngDelta = Math.abs(lng - other.lng); - if (lngDelta > 180) - lngDelta = 360 - lngDelta; - double p1 = lngDelta * Math.cos(0.5 * radians * (lat + other.lat)); - double p2 = (lat - other.lat); - return EarthRadius * radians * Math.sqrt(p1 * p1 + p2 * p2); + fun distanceInMetres( //@NotNull + other: LatLng + ): Double { + var lngDelta = abs(lng - other.lng) + if (lngDelta > 180) lngDelta = 360 - lngDelta + val p1 = lngDelta * cos(0.5 * radians * (lat + other.lat)) + val p2 = (lat - other.lat) + return EarthRadius * radians * sqrt(p1 * p1 + p2 * p2) } + companion object { + const val NO_NUM: Double = -3e11 + const val EarthRadius: Double = 6371000.0 + const val radians: Double = 3.14159 / 180 + var nullLatLong: LatLng = LatLng(0.0, 0.0) + } } diff --git a/TripKitAndroid/src/main/java/com/skedgo/geocoding/agregator/GCGoogleResultInterface.kt b/TripKitAndroid/src/main/java/com/skedgo/geocoding/agregator/GCGoogleResultInterface.kt index 9c5414eb..6e3f6dde 100644 --- a/TripKitAndroid/src/main/java/com/skedgo/geocoding/agregator/GCGoogleResultInterface.kt +++ b/TripKitAndroid/src/main/java/com/skedgo/geocoding/agregator/GCGoogleResultInterface.kt @@ -3,5 +3,5 @@ package com.skedgo.geocoding.agregator interface GCGoogleResultInterface : GCResultInterface { // Result address - val address: String + val address: String? } diff --git a/TripKitAndroid/src/main/java/com/skedgo/tripkit/RouteServiceImpl.kt b/TripKitAndroid/src/main/java/com/skedgo/tripkit/RouteServiceImpl.kt index 5f6e23cd..4f02d935 100644 --- a/TripKitAndroid/src/main/java/com/skedgo/tripkit/RouteServiceImpl.kt +++ b/TripKitAndroid/src/main/java/com/skedgo/tripkit/RouteServiceImpl.kt @@ -6,8 +6,8 @@ import androidx.collection.ArrayMap import com.skedgo.tripkit.a2brouting.FailoverA2bRoutingApi import com.skedgo.tripkit.a2brouting.RouteService import com.skedgo.tripkit.a2brouting.ToWeightingProfileString -import com.skedgo.tripkit.common.model.location.Location import com.skedgo.tripkit.common.model.Query +import com.skedgo.tripkit.common.model.location.Location import com.skedgo.tripkit.routing.TripGroup import com.skedgo.tripkit.tsp.RegionInfoRepository import io.reactivex.Observable @@ -40,7 +40,7 @@ internal class RouteServiceImpl( val region = subQuery.region - val baseUrls = region?.getURLs() + val baseUrls = region?.getURLs()?.toList() val modes = transportModeFilter.getFilteredMode(subQuery.transportModeIds) val excludeStops = subQuery.excludedStopCodes @@ -48,7 +48,13 @@ internal class RouteServiceImpl( .filter { transportModeFilter.avoidTransportMode(it) } val options = toOptions(subQuery) - routingApi.fetchRoutesAsync(baseUrls, modes, avoidModes, excludeStops, options) + routingApi.fetchRoutesAsync( + baseUrls.orEmpty(), + modes, + avoidModes, + excludeStops, + options + ) } } diff --git a/TripKitAndroid/src/main/java/com/skedgo/tripkit/a2brouting/A2bRoutingApi.kt b/TripKitAndroid/src/main/java/com/skedgo/tripkit/a2brouting/A2bRoutingApi.kt index d76e2d61..0d67ce1d 100644 --- a/TripKitAndroid/src/main/java/com/skedgo/tripkit/a2brouting/A2bRoutingApi.kt +++ b/TripKitAndroid/src/main/java/com/skedgo/tripkit/a2brouting/A2bRoutingApi.kt @@ -1,27 +1,23 @@ -package com.skedgo.tripkit.a2brouting; +package com.skedgo.tripkit.a2brouting -import com.skedgo.tripkit.routing.RoutingResponse; - -import java.util.List; -import java.util.Map; - -import io.reactivex.Observable; -import retrofit2.http.GET; -import retrofit2.http.Query; -import retrofit2.http.QueryMap; -import retrofit2.http.Url; +import com.skedgo.tripkit.routing.RoutingResponse +import io.reactivex.Observable +import retrofit2.http.GET +import retrofit2.http.Query +import retrofit2.http.QueryMap +import retrofit2.http.Url /** * Calculates door-to-door trips for the specified mode(s). * See more at https://skedgo.github.io/tripgo-api/#tag/Routing%2Fpaths%2F~1routing.json%2Fget. */ -public interface A2bRoutingApi { +interface A2bRoutingApi { @GET - Observable execute( - @Url String url, - @Query("modes") List modes, - @Query("avoid") List excludedTransitModes, - @Query("avoidStops") List excludeStops, - @QueryMap Map options - ); + fun execute( + @Url url: String, + @Query("modes") modes: List, + @Query("avoid") excludedTransitModes: List, + @Query("avoidStops") excludeStops: List, + @QueryMap options: Map + ): Observable } \ No newline at end of file diff --git a/TripKitAndroid/src/main/java/com/skedgo/tripkit/a2brouting/FailoverA2bRoutingApi.kt b/TripKitAndroid/src/main/java/com/skedgo/tripkit/a2brouting/FailoverA2bRoutingApi.kt index 365a5238..d775077b 100644 --- a/TripKitAndroid/src/main/java/com/skedgo/tripkit/a2brouting/FailoverA2bRoutingApi.kt +++ b/TripKitAndroid/src/main/java/com/skedgo/tripkit/a2brouting/FailoverA2bRoutingApi.kt @@ -1,115 +1,99 @@ -package com.skedgo.tripkit.a2brouting; +package com.skedgo.tripkit.a2brouting -import android.content.res.Resources; - -import com.google.gson.Gson; -import com.skedgo.tripkit.RoutingUserError; -import com.skedgo.tripkit.common.model.region.Region; -import com.skedgo.tripkit.routing.RoutingResponse; -import com.skedgo.tripkit.routing.TripGroup; - -import org.apache.commons.collections4.CollectionUtils; - -import java.util.List; -import java.util.Map; - -import io.reactivex.Maybe; -import io.reactivex.Observable; -import io.reactivex.functions.Function; - -import static com.skedgo.tripkit.extensions.StringKt.buildUrlWithQueryParams; -import static com.skedgo.tripkit.routing.RoutingResponse.ERROR_CODE_NO_FROM_LOCATION; +import android.content.res.Resources +import com.google.gson.Gson +import com.skedgo.tripkit.RoutingUserError +import com.skedgo.tripkit.extensions.buildUrlWithQueryParams +import com.skedgo.tripkit.routing.RoutingResponse +import com.skedgo.tripkit.routing.RoutingResponse.Companion.ERROR_CODE_NO_FROM_LOCATION +import com.skedgo.tripkit.routing.TripGroup +import io.reactivex.Maybe +import io.reactivex.Observable /** - * A wrapper of {@link A2bRoutingApi} that requests `routing.json` + * A wrapper of [A2bRoutingApi] that requests `routing.json` * on multiple servers w/ failover. */ -public class FailoverA2bRoutingApi { - private final SelectBestDisplayTrip selectBestDisplayTrip = new SelectBestDisplayTrip(); - private final FillIdentifiers fillIdentifiers = new FillIdentifiers(); - private final Resources resources; - private final Gson gson; - private final A2bRoutingApi a2bRoutingApi; - - public FailoverA2bRoutingApi( - Resources resources, - Gson gson, - A2bRoutingApi a2bRoutingApi - ) { - this.resources = resources; - this.gson = gson; - this.a2bRoutingApi = a2bRoutingApi; - } +class FailoverA2bRoutingApi( + private val resources: Resources, + private val gson: Gson, + private val a2bRoutingApi: A2bRoutingApi +) { + private val selectBestDisplayTrip = SelectBestDisplayTrip() + private val fillIdentifiers = FillIdentifiers() /** - * Fetches routes on multiple base urls serially. - * If it fails on one url, it'll failover on next url. + * Fetches routes on multiple base URLs serially. + * If it fails on one URL, it'll failover to the next URL. * - * @param baseUrls Can be obtained by {@link Region#getURLs()}. + * @param baseUrls Can be obtained by Region.getURLs(). */ - public Observable> fetchRoutesAsync( - List baseUrls, - final List modes, - final List excludedTransitModes, - final List excludeStops, - final Map options - ) { + fun fetchRoutesAsync( + baseUrls: List, + modes: List, + excludedTransitModes: List, + excludeStops: List, + options: Map + ): Observable> { return Observable.fromIterable(baseUrls) - .map(baseUrl -> buildUrlWithQueryParams(baseUrl, modes, excludedTransitModes, excludeStops, options)) - .concatMap(url -> fetchRoutesPerUrlAsync(url, modes, excludedTransitModes, excludeStops, options) - .map(response -> { - List tripGroups = response.getTripGroupList(); - if (CollectionUtils.isNotEmpty(tripGroups)) { - for (TripGroup group : tripGroups) { - group.setFullUrl(url); - selectBestDisplayTrip.apply(group); + .map { baseUrl -> + baseUrl.buildUrlWithQueryParams( + modes, + excludedTransitModes, + excludeStops, + options + ) + } + .concatMap { url -> + fetchRoutesPerUrlAsync(url, modes, excludedTransitModes, excludeStops, options) + .map { response -> + val tripGroups = response.tripGroupList + if (!tripGroups.isNullOrEmpty()) { + tripGroups.forEach { group -> + group.fullUrl = url + selectBestDisplayTrip.apply(group) + } } + response } - return response; - })) - .first(new RoutingResponse()) - .map(response -> { - response.processRawData(resources, gson); - return response.getTripGroupList(); - }) - .filter(CollectionUtils::isNotEmpty) + } + .first(RoutingResponse()) + .map { response -> + response.processRawData(resources, gson) + response.tripGroupList + } + .filter { it.isNotEmpty() } .map(fillIdentifiers) - .map(groups -> { - for (TripGroup group : groups) { - selectBestDisplayTrip.apply(group); - } - return groups; - }) - .onErrorResumeNext(error -> error instanceof RoutingUserError - ? Maybe.error(error) - : Maybe.empty()) - .toObservable(); + .map { groups -> + groups.forEach { group -> selectBestDisplayTrip.apply(group) } + groups + } + .onErrorResumeNext { error: Throwable -> + if (error is RoutingUserError) Maybe.error(error) else Maybe.empty() + } + .toObservable() } - Observable fetchRoutesPerUrlAsync( - final String url, - final List modes, - final List excludedTransitModes, - final List excludeStops, - final Map options - ) { - return a2bRoutingApi - .execute(url, modes, excludedTransitModes, excludeStops, options) - .filter(response -> !(response.getErrorMessage() != null && !response.hasError())) - /* Let it fail silently. */ + private fun fetchRoutesPerUrlAsync( + url: String, + modes: List, + excludedTransitModes: List, + excludeStops: List, + options: Map + ): Observable { + return a2bRoutingApi.execute(url, modes, excludedTransitModes, excludeStops, options) + .filter { response -> !(response.errorMessage != null && !response.hasError()) } .onErrorResumeNext(Observable.empty()) - .flatMap((Function>) response -> { - if (response.getErrorMessage() != null) { - //Only add handling for error 1102 or "No ''from'' location set. Please try again." error for now - //to allow it to fail silently - if (response.getErrorCode().equals(ERROR_CODE_NO_FROM_LOCATION)) { - return Observable.empty(); + .flatMap { response -> + if (response.errorMessage != null) { + if (response.errorCode == ERROR_CODE_NO_FROM_LOCATION) { + Observable.empty() } else { - return Observable.error(new RoutingUserError(response.getErrorMessage())); + Observable.error(RoutingUserError(response.errorMessage.orEmpty())) } } else { - return Observable.just(response); + Observable.just(response) } - }); + } } } \ No newline at end of file From e640476064952e40fb76cacc3c80ed5e414cbc9d Mon Sep 17 00:00:00 2001 From: Michael Angelo Reyes Date: Thu, 7 Nov 2024 02:06:39 +0800 Subject: [PATCH 05/25] Rename .java to .kt --- .../com/skedgo/tripkit/alerts/{AlertBlock.java => AlertBlock.kt} | 0 .../java/com/skedgo/tripkit/alerts/{ModeInfo.java => ModeInfo.kt} | 0 .../tripkit/alerts/{RealtimeAlertApi.java => RealtimeAlertApi.kt} | 0 .../{RealtimeAlertResponse.java => RealtimeAlertResponse.kt} | 0 .../alerts/{RealtimeAlertService.java => RealtimeAlertService.kt} | 0 .../main/java/com/skedgo/tripkit/alerts/{Route.java => Route.kt} | 0 6 files changed, 0 insertions(+), 0 deletions(-) rename TripKitAndroid/src/main/java/com/skedgo/tripkit/alerts/{AlertBlock.java => AlertBlock.kt} (100%) rename TripKitAndroid/src/main/java/com/skedgo/tripkit/alerts/{ModeInfo.java => ModeInfo.kt} (100%) rename TripKitAndroid/src/main/java/com/skedgo/tripkit/alerts/{RealtimeAlertApi.java => RealtimeAlertApi.kt} (100%) rename TripKitAndroid/src/main/java/com/skedgo/tripkit/alerts/{RealtimeAlertResponse.java => RealtimeAlertResponse.kt} (100%) rename TripKitAndroid/src/main/java/com/skedgo/tripkit/alerts/{RealtimeAlertService.java => RealtimeAlertService.kt} (100%) rename TripKitAndroid/src/main/java/com/skedgo/tripkit/alerts/{Route.java => Route.kt} (100%) diff --git a/TripKitAndroid/src/main/java/com/skedgo/tripkit/alerts/AlertBlock.java b/TripKitAndroid/src/main/java/com/skedgo/tripkit/alerts/AlertBlock.kt similarity index 100% rename from TripKitAndroid/src/main/java/com/skedgo/tripkit/alerts/AlertBlock.java rename to TripKitAndroid/src/main/java/com/skedgo/tripkit/alerts/AlertBlock.kt diff --git a/TripKitAndroid/src/main/java/com/skedgo/tripkit/alerts/ModeInfo.java b/TripKitAndroid/src/main/java/com/skedgo/tripkit/alerts/ModeInfo.kt similarity index 100% rename from TripKitAndroid/src/main/java/com/skedgo/tripkit/alerts/ModeInfo.java rename to TripKitAndroid/src/main/java/com/skedgo/tripkit/alerts/ModeInfo.kt diff --git a/TripKitAndroid/src/main/java/com/skedgo/tripkit/alerts/RealtimeAlertApi.java b/TripKitAndroid/src/main/java/com/skedgo/tripkit/alerts/RealtimeAlertApi.kt similarity index 100% rename from TripKitAndroid/src/main/java/com/skedgo/tripkit/alerts/RealtimeAlertApi.java rename to TripKitAndroid/src/main/java/com/skedgo/tripkit/alerts/RealtimeAlertApi.kt diff --git a/TripKitAndroid/src/main/java/com/skedgo/tripkit/alerts/RealtimeAlertResponse.java b/TripKitAndroid/src/main/java/com/skedgo/tripkit/alerts/RealtimeAlertResponse.kt similarity index 100% rename from TripKitAndroid/src/main/java/com/skedgo/tripkit/alerts/RealtimeAlertResponse.java rename to TripKitAndroid/src/main/java/com/skedgo/tripkit/alerts/RealtimeAlertResponse.kt diff --git a/TripKitAndroid/src/main/java/com/skedgo/tripkit/alerts/RealtimeAlertService.java b/TripKitAndroid/src/main/java/com/skedgo/tripkit/alerts/RealtimeAlertService.kt similarity index 100% rename from TripKitAndroid/src/main/java/com/skedgo/tripkit/alerts/RealtimeAlertService.java rename to TripKitAndroid/src/main/java/com/skedgo/tripkit/alerts/RealtimeAlertService.kt diff --git a/TripKitAndroid/src/main/java/com/skedgo/tripkit/alerts/Route.java b/TripKitAndroid/src/main/java/com/skedgo/tripkit/alerts/Route.kt similarity index 100% rename from TripKitAndroid/src/main/java/com/skedgo/tripkit/alerts/Route.java rename to TripKitAndroid/src/main/java/com/skedgo/tripkit/alerts/Route.kt From aae9d96fd62741aec59143b72aad0f227ddf367f Mon Sep 17 00:00:00 2001 From: Michael Angelo Reyes Date: Thu, 7 Nov 2024 02:06:40 +0800 Subject: [PATCH 06/25] [22682] - [TripKit] convert AlertBlock.java to kotlin - [TripKit] convert ModeInfo.java to kotlin - [TripKit] convert RealtimeAlertApi.java to kotlin - [TripKit] convert RealtimeAlertResponse.java to kotlin - [TripKit] convert RealtimeAlertService.java to kotlin - [TripKit] convert Route.java to kotlin --- .../com/skedgo/tripkit/alerts/AlertBlock.kt | 44 +++++------- .../com/skedgo/tripkit/alerts/ModeInfo.kt | 32 ++++----- .../skedgo/tripkit/alerts/RealtimeAlertApi.kt | 30 ++++----- .../tripkit/alerts/RealtimeAlertResponse.kt | 26 +++---- .../tripkit/alerts/RealtimeAlertService.kt | 67 ++++++++----------- .../java/com/skedgo/tripkit/alerts/Route.kt | 43 ++++++------ 6 files changed, 103 insertions(+), 139 deletions(-) diff --git a/TripKitAndroid/src/main/java/com/skedgo/tripkit/alerts/AlertBlock.kt b/TripKitAndroid/src/main/java/com/skedgo/tripkit/alerts/AlertBlock.kt index 71cf76ac..ce71b046 100644 --- a/TripKitAndroid/src/main/java/com/skedgo/tripkit/alerts/AlertBlock.kt +++ b/TripKitAndroid/src/main/java/com/skedgo/tripkit/alerts/AlertBlock.kt @@ -1,37 +1,29 @@ -package com.skedgo.tripkit.alerts; +package com.skedgo.tripkit.alerts -import com.google.gson.annotations.JsonAdapter; -import com.skedgo.tripkit.common.model.realtimealert.RealtimeAlert; - -import androidx.annotation.Nullable; - -import static org.immutables.gson.Gson.TypeAdapters; -import static org.immutables.value.Value.Immutable; -import static org.immutables.value.Value.Style; +import com.google.gson.annotations.JsonAdapter +import com.skedgo.tripkit.common.model.realtimealert.RealtimeAlert +import org.immutables.gson.Gson.TypeAdapters +import org.immutables.value.Value.Immutable +import org.immutables.value.Value.Style @Immutable @TypeAdapters -@Style(passAnnotations = JsonAdapter.class) -@JsonAdapter(GsonAdaptersAlertBlock.class) -public interface AlertBlock { - @Nullable - RealtimeAlert alert(); +@Style(passAnnotations = [JsonAdapter::class]) +@JsonAdapter( + GsonAdaptersAlertBlock::class +) +interface AlertBlock { + fun alert(): RealtimeAlert? - @Nullable - String disruptionType(); + fun disruptionType(): String? - @Nullable - String[] operators(); + fun operators(): Array - @Nullable - Route[] routes(); + fun routes(): Array - @Nullable - ModeInfo modeInfo(); + fun modeInfo(): ModeInfo? - @Nullable - String[] stopCodes(); + fun stopCodes(): Array - @Nullable - String[] serviceTripIDs(); + fun serviceTripIDs(): Array } \ No newline at end of file diff --git a/TripKitAndroid/src/main/java/com/skedgo/tripkit/alerts/ModeInfo.kt b/TripKitAndroid/src/main/java/com/skedgo/tripkit/alerts/ModeInfo.kt index c5ce8580..c3d29bc2 100644 --- a/TripKitAndroid/src/main/java/com/skedgo/tripkit/alerts/ModeInfo.kt +++ b/TripKitAndroid/src/main/java/com/skedgo/tripkit/alerts/ModeInfo.kt @@ -1,25 +1,21 @@ -package com.skedgo.tripkit.alerts; +package com.skedgo.tripkit.alerts -import com.google.gson.annotations.JsonAdapter; -import com.skedgo.tripkit.routing.ServiceColor; - -import androidx.annotation.Nullable; - -import static org.immutables.gson.Gson.TypeAdapters; -import static org.immutables.value.Value.Immutable; -import static org.immutables.value.Value.Style; +import com.google.gson.annotations.JsonAdapter +import com.skedgo.tripkit.routing.ServiceColor +import org.immutables.gson.Gson.TypeAdapters +import org.immutables.value.Value.Immutable +import org.immutables.value.Value.Style @Immutable @TypeAdapters -@Style(passAnnotations = JsonAdapter.class) -@JsonAdapter(GsonAdaptersModeInfo.class) -public interface ModeInfo { - @Nullable - ServiceColor color(); +@Style(passAnnotations = [JsonAdapter::class]) +@JsonAdapter( + GsonAdaptersModeInfo::class +) +interface ModeInfo { + fun color(): ServiceColor? - @Nullable - String identifier(); + fun identifier(): String? - @Nullable - String alt(); + fun alt(): String? } \ No newline at end of file diff --git a/TripKitAndroid/src/main/java/com/skedgo/tripkit/alerts/RealtimeAlertApi.kt b/TripKitAndroid/src/main/java/com/skedgo/tripkit/alerts/RealtimeAlertApi.kt index 8ac7f419..9ff6f049 100644 --- a/TripKitAndroid/src/main/java/com/skedgo/tripkit/alerts/RealtimeAlertApi.kt +++ b/TripKitAndroid/src/main/java/com/skedgo/tripkit/alerts/RealtimeAlertApi.kt @@ -1,27 +1,25 @@ -package com.skedgo.tripkit.alerts; +package com.skedgo.tripkit.alerts -import com.skedgo.tripkit.common.model.region.Region; - -import io.reactivex.Observable; -import retrofit2.http.GET; -import retrofit2.http.Query; -import retrofit2.http.Url; +import io.reactivex.Observable +import retrofit2.http.GET +import retrofit2.http.Query +import retrofit2.http.Url /** - * Use {@link RealtimeAlertService} for easier usages. + * Use [RealtimeAlertService] for easier usages. */ -public interface RealtimeAlertApi { +interface RealtimeAlertApi { /** * See http://skedgo.github.io/tripgo-api/swagger/#!/Transit/get_alerts_transit_json. * * @param url e.g. https://inflationary-br-rj-riodejaneiro.tripgo.skedgo.com/satapp/alerts/transit.json. - * The url is a composition of an URL from {@link Region#getURLs()} - * and `/alerts/transit.json`. - * @param regionName Which is {@link Region#getName()}. + * The url is a composition of an URL from [Region.getURLs] + * and `/alerts/transit.json`. + * @param regionName Which is [Region.getName]. */ @GET - Observable fetchRealtimeAlertsAsync( - @Url String url, - @Query("region") String regionName - ); + fun fetchRealtimeAlertsAsync( + @Url url: String, + @Query("region") regionName: String + ): Observable } \ No newline at end of file diff --git a/TripKitAndroid/src/main/java/com/skedgo/tripkit/alerts/RealtimeAlertResponse.kt b/TripKitAndroid/src/main/java/com/skedgo/tripkit/alerts/RealtimeAlertResponse.kt index 615b4507..c6dd9110 100644 --- a/TripKitAndroid/src/main/java/com/skedgo/tripkit/alerts/RealtimeAlertResponse.kt +++ b/TripKitAndroid/src/main/java/com/skedgo/tripkit/alerts/RealtimeAlertResponse.kt @@ -1,20 +1,16 @@ -package com.skedgo.tripkit.alerts; +package com.skedgo.tripkit.alerts -import com.google.gson.annotations.JsonAdapter; - -import java.util.List; - -import androidx.annotation.Nullable; - -import static org.immutables.gson.Gson.TypeAdapters; -import static org.immutables.value.Value.Immutable; -import static org.immutables.value.Value.Style; +import com.google.gson.annotations.JsonAdapter +import org.immutables.gson.Gson.TypeAdapters +import org.immutables.value.Value.Immutable +import org.immutables.value.Value.Style @Immutable @TypeAdapters -@Style(passAnnotations = JsonAdapter.class) -@JsonAdapter(GsonAdaptersRealtimeAlertResponse.class) -public interface RealtimeAlertResponse { - @Nullable - List alerts(); +@Style(passAnnotations = [JsonAdapter::class]) +@JsonAdapter( + GsonAdaptersRealtimeAlertResponse::class +) +interface RealtimeAlertResponse { + fun alerts(): List } \ No newline at end of file diff --git a/TripKitAndroid/src/main/java/com/skedgo/tripkit/alerts/RealtimeAlertService.kt b/TripKitAndroid/src/main/java/com/skedgo/tripkit/alerts/RealtimeAlertService.kt index 85e87f5c..5786226e 100644 --- a/TripKitAndroid/src/main/java/com/skedgo/tripkit/alerts/RealtimeAlertService.kt +++ b/TripKitAndroid/src/main/java/com/skedgo/tripkit/alerts/RealtimeAlertService.kt @@ -1,49 +1,36 @@ -package com.skedgo.tripkit.alerts; +package com.skedgo.tripkit.alerts -import com.skedgo.tripkit.common.model.region.Region; +import io.reactivex.Observable +import okhttp3.HttpUrl +import okhttp3.HttpUrl.Companion.toHttpUrl +import okhttp3.HttpUrl.Companion.toHttpUrlOrNull +import retrofit2.http.Query +import javax.inject.Inject -import java.util.List; - -import javax.inject.Inject; - -import androidx.annotation.NonNull; -import androidx.annotation.Nullable; -import io.reactivex.Observable; -import io.reactivex.functions.Function; -import okhttp3.HttpUrl; -import retrofit2.http.Query; - -public class RealtimeAlertService { - private final RealtimeAlertApi api; - - @Inject - public RealtimeAlertService(@NonNull RealtimeAlertApi api) { - this.api = api; - } +class RealtimeAlertService @Inject constructor(private val api: RealtimeAlertApi) { /** - * @param baseUrls Which can be obtained via {@link Region#getURLs()}. - * @param regionName Which can be obtained via {@link Region#getName()}. + * @param baseUrls Which can be obtained via [Region.getURLs]. + * @param regionName Which can be obtained via [Region.getName]. */ - public Observable fetchRealtimeAlertsAsync( - @Nullable List baseUrls, - @Query("region") final String regionName) { - if (baseUrls == null) { - return Observable.error(new NullPointerException("baseUrls is null")); + fun fetchRealtimeAlertsAsync( + baseUrls: List?, + @Query("region") regionName: String + ): Observable { + return if (baseUrls == null) { + Observable.error(NullPointerException("baseUrls is null")) } else { - return Observable.fromIterable(baseUrls) - .concatMapDelayError(new Function>() { - @Override - public Observable apply(String baseUrl) { - final String url = HttpUrl.parse(baseUrl) - .newBuilder() - .addPathSegments("alerts/transit.json") - .build() - .toString(); - return api.fetchRealtimeAlertsAsync(url, regionName); - } - }) - .firstElement().toObservable(); + Observable.fromIterable(baseUrls) + .concatMapDelayError { baseUrl -> + val url = baseUrl.toHttpUrl() + .newBuilder() + .addPathSegments("alerts/transit.json") + .build() + .toString() + api.fetchRealtimeAlertsAsync(url, regionName) + } + .firstElement() + .toObservable() } } } \ No newline at end of file diff --git a/TripKitAndroid/src/main/java/com/skedgo/tripkit/alerts/Route.kt b/TripKitAndroid/src/main/java/com/skedgo/tripkit/alerts/Route.kt index cd606526..4306c365 100644 --- a/TripKitAndroid/src/main/java/com/skedgo/tripkit/alerts/Route.kt +++ b/TripKitAndroid/src/main/java/com/skedgo/tripkit/alerts/Route.kt @@ -1,34 +1,29 @@ -package com.skedgo.tripkit.alerts; +package com.skedgo.tripkit.alerts -import com.google.gson.annotations.JsonAdapter; -import com.skedgo.tripkit.routing.ModeInfo; - -import org.immutables.value.Value; - -import androidx.annotation.Nullable; - -import static org.immutables.gson.Gson.TypeAdapters; -import static org.immutables.value.Value.Immutable; -import static org.immutables.value.Value.Style; +import com.google.gson.annotations.JsonAdapter +import com.skedgo.tripkit.routing.ModeInfo +import org.immutables.gson.Gson.TypeAdapters +import org.immutables.value.Value.Default +import org.immutables.value.Value.Immutable +import org.immutables.value.Value.Style @Immutable @TypeAdapters -@Style(passAnnotations = JsonAdapter.class) -@JsonAdapter(GsonAdaptersRoute.class) -public abstract class Route { - public abstract String id(); +@Style(passAnnotations = [JsonAdapter::class]) +@JsonAdapter( + GsonAdaptersRoute::class +) +abstract class Route { + abstract fun id(): String - @Nullable - public abstract String name(); + abstract fun name(): String? - @Nullable - public abstract String number(); + abstract fun number(): String? - @Nullable - public abstract ModeInfo modeInfo(); + abstract fun modeInfo(): ModeInfo? - @Value.Default - int type() { - return -1; + @Default + open fun type(): Int { + return -1 } } From 5247c0d5194c4f42968c23b6170615baddfd99d8 Mon Sep 17 00:00:00 2001 From: Michael Angelo Reyes Date: Thu, 7 Nov 2024 02:52:12 +0800 Subject: [PATCH 07/25] Rename .java to .kt --- .../bookingproviders/{BookingProvider.java => BookingProvider.kt} | 0 .../bookingproviders/{BookingResolver.java => BookingResolver.kt} | 0 .../{BookingResolverImpl.java => BookingResolverImpl.kt} | 0 .../{FlitWaysBookingResolver.java => FlitWaysBookingResolver.kt} | 0 .../{GoCatchBookingResolver.java => GoCatchBookingResolver.kt} | 0 .../{IngogoBookingResolver.java => IngogoBookingResolver.kt} | 0 .../{LyftBookingResolver.java => LyftBookingResolver.kt} | 0 .../{SmsBookingResolver.java => SmsBookingResolver.kt} | 0 .../{TelBookingResolver.java => TelBookingResolver.kt} | 0 .../{WebBookingResolver.java => WebBookingResolver.kt} | 0 10 files changed, 0 insertions(+), 0 deletions(-) rename TripKitAndroid/src/main/java/com/skedgo/tripkit/bookingproviders/{BookingProvider.java => BookingProvider.kt} (100%) rename TripKitAndroid/src/main/java/com/skedgo/tripkit/bookingproviders/{BookingResolver.java => BookingResolver.kt} (100%) rename TripKitAndroid/src/main/java/com/skedgo/tripkit/bookingproviders/{BookingResolverImpl.java => BookingResolverImpl.kt} (100%) rename TripKitAndroid/src/main/java/com/skedgo/tripkit/bookingproviders/{FlitWaysBookingResolver.java => FlitWaysBookingResolver.kt} (100%) rename TripKitAndroid/src/main/java/com/skedgo/tripkit/bookingproviders/{GoCatchBookingResolver.java => GoCatchBookingResolver.kt} (100%) rename TripKitAndroid/src/main/java/com/skedgo/tripkit/bookingproviders/{IngogoBookingResolver.java => IngogoBookingResolver.kt} (100%) rename TripKitAndroid/src/main/java/com/skedgo/tripkit/bookingproviders/{LyftBookingResolver.java => LyftBookingResolver.kt} (100%) rename TripKitAndroid/src/main/java/com/skedgo/tripkit/bookingproviders/{SmsBookingResolver.java => SmsBookingResolver.kt} (100%) rename TripKitAndroid/src/main/java/com/skedgo/tripkit/bookingproviders/{TelBookingResolver.java => TelBookingResolver.kt} (100%) rename TripKitAndroid/src/main/java/com/skedgo/tripkit/bookingproviders/{WebBookingResolver.java => WebBookingResolver.kt} (100%) diff --git a/TripKitAndroid/src/main/java/com/skedgo/tripkit/bookingproviders/BookingProvider.java b/TripKitAndroid/src/main/java/com/skedgo/tripkit/bookingproviders/BookingProvider.kt similarity index 100% rename from TripKitAndroid/src/main/java/com/skedgo/tripkit/bookingproviders/BookingProvider.java rename to TripKitAndroid/src/main/java/com/skedgo/tripkit/bookingproviders/BookingProvider.kt diff --git a/TripKitAndroid/src/main/java/com/skedgo/tripkit/bookingproviders/BookingResolver.java b/TripKitAndroid/src/main/java/com/skedgo/tripkit/bookingproviders/BookingResolver.kt similarity index 100% rename from TripKitAndroid/src/main/java/com/skedgo/tripkit/bookingproviders/BookingResolver.java rename to TripKitAndroid/src/main/java/com/skedgo/tripkit/bookingproviders/BookingResolver.kt diff --git a/TripKitAndroid/src/main/java/com/skedgo/tripkit/bookingproviders/BookingResolverImpl.java b/TripKitAndroid/src/main/java/com/skedgo/tripkit/bookingproviders/BookingResolverImpl.kt similarity index 100% rename from TripKitAndroid/src/main/java/com/skedgo/tripkit/bookingproviders/BookingResolverImpl.java rename to TripKitAndroid/src/main/java/com/skedgo/tripkit/bookingproviders/BookingResolverImpl.kt diff --git a/TripKitAndroid/src/main/java/com/skedgo/tripkit/bookingproviders/FlitWaysBookingResolver.java b/TripKitAndroid/src/main/java/com/skedgo/tripkit/bookingproviders/FlitWaysBookingResolver.kt similarity index 100% rename from TripKitAndroid/src/main/java/com/skedgo/tripkit/bookingproviders/FlitWaysBookingResolver.java rename to TripKitAndroid/src/main/java/com/skedgo/tripkit/bookingproviders/FlitWaysBookingResolver.kt diff --git a/TripKitAndroid/src/main/java/com/skedgo/tripkit/bookingproviders/GoCatchBookingResolver.java b/TripKitAndroid/src/main/java/com/skedgo/tripkit/bookingproviders/GoCatchBookingResolver.kt similarity index 100% rename from TripKitAndroid/src/main/java/com/skedgo/tripkit/bookingproviders/GoCatchBookingResolver.java rename to TripKitAndroid/src/main/java/com/skedgo/tripkit/bookingproviders/GoCatchBookingResolver.kt diff --git a/TripKitAndroid/src/main/java/com/skedgo/tripkit/bookingproviders/IngogoBookingResolver.java b/TripKitAndroid/src/main/java/com/skedgo/tripkit/bookingproviders/IngogoBookingResolver.kt similarity index 100% rename from TripKitAndroid/src/main/java/com/skedgo/tripkit/bookingproviders/IngogoBookingResolver.java rename to TripKitAndroid/src/main/java/com/skedgo/tripkit/bookingproviders/IngogoBookingResolver.kt diff --git a/TripKitAndroid/src/main/java/com/skedgo/tripkit/bookingproviders/LyftBookingResolver.java b/TripKitAndroid/src/main/java/com/skedgo/tripkit/bookingproviders/LyftBookingResolver.kt similarity index 100% rename from TripKitAndroid/src/main/java/com/skedgo/tripkit/bookingproviders/LyftBookingResolver.java rename to TripKitAndroid/src/main/java/com/skedgo/tripkit/bookingproviders/LyftBookingResolver.kt diff --git a/TripKitAndroid/src/main/java/com/skedgo/tripkit/bookingproviders/SmsBookingResolver.java b/TripKitAndroid/src/main/java/com/skedgo/tripkit/bookingproviders/SmsBookingResolver.kt similarity index 100% rename from TripKitAndroid/src/main/java/com/skedgo/tripkit/bookingproviders/SmsBookingResolver.java rename to TripKitAndroid/src/main/java/com/skedgo/tripkit/bookingproviders/SmsBookingResolver.kt diff --git a/TripKitAndroid/src/main/java/com/skedgo/tripkit/bookingproviders/TelBookingResolver.java b/TripKitAndroid/src/main/java/com/skedgo/tripkit/bookingproviders/TelBookingResolver.kt similarity index 100% rename from TripKitAndroid/src/main/java/com/skedgo/tripkit/bookingproviders/TelBookingResolver.java rename to TripKitAndroid/src/main/java/com/skedgo/tripkit/bookingproviders/TelBookingResolver.kt diff --git a/TripKitAndroid/src/main/java/com/skedgo/tripkit/bookingproviders/WebBookingResolver.java b/TripKitAndroid/src/main/java/com/skedgo/tripkit/bookingproviders/WebBookingResolver.kt similarity index 100% rename from TripKitAndroid/src/main/java/com/skedgo/tripkit/bookingproviders/WebBookingResolver.java rename to TripKitAndroid/src/main/java/com/skedgo/tripkit/bookingproviders/WebBookingResolver.kt From de87d3f41579f8f75cede21aa8e2e636f493eff6 Mon Sep 17 00:00:00 2001 From: Michael Angelo Reyes Date: Thu, 7 Nov 2024 02:52:12 +0800 Subject: [PATCH 08/25] [22682] - [TripKit] convert BookingProvider.java to kotlin - [TripKit] convert BookingResolver.java to kotlin - [TripKit] convert BookingResolverImpl.java to kotlin - [TripKit] convert FlitWaysBookingResolver.java to kotlin - [TripKit] convert GoCatchBookingResolver.java to kotlin - [TripKit] convert IngogoBookingResolver.java to kotlin - [TripKit] convert LyftBookingResolver.java to kotlin - [TripKit] convert SmsBookingResolver.java to kotlin - [TripKit] convert TelBookingResolver.java to kotlin - [TripKit] convert WebBookingResolver.java to kotlin --- .../bookingproviders/BookingProvider.kt | 17 +-- .../bookingproviders/BookingResolver.kt | 35 +++-- .../bookingproviders/BookingResolverImpl.kt | 129 ++++++++---------- .../FlitWaysBookingResolver.kt | 129 ++++++++---------- .../GoCatchBookingResolver.kt | 120 +++++++--------- .../bookingproviders/IngogoBookingResolver.kt | 79 +++++------ .../bookingproviders/LyftBookingResolver.kt | 89 ++++++------ .../bookingproviders/MTaxiBookingResolver.kt | 2 +- .../bookingproviders/SmsBookingResolver.kt | 91 ++++++------ .../bookingproviders/TelBookingResolver.kt | 68 ++++----- .../bookingproviders/WebBookingResolver.kt | 45 +++--- 11 files changed, 350 insertions(+), 454 deletions(-) diff --git a/TripKitAndroid/src/main/java/com/skedgo/tripkit/bookingproviders/BookingProvider.kt b/TripKitAndroid/src/main/java/com/skedgo/tripkit/bookingproviders/BookingProvider.kt index 6caf28ed..d388c3fe 100644 --- a/TripKitAndroid/src/main/java/com/skedgo/tripkit/bookingproviders/BookingProvider.kt +++ b/TripKitAndroid/src/main/java/com/skedgo/tripkit/bookingproviders/BookingProvider.kt @@ -1,11 +1,9 @@ -package com.skedgo.tripkit.bookingproviders; +package com.skedgo.tripkit.bookingproviders -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; +import androidx.annotation.IntDef +import kotlin.annotation.AnnotationRetention.SOURCE -import androidx.annotation.IntDef; - -@IntDef({ +@IntDef( BookingResolver.UBER, BookingResolver.LYFT, BookingResolver.FLITWAYS, @@ -14,7 +12,6 @@ import androidx.annotation.IntDef; BookingResolver.MTAXI, BookingResolver.SMS, BookingResolver.OTHERS -}) -@Retention(RetentionPolicy.SOURCE) -public @interface BookingProvider { -} \ No newline at end of file +) +@Retention(SOURCE) +annotation class BookingProvider \ No newline at end of file diff --git a/TripKitAndroid/src/main/java/com/skedgo/tripkit/bookingproviders/BookingResolver.kt b/TripKitAndroid/src/main/java/com/skedgo/tripkit/bookingproviders/BookingResolver.kt index 4d3f60d2..3a1e1d8d 100644 --- a/TripKitAndroid/src/main/java/com/skedgo/tripkit/bookingproviders/BookingResolver.kt +++ b/TripKitAndroid/src/main/java/com/skedgo/tripkit/bookingproviders/BookingResolver.kt @@ -1,23 +1,22 @@ -package com.skedgo.tripkit.bookingproviders; +package com.skedgo.tripkit.bookingproviders -import com.skedgo.tripkit.BookingAction; -import com.skedgo.tripkit.ExternalActionParams; +import com.skedgo.tripkit.BookingAction +import com.skedgo.tripkit.ExternalActionParams +import io.reactivex.Observable -import androidx.annotation.Nullable; -import io.reactivex.Observable; +interface BookingResolver { + fun performExternalActionAsync(params: ExternalActionParams): Observable -public interface BookingResolver { - int UBER = 0; - int LYFT = UBER + 1; - int FLITWAYS = LYFT + 1; - int GOCATCH = FLITWAYS + 1; - int INGOGO = GOCATCH + 1; - int MTAXI = INGOGO + 1; - int SMS = MTAXI + 1; - int OTHERS = SMS + 1; + fun getTitleForExternalAction(externalAction: String): String? - Observable performExternalActionAsync(ExternalActionParams params); - - @Nullable - String getTitleForExternalAction(String externalAction); + companion object { + const val UBER: Int = 0 + const val LYFT: Int = UBER + 1 + const val FLITWAYS: Int = LYFT + 1 + const val GOCATCH: Int = FLITWAYS + 1 + const val INGOGO: Int = GOCATCH + 1 + const val MTAXI: Int = INGOGO + 1 + const val SMS: Int = MTAXI + 1 + const val OTHERS: Int = SMS + 1 + } } \ No newline at end of file diff --git a/TripKitAndroid/src/main/java/com/skedgo/tripkit/bookingproviders/BookingResolverImpl.kt b/TripKitAndroid/src/main/java/com/skedgo/tripkit/bookingproviders/BookingResolverImpl.kt index 3a81a76e..518a5f44 100644 --- a/TripKitAndroid/src/main/java/com/skedgo/tripkit/bookingproviders/BookingResolverImpl.kt +++ b/TripKitAndroid/src/main/java/com/skedgo/tripkit/bookingproviders/BookingResolverImpl.kt @@ -1,94 +1,79 @@ -package com.skedgo.tripkit.bookingproviders; +package com.skedgo.tripkit.bookingproviders -import android.content.Intent; -import android.content.pm.PackageManager; -import android.content.res.Resources; +import android.content.Intent +import android.content.pm.PackageManager +import android.content.pm.PackageManager.NameNotFoundException +import android.content.res.Resources +import com.skedgo.tripkit.BookingAction +import com.skedgo.tripkit.ExternalActionParams +import com.skedgo.tripkit.geocoding.ReverseGeocodable +import io.reactivex.Observable +import io.reactivex.functions.Function -import com.skedgo.tripkit.BookingAction; -import com.skedgo.tripkit.ExternalActionParams; -import com.skedgo.tripkit.geocoding.ReverseGeocodable; +class BookingResolverImpl( + resources: Resources, + packageManager: PackageManager, + geocoderFactory: ReverseGeocodable +) : BookingResolver { + private val resolverMap: MutableMap -import java.util.HashMap; -import java.util.Map; - -import androidx.annotation.NonNull; -import androidx.annotation.Nullable; -import io.reactivex.Observable; -import io.reactivex.functions.Function; - -public final class BookingResolverImpl implements BookingResolver { - private Map resolverMap; - - public BookingResolverImpl( - @NonNull Resources resources, - @NonNull final PackageManager packageManager, - @NonNull ReverseGeocodable geocoderFactory) { - final Function isPackageInstalled = new Function() { - @Override - public Boolean apply(String packageName) { + init { + val isPackageInstalled: Function = object : Function { + override fun apply(packageName: String): Boolean { try { - packageManager.getPackageInfo(packageName, PackageManager.GET_ACTIVITIES); - return true; - } catch (PackageManager.NameNotFoundException ignored) { + packageManager.getPackageInfo(packageName, PackageManager.GET_ACTIVITIES) + return true + } catch (ignored: NameNotFoundException) { } - return false; + return false } - }; + } - final Function getAppIntent = new Function() { - @Override - public Intent apply(String packageName) { - return packageManager.getLaunchIntentForPackage(packageName); - } - }; + val getAppIntent: Function = + Function { packageName -> packageManager.getLaunchIntentForPackage(packageName) } - resolverMap = new HashMap<>(8); - resolverMap.put("gocatch", new GoCatchBookingResolver(resources, isPackageInstalled, geocoderFactory)); - resolverMap.put("ingogo", new IngogoBookingResolver(resources, isPackageInstalled)); - resolverMap.put("mtaxi", new MTaxiBookingResolver(isPackageInstalled, getAppIntent)); - resolverMap.put("uber", new UberBookingResolver(isPackageInstalled, getAppIntent)); - resolverMap.put("lyft", new LyftBookingResolver(resources, isPackageInstalled)); - resolverMap.put("flitways", new FlitWaysBookingResolver(geocoderFactory)); - resolverMap.put("tel:", new TelBookingResolver(resources)); - resolverMap.put("sms:", new SmsBookingResolver()); - resolverMap.put("http", new WebBookingResolver(resources)); + resolverMap = HashMap(8) + resolverMap["gocatch"] = + GoCatchBookingResolver(resources, isPackageInstalled, geocoderFactory) + resolverMap["ingogo"] = IngogoBookingResolver(resources, isPackageInstalled) + resolverMap["mtaxi"] = MTaxiBookingResolver(isPackageInstalled, getAppIntent) + resolverMap["uber"] = UberBookingResolver(isPackageInstalled, getAppIntent) + resolverMap["lyft"] = LyftBookingResolver(resources, isPackageInstalled) + resolverMap["flitways"] = FlitWaysBookingResolver(geocoderFactory) + resolverMap["tel:"] = TelBookingResolver(resources) + resolverMap["sms:"] = SmsBookingResolver() + resolverMap["http"] = WebBookingResolver(resources) } - @Override - public Observable performExternalActionAsync(ExternalActionParams params) { - final String externalAction = params.action(); - final BookingResolver resolver = getBookingResolver(externalAction); - if (resolver != null) { - return resolver.performExternalActionAsync(params); - } else { - return Observable.error(new UnsupportedOperationException("Strange action: " + externalAction)); - } + override fun performExternalActionAsync(params: ExternalActionParams): Observable { + val externalAction = params.action() + val resolver = getBookingResolver(externalAction) + return resolver?.performExternalActionAsync(params) + ?: Observable.error( + UnsupportedOperationException( + "Strange action: $externalAction" + ) + ) } - @Nullable - @Override - public String getTitleForExternalAction(String externalAction) { - BookingResolver resolver = getBookingResolver(externalAction); - if (resolver != null) { - return resolver.getTitleForExternalAction(externalAction); - } else { - return null; - } + override fun getTitleForExternalAction(externalAction: String): String? { + val resolver = getBookingResolver(externalAction) + return resolver?.getTitleForExternalAction(externalAction) } - private BookingResolver getBookingResolver(String externalAction) { - if (externalAction.startsWith("lyft")) { - return resolverMap.get("lyft"); + private fun getBookingResolver(externalAction: String?): BookingResolver? { + return if (externalAction!!.startsWith("lyft")) { + resolverMap["lyft"] } else if (externalAction.startsWith("http")) { - return resolverMap.get("http"); + resolverMap["http"] } else if (externalAction.startsWith("tel:")) { - return resolverMap.get("tel:"); + resolverMap["tel:"] } else if (externalAction.startsWith("sms:")) { - return resolverMap.get("sms:"); + resolverMap["sms:"] } else if (resolverMap.containsKey(externalAction)) { - return resolverMap.get(externalAction); + resolverMap[externalAction] } else { - return null; + null } } } \ No newline at end of file diff --git a/TripKitAndroid/src/main/java/com/skedgo/tripkit/bookingproviders/FlitWaysBookingResolver.kt b/TripKitAndroid/src/main/java/com/skedgo/tripkit/bookingproviders/FlitWaysBookingResolver.kt index f4a003e8..224ebdf6 100644 --- a/TripKitAndroid/src/main/java/com/skedgo/tripkit/bookingproviders/FlitWaysBookingResolver.kt +++ b/TripKitAndroid/src/main/java/com/skedgo/tripkit/bookingproviders/FlitWaysBookingResolver.kt @@ -1,88 +1,77 @@ -package com.skedgo.tripkit.bookingproviders; +package com.skedgo.tripkit.bookingproviders -import android.content.Intent; -import android.net.Uri; +import android.content.Intent +import android.net.Uri +import com.skedgo.tripkit.BookingAction +import com.skedgo.tripkit.ExternalActionParams +import com.skedgo.tripkit.geocoding.ReverseGeocodable +import io.reactivex.Observable +import io.reactivex.functions.BiFunction +import io.reactivex.functions.Function +import io.reactivex.schedulers.Schedulers +import okhttp3.HttpUrl +import okhttp3.HttpUrl.Companion.toHttpUrl +import java.text.SimpleDateFormat +import java.util.Date +import java.util.Locale +import java.util.TimeZone -import com.skedgo.tripkit.BookingAction; -import com.skedgo.tripkit.ExternalActionParams; -import com.skedgo.tripkit.common.model.location.Location; -import com.skedgo.tripkit.geocoding.ReverseGeocodable; -import com.skedgo.tripkit.routing.TripSegment; +internal class FlitWaysBookingResolver(private val geocoderFactory: ReverseGeocodable) : + BookingResolver { -import java.text.SimpleDateFormat; -import java.util.Date; -import java.util.Locale; -import java.util.TimeZone; - -import androidx.annotation.Nullable; -import io.reactivex.Observable; -import io.reactivex.functions.BiFunction; -import io.reactivex.functions.Function; -import io.reactivex.schedulers.Schedulers; -import okhttp3.HttpUrl; - -final class FlitWaysBookingResolver implements BookingResolver { - private final ReverseGeocodable geocoderFactory; - - FlitWaysBookingResolver(ReverseGeocodable geocoderFactory) { - this.geocoderFactory = geocoderFactory; - } - - @Override - public Observable performExternalActionAsync(ExternalActionParams params) { - final BookingAction.Builder actionBuilder = BookingAction.builder() - .bookingProvider(FLITWAYS); - final String flitWaysPartnerKey = params.flitWaysPartnerKey(); + override fun performExternalActionAsync(params: ExternalActionParams): Observable { + val actionBuilder = BookingAction.builder() + .bookingProvider(BookingResolver.FLITWAYS) + val flitWaysPartnerKey = params.flitWaysPartnerKey() if (flitWaysPartnerKey == null) { - final Intent data = new Intent(Intent.ACTION_VIEW) - .setData(Uri.parse("https://flitways.com")); - final BookingAction action = actionBuilder + val data = Intent(Intent.ACTION_VIEW) + .setData(Uri.parse("https://flitways.com")) + val action = actionBuilder .hasApp(false) .data(data) - .build(); - return Observable.just(action); + .build() + return Observable.just(action) } else { // See https://flitways.com/deeplink. - final TripSegment segment = params.segment(); - final Location departure = segment.getFrom(); - final Location arrival = segment.getTo(); - final long startTimeInSecs = segment.getStartTimeInSecs(); - final String timeZone = segment.getTimeZone(); + val segment = params.segment() + val departure = segment.from + val arrival = segment.to + val startTimeInSecs = segment.startTimeInSecs + val timeZone = segment.timeZone return Observable - .fromCallable(() -> { - final SimpleDateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy hh:mm a", Locale.US); + .fromCallable { + val dateFormat = SimpleDateFormat("MM/dd/yyyy hh:mm a", Locale.US) if (timeZone != null) { - dateFormat.setTimeZone(TimeZone.getTimeZone(timeZone)); + dateFormat.timeZone = TimeZone.getTimeZone(timeZone) } - final String tripDate = dateFormat.format(new Date(startTimeInSecs * 1000)); - return HttpUrl.parse("https://flitways.com/api/link") - .newBuilder() + val tripDate = dateFormat.format(Date(startTimeInSecs * 1000)) + "https://flitways.com/api/link".toHttpUrl().newBuilder() .addQueryParameter("trip_date", tripDate) - .addQueryParameter("key", flitWaysPartnerKey); - }) - .flatMap((Function>) builder -> Observable.combineLatest( - geocoderFactory.getAddress(departure.getLat(), departure.getLon()), - geocoderFactory.getAddress(arrival.getLat(), arrival.getLon()), - (BiFunction) (departureAddress, arrivalAddress) -> { - final String url = builder - .addQueryParameter("pickup", departureAddress) - .addQueryParameter("destination", arrivalAddress) - .build() - .toString(); - return actionBuilder - .hasApp(false) - .data(new Intent(Intent.ACTION_VIEW, Uri.parse(url))) - .build(); - } - )) - .subscribeOn(Schedulers.io()); + .addQueryParameter("key", flitWaysPartnerKey) + } + .flatMap(Function> { builder: HttpUrl.Builder -> + Observable.combineLatest( + geocoderFactory.getAddress(departure!!.lat, departure.lon), + geocoderFactory.getAddress(arrival!!.lat, arrival.lon), + BiFunction { departureAddress: String?, arrivalAddress: String? -> + val url: String = builder + .addQueryParameter("pickup", departureAddress) + .addQueryParameter("destination", arrivalAddress) + .build() + .toString() + actionBuilder + .hasApp(false) + .data(Intent(Intent.ACTION_VIEW, Uri.parse(url))) + .build() + } + ) + } as Function>?) + .subscribeOn(Schedulers.io()) } } - @Nullable - @Override - public String getTitleForExternalAction(String externalAction) { - return "Book with FlitWays"; // TODO: i18n. + override fun getTitleForExternalAction(externalAction: String): String { + return "Book with FlitWays" // TODO: i18n. } } \ No newline at end of file diff --git a/TripKitAndroid/src/main/java/com/skedgo/tripkit/bookingproviders/GoCatchBookingResolver.kt b/TripKitAndroid/src/main/java/com/skedgo/tripkit/bookingproviders/GoCatchBookingResolver.kt index ed51a6bc..d7a9e1b6 100644 --- a/TripKitAndroid/src/main/java/com/skedgo/tripkit/bookingproviders/GoCatchBookingResolver.kt +++ b/TripKitAndroid/src/main/java/com/skedgo/tripkit/bookingproviders/GoCatchBookingResolver.kt @@ -1,82 +1,64 @@ -package com.skedgo.tripkit.bookingproviders; +package com.skedgo.tripkit.bookingproviders -import android.content.Intent; -import android.content.res.Resources; -import android.net.Uri; +import android.content.Intent +import android.content.res.Resources +import android.net.Uri +import com.skedgo.tripkit.BookingAction +import com.skedgo.tripkit.ExternalActionParams +import com.skedgo.tripkit.R +import com.skedgo.tripkit.common.model.location.Location +import com.skedgo.tripkit.geocoding.ReverseGeocodable +import io.reactivex.Observable +import io.reactivex.functions.Function -import com.skedgo.tripkit.BookingAction; -import com.skedgo.tripkit.ExternalActionParams; -import com.skedgo.tripkit.R; -import com.skedgo.tripkit.common.model.location.Location; -import com.skedgo.tripkit.geocoding.ReverseGeocodable; -import com.skedgo.tripkit.routing.TripSegment; - -import androidx.annotation.NonNull; -import androidx.annotation.Nullable; -import io.reactivex.Observable; -import io.reactivex.functions.Function; - -final class GoCatchBookingResolver implements BookingResolver { - private static final String GOCATCH_PACKAGE = "com.gocatchapp.goCatch"; - private static final String GOCATCH_CODE = "tripgo"; - - private final Resources resources; - private final Function isPackageInstalled; - private final ReverseGeocodable geocoderFactory; - - GoCatchBookingResolver( - @NonNull Resources resources, - @NonNull Function isPackageInstalled, - @NonNull ReverseGeocodable geocoderFactory) { - this.resources = resources; - this.isPackageInstalled = isPackageInstalled; - this.geocoderFactory = geocoderFactory; - } - - @Override - public Observable performExternalActionAsync(ExternalActionParams params) { +internal class GoCatchBookingResolver( + private val resources: Resources, + private val isPackageInstalled: Function, + private val geocoderFactory: ReverseGeocodable +) : BookingResolver { + override fun performExternalActionAsync(params: ExternalActionParams): Observable { try { if (isPackageInstalled.apply(GOCATCH_PACKAGE)) { - final TripSegment segment = params.segment(); - final Location departure = segment.getFrom(); - final Location arrival = segment.getTo(); - return geocoderFactory.getAddress(arrival.getLat(), arrival.getLon()) - .map(new Function() { - @Override - public BookingAction apply(String arrivalAddress) { - final Uri uri = Uri.parse("gocatch://referral") - .buildUpon() - .appendQueryParameter("code", GOCATCH_CODE) - .appendQueryParameter("destination", arrivalAddress) - .appendQueryParameter("pickup", "") - .appendQueryParameter("lat", String.valueOf(departure.getLat())) - .appendQueryParameter("lng", String.valueOf(departure.getLon())) - .build(); - return BookingAction.builder() - .bookingProvider(GOCATCH) - .hasApp(true) - .data(new Intent(Intent.ACTION_VIEW).setData(uri)) - .build(); - } - }); + val segment = params.segment() + val departure = segment.from ?: Location(0.0,0.0) + val arrival = segment.to ?: Location(0.0,0.0) + return geocoderFactory.getAddress(arrival.lat, arrival.lon) + .map { arrivalAddress -> + val uri = Uri.parse("gocatch://referral") + .buildUpon() + .appendQueryParameter("code", GOCATCH_CODE) + .appendQueryParameter("destination", arrivalAddress) + .appendQueryParameter("pickup", "") + .appendQueryParameter("lat", departure!!.lat.toString()) + .appendQueryParameter("lng", departure.lon.toString()) + .build() + BookingAction.builder() + .bookingProvider(BookingResolver.GOCATCH) + .hasApp(true) + .data(Intent(Intent.ACTION_VIEW).setData(uri)) + .build() + } } else { - final Intent data = new Intent(Intent.ACTION_VIEW) - .setData(Uri.parse("https://play.google.com/store/apps/details?id=" + GOCATCH_PACKAGE)); - final BookingAction action = BookingAction.builder() - .bookingProvider(GOCATCH) + val data = Intent(Intent.ACTION_VIEW) + .setData(Uri.parse("https://play.google.com/store/apps/details?id=$GOCATCH_PACKAGE")) + val action = BookingAction.builder() + .bookingProvider(BookingResolver.GOCATCH) .hasApp(false) .data(data) - .build(); - return Observable.just(action); + .build() + return Observable.just(action) } - } catch (Exception e) { - return Observable.empty(); + } catch (e: Exception) { + return Observable.empty() } } - @Nullable - @Override - public String getTitleForExternalAction(String externalAction) { - return resources.getString(R.string.gocatch_a_taxi); + override fun getTitleForExternalAction(externalAction: String): String { + return resources.getString(R.string.gocatch_a_taxi) + } + + companion object { + private const val GOCATCH_PACKAGE = "com.gocatchapp.goCatch" + private const val GOCATCH_CODE = "tripgo" } } \ No newline at end of file diff --git a/TripKitAndroid/src/main/java/com/skedgo/tripkit/bookingproviders/IngogoBookingResolver.kt b/TripKitAndroid/src/main/java/com/skedgo/tripkit/bookingproviders/IngogoBookingResolver.kt index 98ef92c0..39e40443 100644 --- a/TripKitAndroid/src/main/java/com/skedgo/tripkit/bookingproviders/IngogoBookingResolver.kt +++ b/TripKitAndroid/src/main/java/com/skedgo/tripkit/bookingproviders/IngogoBookingResolver.kt @@ -1,58 +1,47 @@ -package com.skedgo.tripkit.bookingproviders; +package com.skedgo.tripkit.bookingproviders -import android.content.Intent; -import android.content.res.Resources; -import android.net.Uri; +import android.content.Intent +import android.content.res.Resources +import android.net.Uri +import com.skedgo.tripkit.BookingAction +import com.skedgo.tripkit.ExternalActionParams +import com.skedgo.tripkit.R +import io.reactivex.Observable +import io.reactivex.functions.Function -import com.skedgo.tripkit.BookingAction; -import com.skedgo.tripkit.ExternalActionParams; -import com.skedgo.tripkit.R; - -import androidx.annotation.NonNull; -import androidx.annotation.Nullable; -import io.reactivex.Observable; -import io.reactivex.functions.Function; - -final class IngogoBookingResolver implements BookingResolver { - private static final String INGOGO_PACKAGE = "com.ingogo.passenger"; - private final Resources resources; - private final Function isPackageInstalled; - - public IngogoBookingResolver( - @NonNull Resources resources, - @NonNull Function isPackageInstalled) { - this.resources = resources; - this.isPackageInstalled = isPackageInstalled; - } - - @Override - public Observable performExternalActionAsync(ExternalActionParams params) { - final BookingAction.Builder actionBuilder = BookingAction.builder(); - actionBuilder.bookingProvider(INGOGO); +internal class IngogoBookingResolver( + private val resources: Resources, + private val isPackageInstalled: Function +) : BookingResolver { + override fun performExternalActionAsync(params: ExternalActionParams): Observable { + val actionBuilder = BookingAction.builder() + actionBuilder.bookingProvider(BookingResolver.INGOGO) try { if (isPackageInstalled.apply(INGOGO_PACKAGE)) { - final BookingAction action = actionBuilder.hasApp(true).data( - new Intent(Intent.ACTION_VIEW).setData(Uri.parse("ingogo://")) - ).build(); - return Observable.just(action); + val action = actionBuilder.hasApp(true).data( + Intent(Intent.ACTION_VIEW).setData(Uri.parse("ingogo://")) + ).build() + return Observable.just(action) } else { - final Intent data = new Intent(Intent.ACTION_VIEW) - .setData(Uri.parse("https://play.google.com/store/apps/details?id=" + INGOGO_PACKAGE)); - final BookingAction action = actionBuilder + val data = Intent(Intent.ACTION_VIEW) + .setData(Uri.parse("https://play.google.com/store/apps/details?id=$INGOGO_PACKAGE")) + val action = actionBuilder .hasApp(false) .data(data) - .build(); - return Observable.just(action); + .build() + return Observable.just(action) } - } catch (Exception e) { - e.printStackTrace(); - return Observable.empty(); + } catch (e: Exception) { + e.printStackTrace() + return Observable.empty() } } - @Nullable - @Override - public String getTitleForExternalAction(String externalAction) { - return resources.getString(R.string.ingogo_a_taxi); + override fun getTitleForExternalAction(externalAction: String): String { + return resources.getString(R.string.ingogo_a_taxi) + } + + companion object { + private const val INGOGO_PACKAGE = "com.ingogo.passenger" } } \ No newline at end of file diff --git a/TripKitAndroid/src/main/java/com/skedgo/tripkit/bookingproviders/LyftBookingResolver.kt b/TripKitAndroid/src/main/java/com/skedgo/tripkit/bookingproviders/LyftBookingResolver.kt index 0efd9fca..2ed763a6 100644 --- a/TripKitAndroid/src/main/java/com/skedgo/tripkit/bookingproviders/LyftBookingResolver.kt +++ b/TripKitAndroid/src/main/java/com/skedgo/tripkit/bookingproviders/LyftBookingResolver.kt @@ -1,65 +1,54 @@ -package com.skedgo.tripkit.bookingproviders; +package com.skedgo.tripkit.bookingproviders -import android.content.Intent; -import android.content.res.Resources; -import android.net.Uri; +import android.content.Intent +import android.content.res.Resources +import android.net.Uri +import com.skedgo.tripkit.BookingAction +import com.skedgo.tripkit.ExternalActionParams +import com.skedgo.tripkit.R +import io.reactivex.Observable +import io.reactivex.functions.Function -import com.skedgo.tripkit.BookingAction; -import com.skedgo.tripkit.ExternalActionParams; -import com.skedgo.tripkit.R; - -import androidx.annotation.NonNull; -import androidx.annotation.Nullable; -import io.reactivex.Observable; -import io.reactivex.functions.Function; - -final class LyftBookingResolver implements BookingResolver { - private static final String LYFT_PACKAGE = "me.lyft.android"; - private final Resources resources; - private final Function isPackageInstalled; - - public LyftBookingResolver( - @NonNull Resources resources, - @NonNull Function isPackageInstalled) { - this.resources = resources; - this.isPackageInstalled = isPackageInstalled; - } - - @Override - public Observable performExternalActionAsync(ExternalActionParams params) { - final BookingAction.Builder actionBuilder = BookingAction.builder(); - actionBuilder.bookingProvider(LYFT); +internal class LyftBookingResolver( + private val resources: Resources, + private val isPackageInstalled: Function +) : BookingResolver { + override fun performExternalActionAsync(params: ExternalActionParams): Observable { + val actionBuilder = BookingAction.builder() + actionBuilder.bookingProvider(BookingResolver.LYFT) try { if (isPackageInstalled.apply(LYFT_PACKAGE)) { - final BookingAction action = actionBuilder.hasApp(true).data( - new Intent(Intent.ACTION_VIEW).setData(Uri.parse("lyft://")) - ).build(); - return Observable.just(action); + val action = actionBuilder.hasApp(true).data( + Intent(Intent.ACTION_VIEW).setData(Uri.parse("lyft://")) + ).build() + return Observable.just(action) } else { - final Intent data = new Intent(Intent.ACTION_VIEW) - .setData(Uri.parse("https://play.google.com/store/apps/details?id=" + LYFT_PACKAGE)); - final BookingAction action = actionBuilder + val data = Intent(Intent.ACTION_VIEW) + .setData(Uri.parse("https://play.google.com/store/apps/details?id=$LYFT_PACKAGE")) + val action = actionBuilder .hasApp(false) .data(data) - .build(); - return Observable.just(action); + .build() + return Observable.just(action) } - } catch (Exception e) { - e.printStackTrace(); - return Observable.empty(); + } catch (e: Exception) { + e.printStackTrace() + return Observable.empty() } } - @Nullable - @Override - public String getTitleForExternalAction(String externalAction) { + override fun getTitleForExternalAction(externalAction: String): String { try { - return isPackageInstalled.apply(LYFT_PACKAGE) - ? resources.getString(R.string.open_lyft) - : resources.getString(R.string.get_lyft); - } catch (Exception e) { - e.printStackTrace(); - return resources.getString(R.string.get_lyft); + return if (isPackageInstalled.apply(LYFT_PACKAGE) + ) resources.getString(R.string.open_lyft) + else resources.getString(R.string.get_lyft) + } catch (e: Exception) { + e.printStackTrace() + return resources.getString(R.string.get_lyft) } } + + companion object { + private const val LYFT_PACKAGE = "me.lyft.android" + } } \ No newline at end of file diff --git a/TripKitAndroid/src/main/java/com/skedgo/tripkit/bookingproviders/MTaxiBookingResolver.kt b/TripKitAndroid/src/main/java/com/skedgo/tripkit/bookingproviders/MTaxiBookingResolver.kt index 112338ff..23306f6e 100644 --- a/TripKitAndroid/src/main/java/com/skedgo/tripkit/bookingproviders/MTaxiBookingResolver.kt +++ b/TripKitAndroid/src/main/java/com/skedgo/tripkit/bookingproviders/MTaxiBookingResolver.kt @@ -10,7 +10,7 @@ private val MTAXI_PACKAGE = "au.com.mtaxi" internal class MTaxiBookingResolver( private val isPackageInstalled: Function, private val getAppIntent: Function -) : com.skedgo.tripkit.bookingproviders.BookingResolver { +) : BookingResolver { override fun performExternalActionAsync(params: com.skedgo.tripkit.ExternalActionParams): Observable { val actionBuilder = com.skedgo.tripkit.BookingAction.builder() diff --git a/TripKitAndroid/src/main/java/com/skedgo/tripkit/bookingproviders/SmsBookingResolver.kt b/TripKitAndroid/src/main/java/com/skedgo/tripkit/bookingproviders/SmsBookingResolver.kt index bf7b1839..5a3b49f3 100644 --- a/TripKitAndroid/src/main/java/com/skedgo/tripkit/bookingproviders/SmsBookingResolver.kt +++ b/TripKitAndroid/src/main/java/com/skedgo/tripkit/bookingproviders/SmsBookingResolver.kt @@ -1,56 +1,47 @@ -package com.skedgo.tripkit.bookingproviders; - -import android.content.Intent; -import android.net.Uri; - -import com.skedgo.tripkit.BookingAction; -import com.skedgo.tripkit.ExternalActionParams; - -import androidx.annotation.NonNull; -import androidx.annotation.Nullable; -import io.reactivex.Observable; - -final class SmsBookingResolver implements BookingResolver { - public SmsBookingResolver() { - } - - /** - * @param uri e.g. 'sms:12345' where '12345' is phone number. - */ - @NonNull - static Intent createSmsIntentByUri(String uri, String smsBody) { - // Put EXTRA_TEXT to avoid missing body on Samsung devices running 5.0. - return new Intent(Intent.ACTION_VIEW) - .setData(Uri.parse(uri)) - .putExtra("sms_body", smsBody) - .putExtra(Intent.EXTRA_TEXT, smsBody); - } - - /** - * @param action e.g. 'sms:12345?Body goes here' - * where '12345' is phone number and 'Body goes here' is sms body. - */ - @NonNull - static Intent createSmsIntentByAction(@NonNull String action) { - final String[] parts = action.split("\\?"); - final String uri = parts.length > 0 ? parts[0] : null; - final String smsBody = parts.length > 1 ? parts[1] : null; - return createSmsIntentByUri(uri, smsBody); - } - - @Override - public Observable performExternalActionAsync(ExternalActionParams params) { - final BookingAction action = BookingAction.builder() - .bookingProvider(SMS) +package com.skedgo.tripkit.bookingproviders + +import android.content.Intent +import android.net.Uri +import com.skedgo.tripkit.BookingAction +import com.skedgo.tripkit.ExternalActionParams +import io.reactivex.Observable + +internal class SmsBookingResolver : BookingResolver { + override fun performExternalActionAsync(params: ExternalActionParams): Observable { + val action = BookingAction.builder() + .bookingProvider(BookingResolver.SMS) .hasApp(false) .data(createSmsIntentByAction(params.action())) - .build(); - return Observable.just(action); + .build() + return Observable.just(action) + } + + override fun getTitleForExternalAction(externalAction: String): String? { + return "Send SMS" // TODO: i18n. } - @Nullable - @Override - public String getTitleForExternalAction(String externalAction) { - return "Send SMS"; // TODO: i18n. + companion object { + /** + * @param uri e.g. 'sms:12345' where '12345' is phone number. + */ + fun createSmsIntentByUri(uri: String?, smsBody: String?): Intent { + // Put EXTRA_TEXT to avoid missing body on Samsung devices running 5.0. + return Intent(Intent.ACTION_VIEW) + .setData(Uri.parse(uri)) + .putExtra("sms_body", smsBody) + .putExtra(Intent.EXTRA_TEXT, smsBody) + } + + /** + * @param action e.g. 'sms:12345?Body goes here' + * where '12345' is phone number and 'Body goes here' is sms body. + */ + @JvmStatic + fun createSmsIntentByAction(action: String): Intent { + val parts = action.split("\\?".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray() + val uri = if (parts.size > 0) parts[0] else null + val smsBody = if (parts.size > 1) parts[1] else null + return createSmsIntentByUri(uri, smsBody) + } } } \ No newline at end of file diff --git a/TripKitAndroid/src/main/java/com/skedgo/tripkit/bookingproviders/TelBookingResolver.kt b/TripKitAndroid/src/main/java/com/skedgo/tripkit/bookingproviders/TelBookingResolver.kt index 8793039c..1a35431b 100644 --- a/TripKitAndroid/src/main/java/com/skedgo/tripkit/bookingproviders/TelBookingResolver.kt +++ b/TripKitAndroid/src/main/java/com/skedgo/tripkit/bookingproviders/TelBookingResolver.kt @@ -1,52 +1,40 @@ -package com.skedgo.tripkit.bookingproviders; - -import android.content.Intent; -import android.content.res.Resources; -import android.net.Uri; - -import com.skedgo.tripkit.BookingAction; -import com.skedgo.tripkit.ExternalActionParams; -import com.skedgo.tripkit.R; - -import java.io.UnsupportedEncodingException; -import java.net.URLDecoder; - -import androidx.annotation.Nullable; -import io.reactivex.Observable; - -final class TelBookingResolver implements BookingResolver { - private final Resources resources; - - public TelBookingResolver(Resources resources) { - this.resources = resources; - } - - @Override - public Observable performExternalActionAsync(ExternalActionParams params) { - String telAction = params.action(); +package com.skedgo.tripkit.bookingproviders + +import android.content.Intent +import android.content.res.Resources +import android.net.Uri +import com.skedgo.tripkit.BookingAction +import com.skedgo.tripkit.ExternalActionParams +import com.skedgo.tripkit.R +import io.reactivex.Observable +import java.io.UnsupportedEncodingException +import java.net.URLDecoder + +internal class TelBookingResolver(private val resources: Resources) : BookingResolver { + override fun performExternalActionAsync(params: ExternalActionParams): Observable { + var telAction = params.action() if (telAction.contains("?name=")) { - telAction = telAction.substring(0, telAction.indexOf("?name=")); + telAction = telAction.substring(0, telAction.indexOf("?name=")) } - final BookingAction action = BookingAction.builder() - .bookingProvider(OTHERS) + val action = BookingAction.builder() + .bookingProvider(BookingResolver.OTHERS) .hasApp(false) - .data(new Intent(Intent.ACTION_VIEW, Uri.parse(telAction))) - .build(); - return Observable.just(action); + .data(Intent(Intent.ACTION_VIEW, Uri.parse(telAction))) + .build() + return Observable.just(action) } - @Nullable - @Override - public String getTitleForExternalAction(String externalAction) { + override fun getTitleForExternalAction(externalAction: String): String? { if (externalAction.contains("name=")) { - String name = externalAction.substring(externalAction.indexOf("name=") + "name=".length()); + var name: String? = + externalAction.substring(externalAction.indexOf("name=") + "name=".length) try { - name = URLDecoder.decode(name, "UTF-8"); - } catch (UnsupportedEncodingException e) { + name = URLDecoder.decode(name, "UTF-8") + } catch (e: UnsupportedEncodingException) { } - return resources.getString(R.string.call__pattern, name); + return resources.getString(R.string.call__pattern, name) } else { - return resources.getString(R.string.call); + return resources.getString(R.string.call) } } } \ No newline at end of file diff --git a/TripKitAndroid/src/main/java/com/skedgo/tripkit/bookingproviders/WebBookingResolver.kt b/TripKitAndroid/src/main/java/com/skedgo/tripkit/bookingproviders/WebBookingResolver.kt index 5cb1497f..b83840cb 100644 --- a/TripKitAndroid/src/main/java/com/skedgo/tripkit/bookingproviders/WebBookingResolver.kt +++ b/TripKitAndroid/src/main/java/com/skedgo/tripkit/bookingproviders/WebBookingResolver.kt @@ -1,37 +1,24 @@ -package com.skedgo.tripkit.bookingproviders; +package com.skedgo.tripkit.bookingproviders -import android.content.Intent; -import android.content.res.Resources; -import android.net.Uri; +import android.content.Intent +import android.content.res.Resources +import android.net.Uri +import com.skedgo.tripkit.BookingAction +import com.skedgo.tripkit.ExternalActionParams +import com.skedgo.tripkit.R +import io.reactivex.Observable -import com.skedgo.tripkit.BookingAction; -import com.skedgo.tripkit.ExternalActionParams; -import com.skedgo.tripkit.R; - -import androidx.annotation.NonNull; -import androidx.annotation.Nullable; -import io.reactivex.Observable; - -final class WebBookingResolver implements BookingResolver { - private final Resources resources; - - public WebBookingResolver(@NonNull Resources resources) { - this.resources = resources; - } - - @Override - public Observable performExternalActionAsync(ExternalActionParams params) { - final BookingAction action = BookingAction.builder() +internal class WebBookingResolver(private val resources: Resources) : BookingResolver { + override fun performExternalActionAsync(params: ExternalActionParams): Observable { + val action = BookingAction.builder() .bookingProvider(BookingResolver.OTHERS) .hasApp(false) - .data(new Intent(Intent.ACTION_VIEW, Uri.parse(params.action()))) - .build(); - return Observable.just(action); + .data(Intent(Intent.ACTION_VIEW, Uri.parse(params.action()))) + .build() + return Observable.just(action) } - @Nullable - @Override - public String getTitleForExternalAction(String externalAction) { - return resources.getString(R.string.show_website); + override fun getTitleForExternalAction(externalAction: String): String? { + return resources.getString(R.string.show_website) } } \ No newline at end of file From 41ab0c31aa3953cf5c28769a8026d51bebaa48e9 Mon Sep 17 00:00:00 2001 From: Michael Angelo Reyes Date: Thu, 7 Nov 2024 10:55:54 +0800 Subject: [PATCH 09/25] Rename .java to .kt --- .../{ExtraQueryMapProvider.java => ExtraQueryMapProvider.kt} | 0 .../tripkit/scope/{ExtensionScope.java => ExtensionScope.kt} | 0 .../skedgo/tripkit/tsp/{RegionInfoApi.java => RegionInfoApi.kt} | 0 .../skedgo/tripkit/tsp/{RegionInfoBody.java => RegionInfoBody.kt} | 0 .../tsp/{RegionInfoResponse.java => RegionInfoResponse.kt} | 0 .../tripkit/tsp/{RegionInfoService.java => RegionInfoService.kt} | 0 .../java/com/skedgo/tripkit/tsp/{TspModule.java => TspModule.kt} | 0 7 files changed, 0 insertions(+), 0 deletions(-) rename TripKitAndroid/src/main/java/com/skedgo/tripkit/routing/{ExtraQueryMapProvider.java => ExtraQueryMapProvider.kt} (100%) rename TripKitAndroid/src/main/java/com/skedgo/tripkit/scope/{ExtensionScope.java => ExtensionScope.kt} (100%) rename TripKitAndroid/src/main/java/com/skedgo/tripkit/tsp/{RegionInfoApi.java => RegionInfoApi.kt} (100%) rename TripKitAndroid/src/main/java/com/skedgo/tripkit/tsp/{RegionInfoBody.java => RegionInfoBody.kt} (100%) rename TripKitAndroid/src/main/java/com/skedgo/tripkit/tsp/{RegionInfoResponse.java => RegionInfoResponse.kt} (100%) rename TripKitAndroid/src/main/java/com/skedgo/tripkit/tsp/{RegionInfoService.java => RegionInfoService.kt} (100%) rename TripKitAndroid/src/main/java/com/skedgo/tripkit/tsp/{TspModule.java => TspModule.kt} (100%) diff --git a/TripKitAndroid/src/main/java/com/skedgo/tripkit/routing/ExtraQueryMapProvider.java b/TripKitAndroid/src/main/java/com/skedgo/tripkit/routing/ExtraQueryMapProvider.kt similarity index 100% rename from TripKitAndroid/src/main/java/com/skedgo/tripkit/routing/ExtraQueryMapProvider.java rename to TripKitAndroid/src/main/java/com/skedgo/tripkit/routing/ExtraQueryMapProvider.kt diff --git a/TripKitAndroid/src/main/java/com/skedgo/tripkit/scope/ExtensionScope.java b/TripKitAndroid/src/main/java/com/skedgo/tripkit/scope/ExtensionScope.kt similarity index 100% rename from TripKitAndroid/src/main/java/com/skedgo/tripkit/scope/ExtensionScope.java rename to TripKitAndroid/src/main/java/com/skedgo/tripkit/scope/ExtensionScope.kt diff --git a/TripKitAndroid/src/main/java/com/skedgo/tripkit/tsp/RegionInfoApi.java b/TripKitAndroid/src/main/java/com/skedgo/tripkit/tsp/RegionInfoApi.kt similarity index 100% rename from TripKitAndroid/src/main/java/com/skedgo/tripkit/tsp/RegionInfoApi.java rename to TripKitAndroid/src/main/java/com/skedgo/tripkit/tsp/RegionInfoApi.kt diff --git a/TripKitAndroid/src/main/java/com/skedgo/tripkit/tsp/RegionInfoBody.java b/TripKitAndroid/src/main/java/com/skedgo/tripkit/tsp/RegionInfoBody.kt similarity index 100% rename from TripKitAndroid/src/main/java/com/skedgo/tripkit/tsp/RegionInfoBody.java rename to TripKitAndroid/src/main/java/com/skedgo/tripkit/tsp/RegionInfoBody.kt diff --git a/TripKitAndroid/src/main/java/com/skedgo/tripkit/tsp/RegionInfoResponse.java b/TripKitAndroid/src/main/java/com/skedgo/tripkit/tsp/RegionInfoResponse.kt similarity index 100% rename from TripKitAndroid/src/main/java/com/skedgo/tripkit/tsp/RegionInfoResponse.java rename to TripKitAndroid/src/main/java/com/skedgo/tripkit/tsp/RegionInfoResponse.kt diff --git a/TripKitAndroid/src/main/java/com/skedgo/tripkit/tsp/RegionInfoService.java b/TripKitAndroid/src/main/java/com/skedgo/tripkit/tsp/RegionInfoService.kt similarity index 100% rename from TripKitAndroid/src/main/java/com/skedgo/tripkit/tsp/RegionInfoService.java rename to TripKitAndroid/src/main/java/com/skedgo/tripkit/tsp/RegionInfoService.kt diff --git a/TripKitAndroid/src/main/java/com/skedgo/tripkit/tsp/TspModule.java b/TripKitAndroid/src/main/java/com/skedgo/tripkit/tsp/TspModule.kt similarity index 100% rename from TripKitAndroid/src/main/java/com/skedgo/tripkit/tsp/TspModule.java rename to TripKitAndroid/src/main/java/com/skedgo/tripkit/tsp/TspModule.kt From 7b98c94a8393a67c555798b4fe72337fc71d8889 Mon Sep 17 00:00:00 2001 From: Michael Angelo Reyes Date: Thu, 7 Nov 2024 10:55:54 +0800 Subject: [PATCH 10/25] [22682] - [TripKit] convert ExtensionScope.java to kotlin - [TripKit] convert ExtraQueryMapProvider.java to kotlin - [TripKit] convert RegionInfoApi.java to kotlin - [TripKit] convert RegionInfoBody.java to kotlin - [TripKit] convert RegionInfoResponse.java to kotlin - [TripKit] convert RegionInfoService.java to kotlin - [TripKit] convert TspModule.java to kotlin --- .../tripkit/routing/ExtraQueryMapProvider.kt | 17 ++--- .../skedgo/tripkit/scope/ExtensionScope.kt | 13 ++-- .../com/skedgo/tripkit/tsp/RegionInfoApi.kt | 35 +++++---- .../com/skedgo/tripkit/tsp/RegionInfoBody.kt | 29 ++++---- .../skedgo/tripkit/tsp/RegionInfoResponse.kt | 28 +++---- .../skedgo/tripkit/tsp/RegionInfoService.kt | 74 ++++++++----------- .../java/com/skedgo/tripkit/tsp/TspModule.kt | 35 ++++----- 7 files changed, 100 insertions(+), 131 deletions(-) diff --git a/TripKitAndroid/src/main/java/com/skedgo/tripkit/routing/ExtraQueryMapProvider.kt b/TripKitAndroid/src/main/java/com/skedgo/tripkit/routing/ExtraQueryMapProvider.kt index faa2158a..596b7b81 100644 --- a/TripKitAndroid/src/main/java/com/skedgo/tripkit/routing/ExtraQueryMapProvider.kt +++ b/TripKitAndroid/src/main/java/com/skedgo/tripkit/routing/ExtraQueryMapProvider.kt @@ -1,23 +1,16 @@ -package com.skedgo.tripkit.routing; - -import com.skedgo.tripkit.a2brouting.A2bRoutingApi; - -import java.util.Map; - -import androidx.annotation.NonNull; +package com.skedgo.tripkit.routing /** * A decorator that puts additional query params - * into the query map that is supplied into {@link A2bRoutingApi}. + * into the query map that is supplied into [A2bRoutingApi]. * Note that you should only use this when * you really do know what you intend to do. */ -public interface ExtraQueryMapProvider { +interface ExtraQueryMapProvider { /** * Be careful that some entries of this map * may override some default entries of - * the query map of {@link A2bRoutingApi}. + * the query map of [A2bRoutingApi]. */ - @NonNull - Map call(); + fun call(): Map } \ No newline at end of file diff --git a/TripKitAndroid/src/main/java/com/skedgo/tripkit/scope/ExtensionScope.kt b/TripKitAndroid/src/main/java/com/skedgo/tripkit/scope/ExtensionScope.kt index f4ab8ae7..1bd4b354 100644 --- a/TripKitAndroid/src/main/java/com/skedgo/tripkit/scope/ExtensionScope.kt +++ b/TripKitAndroid/src/main/java/com/skedgo/tripkit/scope/ExtensionScope.kt @@ -1,11 +1,8 @@ -package com.skedgo.tripkit.scope; +package com.skedgo.tripkit.scope -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; - -import javax.inject.Scope; +import javax.inject.Scope +import kotlin.annotation.AnnotationRetention.RUNTIME @Scope -@Retention(RetentionPolicy.RUNTIME) -public @interface ExtensionScope { -} \ No newline at end of file +@Retention(RUNTIME) +annotation class ExtensionScope \ No newline at end of file diff --git a/TripKitAndroid/src/main/java/com/skedgo/tripkit/tsp/RegionInfoApi.kt b/TripKitAndroid/src/main/java/com/skedgo/tripkit/tsp/RegionInfoApi.kt index de2adae5..525431bb 100644 --- a/TripKitAndroid/src/main/java/com/skedgo/tripkit/tsp/RegionInfoApi.kt +++ b/TripKitAndroid/src/main/java/com/skedgo/tripkit/tsp/RegionInfoApi.kt @@ -1,32 +1,31 @@ -package com.skedgo.tripkit.tsp; +package com.skedgo.tripkit.tsp -import com.skedgo.tripkit.common.model.region.Region; - -import io.reactivex.Observable; -import retrofit2.http.Body; -import retrofit2.http.POST; -import retrofit2.http.Url; +import io.reactivex.Observable +import retrofit2.http.Body +import retrofit2.http.POST +import retrofit2.http.Url /** * Retrieves detailed information about covered * transport service providers for the specified regions. - *

+ * + * * See http://skedgo.github.io/tripgo-api/swagger/#!/Configuration/post_regionInfo_json. - * See {@link RegionInfoService} for easier usage. + * See [RegionInfoService] for easier usage. */ -public interface RegionInfoApi { +interface RegionInfoApi { @POST("regionInfo.json") - RegionInfoResponse fetchRegionInfo( - @Body RegionInfoBody body - ); + fun fetchRegionInfo( + @Body body: RegionInfoBody + ): RegionInfoResponse /** * @param url The url is a composition of an URL - * from {@link Region#getURLs()} and 'regionInfo.json'. + * from [Region.getURLs] and 'regionInfo.json'. */ @POST - Observable fetchRegionInfoAsync( - @Url String url, - @Body RegionInfoBody body - ); + fun fetchRegionInfoAsync( + @Url url: String, + @Body body: RegionInfoBody + ): Observable } \ No newline at end of file diff --git a/TripKitAndroid/src/main/java/com/skedgo/tripkit/tsp/RegionInfoBody.kt b/TripKitAndroid/src/main/java/com/skedgo/tripkit/tsp/RegionInfoBody.kt index 212bf54d..9590785f 100644 --- a/TripKitAndroid/src/main/java/com/skedgo/tripkit/tsp/RegionInfoBody.kt +++ b/TripKitAndroid/src/main/java/com/skedgo/tripkit/tsp/RegionInfoBody.kt @@ -1,22 +1,21 @@ -package com.skedgo.tripkit.tsp; +package com.skedgo.tripkit.tsp -import com.google.gson.annotations.JsonAdapter; -import com.skedgo.tripkit.common.model.region.Region; - -import org.immutables.value.Value; - -import static org.immutables.gson.Gson.TypeAdapters; -import static org.immutables.value.Value.Immutable; -import static org.immutables.value.Value.Style; +import com.google.gson.annotations.JsonAdapter +import org.immutables.gson.Gson.TypeAdapters +import org.immutables.value.Value.Immutable +import org.immutables.value.Value.Parameter +import org.immutables.value.Value.Style @Immutable @TypeAdapters -@Style(passAnnotations = JsonAdapter.class) -@JsonAdapter(GsonAdaptersRegionInfoBody.class) -public interface RegionInfoBody { +@Style(passAnnotations = [JsonAdapter::class]) +@JsonAdapter( + GsonAdaptersRegionInfoBody::class +) +interface RegionInfoBody { /** - * @return {@link Region#getName()}. + * @return [Region.getName]. */ - @Value.Parameter - String region(); + @Parameter + fun region(): String } \ No newline at end of file diff --git a/TripKitAndroid/src/main/java/com/skedgo/tripkit/tsp/RegionInfoResponse.kt b/TripKitAndroid/src/main/java/com/skedgo/tripkit/tsp/RegionInfoResponse.kt index 3654f3f2..ae837718 100644 --- a/TripKitAndroid/src/main/java/com/skedgo/tripkit/tsp/RegionInfoResponse.kt +++ b/TripKitAndroid/src/main/java/com/skedgo/tripkit/tsp/RegionInfoResponse.kt @@ -1,21 +1,17 @@ -package com.skedgo.tripkit.tsp; +package com.skedgo.tripkit.tsp -import com.google.gson.annotations.JsonAdapter; -import com.skedgo.tripkit.data.tsp.RegionInfo; - -import java.util.List; - -import androidx.annotation.Nullable; - -import static org.immutables.gson.Gson.TypeAdapters; -import static org.immutables.value.Value.Immutable; -import static org.immutables.value.Value.Style; +import com.google.gson.annotations.JsonAdapter +import com.skedgo.tripkit.data.tsp.RegionInfo +import org.immutables.gson.Gson.TypeAdapters +import org.immutables.value.Value.Immutable +import org.immutables.value.Value.Style @TypeAdapters @Immutable -@Style(passAnnotations = JsonAdapter.class) -@JsonAdapter(GsonAdaptersRegionInfoResponse.class) -public interface RegionInfoResponse { - @Nullable - List regions(); +@Style(passAnnotations = [JsonAdapter::class]) +@JsonAdapter( + GsonAdaptersRegionInfoResponse::class +) +interface RegionInfoResponse { + fun regions(): List } \ No newline at end of file diff --git a/TripKitAndroid/src/main/java/com/skedgo/tripkit/tsp/RegionInfoService.kt b/TripKitAndroid/src/main/java/com/skedgo/tripkit/tsp/RegionInfoService.kt index dfeaf1ee..a5e4579e 100644 --- a/TripKitAndroid/src/main/java/com/skedgo/tripkit/tsp/RegionInfoService.kt +++ b/TripKitAndroid/src/main/java/com/skedgo/tripkit/tsp/RegionInfoService.kt @@ -1,58 +1,42 @@ -package com.skedgo.tripkit.tsp; +package com.skedgo.tripkit.tsp -import com.skedgo.tripkit.common.model.region.Region; -import com.skedgo.tripkit.data.tsp.RegionInfo; - -import java.util.List; - -import javax.inject.Inject; - -import dagger.Lazy; -import io.reactivex.Observable; -import io.reactivex.functions.Function; -import okhttp3.HttpUrl; - -import static org.apache.commons.collections4.CollectionUtils.isNotEmpty; +import com.skedgo.tripkit.data.tsp.RegionInfo +import dagger.Lazy +import io.reactivex.Observable +import okhttp3.HttpUrl +import okhttp3.HttpUrl.Companion.toHttpUrlOrNull +import org.apache.commons.collections4.CollectionUtils +import javax.inject.Inject /** - * A facade of {@link RegionInfoApi} that has failover on multiple servers. + * A facade of [RegionInfoApi] that has failover on multiple servers. */ -public class RegionInfoService { - private final Lazy regionInfoApiLazy; - - @Inject - public RegionInfoService(Lazy regionInfoApiLazy) { - this.regionInfoApiLazy = regionInfoApiLazy; - } +class RegionInfoService @Inject constructor( + private val regionInfoApiLazy: Lazy +) { /** * @param baseUrls Can be {@link Region#getURLs()}. * @param regionName Can be {@link Region#getName()}. */ - public Observable fetchRegionInfoAsync( - List baseUrls, - final String regionName) { + fun fetchRegionInfoAsync( + baseUrls: List, + regionName: String? + ): Observable { return Observable.fromIterable(baseUrls) - .concatMapDelayError(new Function>() { - @Override - public Observable apply(final String baseUrl) { - final String url = HttpUrl.parse(baseUrl).newBuilder() - .addPathSegment("regionInfo.json") - .build() - .toString(); - return regionInfoApiLazy.get().fetchRegionInfoAsync( - url, - ImmutableRegionInfoBody.of(regionName) - ).doOnError(Throwable::printStackTrace); - } - }) - .filter(regionInfoResponse -> isNotEmpty(regionInfoResponse.regions())) + .concatMapDelayError { baseUrl -> + val url = baseUrl.toHttpUrlOrNull()?.newBuilder() + ?.addPathSegment("regionInfo.json") + ?.build() + .toString() + regionInfoApiLazy.get().fetchRegionInfoAsync( + url, + ImmutableRegionInfoBody.of(regionName) + ).doOnError { it.printStackTrace() } + } + .filter { regionInfoResponse -> regionInfoResponse.regions().isNotEmpty() } .firstOrError() - .map(new Function() { - @Override - public RegionInfo apply(RegionInfoResponse response) { - return response.regions().get(0); - } - }).toObservable(); + .map { response -> response.regions()[0] } + .toObservable() } } \ No newline at end of file diff --git a/TripKitAndroid/src/main/java/com/skedgo/tripkit/tsp/TspModule.kt b/TripKitAndroid/src/main/java/com/skedgo/tripkit/tsp/TspModule.kt index 39380e3a..6a8f5c73 100644 --- a/TripKitAndroid/src/main/java/com/skedgo/tripkit/tsp/TspModule.kt +++ b/TripKitAndroid/src/main/java/com/skedgo/tripkit/tsp/TspModule.kt @@ -1,27 +1,28 @@ -package com.skedgo.tripkit.tsp; +package com.skedgo.tripkit.tsp -import com.google.gson.Gson; -import com.skedgo.tripkit.configuration.ServerManager; - -import dagger.Module; -import dagger.Provides; -import io.reactivex.schedulers.Schedulers; -import retrofit2.Retrofit; -import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory; -import retrofit2.converter.gson.GsonConverterFactory; +import com.google.gson.Gson +import com.skedgo.tripkit.configuration.ServerManager.configuration +import dagger.Module +import dagger.Provides +import io.reactivex.schedulers.Schedulers +import okhttp3.OkHttpClient +import retrofit2.Retrofit.Builder +import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory +import retrofit2.converter.gson.GsonConverterFactory @Module -public class TspModule { +class TspModule { @Provides - RegionInfoApi regionInfoApi( - Gson gson, - okhttp3.OkHttpClient httpClient) { - return new Retrofit.Builder() - .baseUrl(ServerManager.INSTANCE.getConfiguration().getApiTripGoUrl()) + fun regionInfoApi( + gson: Gson, + httpClient: OkHttpClient + ): RegionInfoApi { + return Builder() + .baseUrl(configuration.apiTripGoUrl) .client(httpClient) .addConverterFactory(GsonConverterFactory.create(gson)) .addCallAdapterFactory(RxJava2CallAdapterFactory.createWithScheduler(Schedulers.io())) .build() - .create(RegionInfoApi.class); + .create(RegionInfoApi::class.java) } } \ No newline at end of file From bf3f56ebd5a09f1c9173a7dc214b9a7f42437b5e Mon Sep 17 00:00:00 2001 From: Michael Angelo Reyes Date: Fri, 8 Nov 2024 00:35:56 +0800 Subject: [PATCH 11/25] Rename .java to .kt --- ...OverridingInterceptor.java => BaseUrlOverridingInterceptor.kt} | 0 .../com/skedgo/tripkit/{BookingAction.java => BookingAction.kt} | 0 .../src/main/java/com/skedgo/tripkit/{Cache.java => Cache.kt} | 0 .../src/main/java/com/skedgo/tripkit/{CarPark.java => CarPark.kt} | 0 .../com/skedgo/tripkit/{Co2Preferences.java => Co2Preferences.kt} | 0 .../{CursorToRegionConverter.java => CursorToRegionConverter.kt} | 0 ...nsportModeConverter.java => CursorToTransportModeConverter.kt} | 0 .../java/com/skedgo/tripkit/{DataLoader.java => DataLoader.kt} | 0 .../{DefaultCo2Preferences.java => DefaultCo2Preferences.kt} | 0 .../{ExternalActionParams.java => ExternalActionParams.kt} | 0 .../java/com/skedgo/tripkit/{LineSegment.java => LineSegment.kt} | 0 .../com/skedgo/tripkit/{LocationInfo.java => LocationInfo.kt} | 0 .../skedgo/tripkit/{LocationInfoApi.java => LocationInfoApi.kt} | 0 .../tripkit/{LocationInfoDetails.java => LocationInfoDetails.kt} | 0 .../tripkit/{LocationInfoService.java => LocationInfoService.kt} | 0 .../{LocationInfoServiceImpl.java => LocationInfoServiceImpl.kt} | 0 .../java/com/skedgo/tripkit/{MainModule.java => MainModule.kt} | 0 .../{RegionDatabaseHelper.java => RegionDatabaseHelper.kt} | 0 .../com/skedgo/tripkit/{RegionFinder.java => RegionFinder.kt} | 0 .../java/com/skedgo/tripkit/{RegionsApi.java => RegionsApi.kt} | 0 .../java/com/skedgo/tripkit/{ServiceApi.java => ServiceApi.kt} | 0 21 files changed, 0 insertions(+), 0 deletions(-) rename TripKitAndroid/src/main/java/com/skedgo/tripkit/{BaseUrlOverridingInterceptor.java => BaseUrlOverridingInterceptor.kt} (100%) rename TripKitAndroid/src/main/java/com/skedgo/tripkit/{BookingAction.java => BookingAction.kt} (100%) rename TripKitAndroid/src/main/java/com/skedgo/tripkit/{Cache.java => Cache.kt} (100%) rename TripKitAndroid/src/main/java/com/skedgo/tripkit/{CarPark.java => CarPark.kt} (100%) rename TripKitAndroid/src/main/java/com/skedgo/tripkit/{Co2Preferences.java => Co2Preferences.kt} (100%) rename TripKitAndroid/src/main/java/com/skedgo/tripkit/{CursorToRegionConverter.java => CursorToRegionConverter.kt} (100%) rename TripKitAndroid/src/main/java/com/skedgo/tripkit/{CursorToTransportModeConverter.java => CursorToTransportModeConverter.kt} (100%) rename TripKitAndroid/src/main/java/com/skedgo/tripkit/{DataLoader.java => DataLoader.kt} (100%) rename TripKitAndroid/src/main/java/com/skedgo/tripkit/{DefaultCo2Preferences.java => DefaultCo2Preferences.kt} (100%) rename TripKitAndroid/src/main/java/com/skedgo/tripkit/{ExternalActionParams.java => ExternalActionParams.kt} (100%) rename TripKitAndroid/src/main/java/com/skedgo/tripkit/{LineSegment.java => LineSegment.kt} (100%) rename TripKitAndroid/src/main/java/com/skedgo/tripkit/{LocationInfo.java => LocationInfo.kt} (100%) rename TripKitAndroid/src/main/java/com/skedgo/tripkit/{LocationInfoApi.java => LocationInfoApi.kt} (100%) rename TripKitAndroid/src/main/java/com/skedgo/tripkit/{LocationInfoDetails.java => LocationInfoDetails.kt} (100%) rename TripKitAndroid/src/main/java/com/skedgo/tripkit/{LocationInfoService.java => LocationInfoService.kt} (100%) rename TripKitAndroid/src/main/java/com/skedgo/tripkit/{LocationInfoServiceImpl.java => LocationInfoServiceImpl.kt} (100%) rename TripKitAndroid/src/main/java/com/skedgo/tripkit/{MainModule.java => MainModule.kt} (100%) rename TripKitAndroid/src/main/java/com/skedgo/tripkit/{RegionDatabaseHelper.java => RegionDatabaseHelper.kt} (100%) rename TripKitAndroid/src/main/java/com/skedgo/tripkit/{RegionFinder.java => RegionFinder.kt} (100%) rename TripKitAndroid/src/main/java/com/skedgo/tripkit/{RegionsApi.java => RegionsApi.kt} (100%) rename TripKitAndroid/src/main/java/com/skedgo/tripkit/{ServiceApi.java => ServiceApi.kt} (100%) diff --git a/TripKitAndroid/src/main/java/com/skedgo/tripkit/BaseUrlOverridingInterceptor.java b/TripKitAndroid/src/main/java/com/skedgo/tripkit/BaseUrlOverridingInterceptor.kt similarity index 100% rename from TripKitAndroid/src/main/java/com/skedgo/tripkit/BaseUrlOverridingInterceptor.java rename to TripKitAndroid/src/main/java/com/skedgo/tripkit/BaseUrlOverridingInterceptor.kt diff --git a/TripKitAndroid/src/main/java/com/skedgo/tripkit/BookingAction.java b/TripKitAndroid/src/main/java/com/skedgo/tripkit/BookingAction.kt similarity index 100% rename from TripKitAndroid/src/main/java/com/skedgo/tripkit/BookingAction.java rename to TripKitAndroid/src/main/java/com/skedgo/tripkit/BookingAction.kt diff --git a/TripKitAndroid/src/main/java/com/skedgo/tripkit/Cache.java b/TripKitAndroid/src/main/java/com/skedgo/tripkit/Cache.kt similarity index 100% rename from TripKitAndroid/src/main/java/com/skedgo/tripkit/Cache.java rename to TripKitAndroid/src/main/java/com/skedgo/tripkit/Cache.kt diff --git a/TripKitAndroid/src/main/java/com/skedgo/tripkit/CarPark.java b/TripKitAndroid/src/main/java/com/skedgo/tripkit/CarPark.kt similarity index 100% rename from TripKitAndroid/src/main/java/com/skedgo/tripkit/CarPark.java rename to TripKitAndroid/src/main/java/com/skedgo/tripkit/CarPark.kt diff --git a/TripKitAndroid/src/main/java/com/skedgo/tripkit/Co2Preferences.java b/TripKitAndroid/src/main/java/com/skedgo/tripkit/Co2Preferences.kt similarity index 100% rename from TripKitAndroid/src/main/java/com/skedgo/tripkit/Co2Preferences.java rename to TripKitAndroid/src/main/java/com/skedgo/tripkit/Co2Preferences.kt diff --git a/TripKitAndroid/src/main/java/com/skedgo/tripkit/CursorToRegionConverter.java b/TripKitAndroid/src/main/java/com/skedgo/tripkit/CursorToRegionConverter.kt similarity index 100% rename from TripKitAndroid/src/main/java/com/skedgo/tripkit/CursorToRegionConverter.java rename to TripKitAndroid/src/main/java/com/skedgo/tripkit/CursorToRegionConverter.kt diff --git a/TripKitAndroid/src/main/java/com/skedgo/tripkit/CursorToTransportModeConverter.java b/TripKitAndroid/src/main/java/com/skedgo/tripkit/CursorToTransportModeConverter.kt similarity index 100% rename from TripKitAndroid/src/main/java/com/skedgo/tripkit/CursorToTransportModeConverter.java rename to TripKitAndroid/src/main/java/com/skedgo/tripkit/CursorToTransportModeConverter.kt diff --git a/TripKitAndroid/src/main/java/com/skedgo/tripkit/DataLoader.java b/TripKitAndroid/src/main/java/com/skedgo/tripkit/DataLoader.kt similarity index 100% rename from TripKitAndroid/src/main/java/com/skedgo/tripkit/DataLoader.java rename to TripKitAndroid/src/main/java/com/skedgo/tripkit/DataLoader.kt diff --git a/TripKitAndroid/src/main/java/com/skedgo/tripkit/DefaultCo2Preferences.java b/TripKitAndroid/src/main/java/com/skedgo/tripkit/DefaultCo2Preferences.kt similarity index 100% rename from TripKitAndroid/src/main/java/com/skedgo/tripkit/DefaultCo2Preferences.java rename to TripKitAndroid/src/main/java/com/skedgo/tripkit/DefaultCo2Preferences.kt diff --git a/TripKitAndroid/src/main/java/com/skedgo/tripkit/ExternalActionParams.java b/TripKitAndroid/src/main/java/com/skedgo/tripkit/ExternalActionParams.kt similarity index 100% rename from TripKitAndroid/src/main/java/com/skedgo/tripkit/ExternalActionParams.java rename to TripKitAndroid/src/main/java/com/skedgo/tripkit/ExternalActionParams.kt diff --git a/TripKitAndroid/src/main/java/com/skedgo/tripkit/LineSegment.java b/TripKitAndroid/src/main/java/com/skedgo/tripkit/LineSegment.kt similarity index 100% rename from TripKitAndroid/src/main/java/com/skedgo/tripkit/LineSegment.java rename to TripKitAndroid/src/main/java/com/skedgo/tripkit/LineSegment.kt diff --git a/TripKitAndroid/src/main/java/com/skedgo/tripkit/LocationInfo.java b/TripKitAndroid/src/main/java/com/skedgo/tripkit/LocationInfo.kt similarity index 100% rename from TripKitAndroid/src/main/java/com/skedgo/tripkit/LocationInfo.java rename to TripKitAndroid/src/main/java/com/skedgo/tripkit/LocationInfo.kt diff --git a/TripKitAndroid/src/main/java/com/skedgo/tripkit/LocationInfoApi.java b/TripKitAndroid/src/main/java/com/skedgo/tripkit/LocationInfoApi.kt similarity index 100% rename from TripKitAndroid/src/main/java/com/skedgo/tripkit/LocationInfoApi.java rename to TripKitAndroid/src/main/java/com/skedgo/tripkit/LocationInfoApi.kt diff --git a/TripKitAndroid/src/main/java/com/skedgo/tripkit/LocationInfoDetails.java b/TripKitAndroid/src/main/java/com/skedgo/tripkit/LocationInfoDetails.kt similarity index 100% rename from TripKitAndroid/src/main/java/com/skedgo/tripkit/LocationInfoDetails.java rename to TripKitAndroid/src/main/java/com/skedgo/tripkit/LocationInfoDetails.kt diff --git a/TripKitAndroid/src/main/java/com/skedgo/tripkit/LocationInfoService.java b/TripKitAndroid/src/main/java/com/skedgo/tripkit/LocationInfoService.kt similarity index 100% rename from TripKitAndroid/src/main/java/com/skedgo/tripkit/LocationInfoService.java rename to TripKitAndroid/src/main/java/com/skedgo/tripkit/LocationInfoService.kt diff --git a/TripKitAndroid/src/main/java/com/skedgo/tripkit/LocationInfoServiceImpl.java b/TripKitAndroid/src/main/java/com/skedgo/tripkit/LocationInfoServiceImpl.kt similarity index 100% rename from TripKitAndroid/src/main/java/com/skedgo/tripkit/LocationInfoServiceImpl.java rename to TripKitAndroid/src/main/java/com/skedgo/tripkit/LocationInfoServiceImpl.kt diff --git a/TripKitAndroid/src/main/java/com/skedgo/tripkit/MainModule.java b/TripKitAndroid/src/main/java/com/skedgo/tripkit/MainModule.kt similarity index 100% rename from TripKitAndroid/src/main/java/com/skedgo/tripkit/MainModule.java rename to TripKitAndroid/src/main/java/com/skedgo/tripkit/MainModule.kt diff --git a/TripKitAndroid/src/main/java/com/skedgo/tripkit/RegionDatabaseHelper.java b/TripKitAndroid/src/main/java/com/skedgo/tripkit/RegionDatabaseHelper.kt similarity index 100% rename from TripKitAndroid/src/main/java/com/skedgo/tripkit/RegionDatabaseHelper.java rename to TripKitAndroid/src/main/java/com/skedgo/tripkit/RegionDatabaseHelper.kt diff --git a/TripKitAndroid/src/main/java/com/skedgo/tripkit/RegionFinder.java b/TripKitAndroid/src/main/java/com/skedgo/tripkit/RegionFinder.kt similarity index 100% rename from TripKitAndroid/src/main/java/com/skedgo/tripkit/RegionFinder.java rename to TripKitAndroid/src/main/java/com/skedgo/tripkit/RegionFinder.kt diff --git a/TripKitAndroid/src/main/java/com/skedgo/tripkit/RegionsApi.java b/TripKitAndroid/src/main/java/com/skedgo/tripkit/RegionsApi.kt similarity index 100% rename from TripKitAndroid/src/main/java/com/skedgo/tripkit/RegionsApi.java rename to TripKitAndroid/src/main/java/com/skedgo/tripkit/RegionsApi.kt diff --git a/TripKitAndroid/src/main/java/com/skedgo/tripkit/ServiceApi.java b/TripKitAndroid/src/main/java/com/skedgo/tripkit/ServiceApi.kt similarity index 100% rename from TripKitAndroid/src/main/java/com/skedgo/tripkit/ServiceApi.java rename to TripKitAndroid/src/main/java/com/skedgo/tripkit/ServiceApi.kt From 183d0ec976dd80be7e67f0d93199d550ad351b4c Mon Sep 17 00:00:00 2001 From: Michael Angelo Reyes Date: Fri, 8 Nov 2024 00:35:56 +0800 Subject: [PATCH 12/25] [22682] - [TripKit] convert BaseUrlOverridingInterceptor.java to kotlin - [TripKit] convert BookingAction.java to kotlin - [TripKit] convert Cache.java to kotlin - [TripKit] convert CarPark.java to kotlin - [TripKit] convert Co2Preferences.java to kotlin - [TripKit] convert CursorToRegionConverter.java to kotlin - [TripKit] convert CursorToTransportModeConverter.java to kotlin - [TripKit] convert DataLoader.java to kotlin - [TripKit] convert DefaultCo2Preferences.java to kotlin - [TripKit] convert ExternalActionParams.java to kotlin - [TripKit] convert LineSegment.java to kotlin - [TripKit] convert LocationInfo.java to kotlin - [TripKit] convert LocationInfoApi.java to kotlin - [TripKit] convert LocationInfoDetails.java to kotlin - [TripKit] convert LocationInfoService.java to kotlin - [TripKit] convert LocationInfoServiceImpl.java to kotlin - [TripKit] convert MainModule.java to kotlin - [TripKit] convert RegionDatabaseHelper.java to kotlin - [TripKit] convert RegionFinder.java to kotlin - [TripKit] convert RegionsApi.java to kotlin - [TripKit] convert ServiceApi.java to kotlin --- .../tripkit/BaseUrlOverridingInterceptor.kt | 75 +++--- .../java/com/skedgo/tripkit/BookingAction.kt | 52 ++-- .../src/main/java/com/skedgo/tripkit/Cache.kt | 10 +- .../main/java/com/skedgo/tripkit/CarPark.kt | 29 ++- .../java/com/skedgo/tripkit/Co2Preferences.kt | 13 +- .../skedgo/tripkit/CursorToRegionConverter.kt | 23 +- .../tripkit/CursorToTransportModeConverter.kt | 23 +- .../java/com/skedgo/tripkit/DataLoader.kt | 43 ++-- .../skedgo/tripkit/DefaultCo2Preferences.kt | 44 ++-- .../skedgo/tripkit/ExternalActionParams.kt | 46 ++-- .../java/com/skedgo/tripkit/LineSegment.kt | 28 +- .../java/com/skedgo/tripkit/LocationInfo.kt | 39 ++- .../com/skedgo/tripkit/LocationInfoApi.kt | 20 +- .../com/skedgo/tripkit/LocationInfoDetails.kt | 30 +-- .../com/skedgo/tripkit/LocationInfoService.kt | 11 +- .../skedgo/tripkit/LocationInfoServiceImpl.kt | 56 ++-- .../java/com/skedgo/tripkit/MainModule.kt | 242 ++++++++---------- .../skedgo/tripkit/RegionDatabaseHelper.kt | 72 +++--- .../java/com/skedgo/tripkit/RegionFinder.kt | 42 +-- .../com/skedgo/tripkit/RegionServiceImpl.kt | 4 +- .../java/com/skedgo/tripkit/RegionsApi.kt | 34 +-- .../com/skedgo/tripkit/RouteServiceImpl.kt | 2 +- .../java/com/skedgo/tripkit/ServiceApi.kt | 28 +- 23 files changed, 428 insertions(+), 538 deletions(-) diff --git a/TripKitAndroid/src/main/java/com/skedgo/tripkit/BaseUrlOverridingInterceptor.kt b/TripKitAndroid/src/main/java/com/skedgo/tripkit/BaseUrlOverridingInterceptor.kt index 248cc207..0a0ebd89 100644 --- a/TripKitAndroid/src/main/java/com/skedgo/tripkit/BaseUrlOverridingInterceptor.kt +++ b/TripKitAndroid/src/main/java/com/skedgo/tripkit/BaseUrlOverridingInterceptor.kt @@ -1,55 +1,46 @@ -package com.skedgo.tripkit; +package com.skedgo.tripkit -import android.text.TextUtils; +import okhttp3.HttpUrl.Companion.toHttpUrlOrNull +import okhttp3.Interceptor +import okhttp3.Response +import java.util.concurrent.Callable -import java.io.IOException; -import java.util.List; -import java.util.concurrent.Callable; +class BaseUrlOverridingInterceptor( + private val baseUrlAdapter: Callable +) : Interceptor { -import androidx.annotation.NonNull; -import okhttp3.HttpUrl; -import okhttp3.Interceptor; -import okhttp3.Request; -import okhttp3.Response; - -public final class BaseUrlOverridingInterceptor implements Interceptor { - private final Callable baseUrlAdapter; - - public BaseUrlOverridingInterceptor(@NonNull Callable baseUrlAdapter) { - this.baseUrlAdapter = baseUrlAdapter; - } - - @Override - public Response intercept(Chain chain) throws IOException { - - String newBaseUrl = ""; + override fun intercept(chain: Interceptor.Chain): Response { + var newBaseUrl = "" try { - newBaseUrl = baseUrlAdapter.call(); - } catch (Exception e) { - e.printStackTrace(); + newBaseUrl = baseUrlAdapter.call() + } catch (e: Exception) { + e.printStackTrace() } - final Request request = chain.request(); - final HttpUrl requestUrl = request.url(); - final List pathSegments = requestUrl.pathSegments(); - boolean isFromSkedGo = pathSegments.get(0).equals("satapp") || requestUrl.host().contains("skedgo.com") || requestUrl.host().contains("buzzhives.com") - || requestUrl.host().contains("tripgo.com"); - if (!TextUtils.isEmpty(newBaseUrl) && isFromSkedGo && !requestUrl.host().contains("payments.tripgo.com")) { - HttpUrl tempUrl = requestUrl.newBuilder().removePathSegment(0).build(); - if (requestUrl.host().equals("galaxies.skedgo.com")) { - tempUrl = tempUrl.newBuilder().removePathSegment(0).removePathSegment(0).build(); + + val request = chain.request() + val requestUrl = request.url + val pathSegments = requestUrl.pathSegments + val isFromSkedGo = pathSegments[0] == "satapp" || + requestUrl.host.contains("skedgo.com") || + requestUrl.host.contains("buzzhives.com") || + requestUrl.host.contains("tripgo.com") + + return if (newBaseUrl.isNotEmpty() && isFromSkedGo && !requestUrl.host.contains("payments.tripgo.com")) { + var tempUrl = requestUrl.newBuilder().removePathSegment(0).build() + if (requestUrl.host == "galaxies.skedgo.com") { + tempUrl = tempUrl.newBuilder().removePathSegment(0).removePathSegment(0).build() } - final String query = tempUrl.query(); - final String encodedPath = TextUtils.join("/", tempUrl.encodedPathSegments()); - final HttpUrl newUrl = HttpUrl.parse(newBaseUrl) + val query = tempUrl.query + val encodedPath = tempUrl.encodedPathSegments.joinToString("/") + val newUrl = newBaseUrl.toHttpUrlOrNull()!! .newBuilder() .addEncodedPathSegments(encodedPath) .query(query) - .build(); - final Request newRequest = request.newBuilder().url(newUrl).build(); - return chain.proceed(newRequest); + .build() + val newRequest = request.newBuilder().url(newUrl).build() + chain.proceed(newRequest) } else { - return chain.proceed(request); - + chain.proceed(request) } } } \ No newline at end of file diff --git a/TripKitAndroid/src/main/java/com/skedgo/tripkit/BookingAction.kt b/TripKitAndroid/src/main/java/com/skedgo/tripkit/BookingAction.kt index b4575476..6d72f3e5 100644 --- a/TripKitAndroid/src/main/java/com/skedgo/tripkit/BookingAction.kt +++ b/TripKitAndroid/src/main/java/com/skedgo/tripkit/BookingAction.kt @@ -1,35 +1,35 @@ -package com.skedgo.tripkit; - -import android.content.Intent; - -import com.skedgo.tripkit.bookingproviders.BookingProvider; - -import org.immutables.value.Value; - -import static org.immutables.value.Value.Style.BuilderVisibility.PACKAGE; -import static org.immutables.value.Value.Style.ImplementationVisibility.PRIVATE; - -@Value.Immutable -@Value.Style(visibility = PRIVATE, builderVisibility = PACKAGE) -public abstract class BookingAction { - public static Builder builder() { - return new BookingActionBuilder(); - } - +package com.skedgo.tripkit + +import android.content.Intent +import com.skedgo.tripkit.bookingproviders.BookingProvider +import org.immutables.value.Value.Immutable +import org.immutables.value.Value.Style +import org.immutables.value.Value.Style.BuilderVisibility.PACKAGE +import org.immutables.value.Value.Style.ImplementationVisibility.PRIVATE + +@Immutable +@Style(visibility = PRIVATE, builderVisibility = PACKAGE) +abstract class BookingAction { @BookingProvider - public abstract int bookingProvider(); + abstract fun bookingProvider(): Int - public abstract boolean hasApp(); + abstract fun hasApp(): Boolean - public abstract Intent data(); + abstract fun data(): Intent - public interface Builder { - Builder bookingProvider(@BookingProvider int bookingProvider); + interface Builder { + fun bookingProvider(@BookingProvider bookingProvider: Int): Builder - Builder hasApp(boolean hasApp); + fun hasApp(hasApp: Boolean): Builder - Builder data(Intent data); + fun data(data: Intent?): Builder + + fun build(): BookingAction + } - BookingAction build(); + companion object { + fun builder(): Builder { + return BookingActionBuilder() + } } } \ No newline at end of file diff --git a/TripKitAndroid/src/main/java/com/skedgo/tripkit/Cache.kt b/TripKitAndroid/src/main/java/com/skedgo/tripkit/Cache.kt index 98e23f3b..ca5228d8 100644 --- a/TripKitAndroid/src/main/java/com/skedgo/tripkit/Cache.kt +++ b/TripKitAndroid/src/main/java/com/skedgo/tripkit/Cache.kt @@ -1,9 +1,9 @@ -package com.skedgo.tripkit; +package com.skedgo.tripkit -import io.reactivex.Single; +import io.reactivex.Single -interface Cache { - Single getAsync(); +internal interface Cache { + fun getAsync(): Single - void invalidate(); + fun invalidate() } \ No newline at end of file diff --git a/TripKitAndroid/src/main/java/com/skedgo/tripkit/CarPark.kt b/TripKitAndroid/src/main/java/com/skedgo/tripkit/CarPark.kt index e7fbc8b3..7c2dbc05 100644 --- a/TripKitAndroid/src/main/java/com/skedgo/tripkit/CarPark.kt +++ b/TripKitAndroid/src/main/java/com/skedgo/tripkit/CarPark.kt @@ -1,23 +1,24 @@ -package com.skedgo.tripkit; +package com.skedgo.tripkit -import com.google.gson.annotations.JsonAdapter; - -import static org.immutables.gson.Gson.TypeAdapters; -import static org.immutables.value.Value.Immutable; -import static org.immutables.value.Value.Style; +import com.google.gson.annotations.JsonAdapter +import org.immutables.gson.Gson.TypeAdapters +import org.immutables.value.Value.Immutable +import org.immutables.value.Value.Style @TypeAdapters @Immutable -@Style(passAnnotations = JsonAdapter.class) -@JsonAdapter(GsonAdaptersCarPark.class) -public abstract class CarPark { - public abstract String identifier(); +@Style(passAnnotations = [JsonAdapter::class]) +@JsonAdapter( + GsonAdaptersCarPark::class +) +abstract class CarPark { + abstract fun identifier(): String - public abstract String name(); + abstract fun name(): String - public abstract int totalSpaces(); + abstract fun totalSpaces(): Int - public abstract int availableSpaces(); + abstract fun availableSpaces(): Int - public abstract long lastUpdate(); + abstract fun lastUpdate(): Long } \ No newline at end of file diff --git a/TripKitAndroid/src/main/java/com/skedgo/tripkit/Co2Preferences.kt b/TripKitAndroid/src/main/java/com/skedgo/tripkit/Co2Preferences.kt index 6b748289..eb345093 100644 --- a/TripKitAndroid/src/main/java/com/skedgo/tripkit/Co2Preferences.kt +++ b/TripKitAndroid/src/main/java/com/skedgo/tripkit/Co2Preferences.kt @@ -1,21 +1,16 @@ -package com.skedgo.tripkit; +package com.skedgo.tripkit -import java.util.Map; - -import androidx.annotation.NonNull; - -public interface Co2Preferences { +interface Co2Preferences { /** * @return An immutable map having key as mode identifier for * which to apply emissions, and its value is emissions for * the supplied mode identifier in grams of CO2 per kilometre. */ - @NonNull - Map getCo2Profile(); + fun getCo2Profile(): Map /** * @param modeId Mode identifier for which to apply these emissions. * @param gramsCO2PerKm Emissions for supplied mode identifier in grams of CO2 per kilometre. */ - void setEmissions(@NonNull String modeId, float gramsCO2PerKm); + fun setEmissions(modeId: String, gramsCO2PerKm: Float) } \ No newline at end of file diff --git a/TripKitAndroid/src/main/java/com/skedgo/tripkit/CursorToRegionConverter.kt b/TripKitAndroid/src/main/java/com/skedgo/tripkit/CursorToRegionConverter.kt index 6f784361..fe46c9b2 100644 --- a/TripKitAndroid/src/main/java/com/skedgo/tripkit/CursorToRegionConverter.kt +++ b/TripKitAndroid/src/main/java/com/skedgo/tripkit/CursorToRegionConverter.kt @@ -1,18 +1,15 @@ -package com.skedgo.tripkit; +package com.skedgo.tripkit -import android.database.Cursor; +import android.database.Cursor +import com.google.gson.Gson +import com.skedgo.tripkit.common.model.region.Region +import io.reactivex.functions.Function -import com.google.gson.Gson; -import com.skedgo.tripkit.common.model.region.Region; +internal class CursorToRegionConverter : Function { + private val gson = Gson() -import io.reactivex.functions.Function; - -final class CursorToRegionConverter implements Function { - private final Gson gson = new Gson(); - - @Override - public Region apply(Cursor cursor) { - final String json = cursor.getString(cursor.getColumnIndex(Tables.FIELD_JSON.name)); - return gson.fromJson(json, Region.class); + override fun apply(cursor: Cursor): Region { + val json = cursor.getString(cursor.getColumnIndex(Tables.FIELD_JSON.name)) + return gson.fromJson(json, Region::class.java) } } \ No newline at end of file diff --git a/TripKitAndroid/src/main/java/com/skedgo/tripkit/CursorToTransportModeConverter.kt b/TripKitAndroid/src/main/java/com/skedgo/tripkit/CursorToTransportModeConverter.kt index 3c0ed10c..2e12d3ab 100644 --- a/TripKitAndroid/src/main/java/com/skedgo/tripkit/CursorToTransportModeConverter.kt +++ b/TripKitAndroid/src/main/java/com/skedgo/tripkit/CursorToTransportModeConverter.kt @@ -1,18 +1,15 @@ -package com.skedgo.tripkit; +package com.skedgo.tripkit -import android.database.Cursor; +import android.database.Cursor +import com.google.gson.Gson +import com.skedgo.tripkit.common.model.TransportMode +import io.reactivex.functions.Function -import com.google.gson.Gson; -import com.skedgo.tripkit.common.model.TransportMode; +internal class CursorToTransportModeConverter : Function { + private val gson = Gson() -import io.reactivex.functions.Function; - -final class CursorToTransportModeConverter implements Function { - private final Gson gson = new Gson(); - - @Override - public TransportMode apply(Cursor cursor) { - final String json = cursor.getString(cursor.getColumnIndex(Tables.FIELD_JSON.name)); - return gson.fromJson(json, TransportMode.class); + override fun apply(cursor: Cursor): TransportMode { + val json = cursor.getString(cursor.getColumnIndex(Tables.FIELD_JSON.name)) + return gson.fromJson(json, TransportMode::class.java) } } \ No newline at end of file diff --git a/TripKitAndroid/src/main/java/com/skedgo/tripkit/DataLoader.kt b/TripKitAndroid/src/main/java/com/skedgo/tripkit/DataLoader.kt index 19356868..f6ddef54 100644 --- a/TripKitAndroid/src/main/java/com/skedgo/tripkit/DataLoader.kt +++ b/TripKitAndroid/src/main/java/com/skedgo/tripkit/DataLoader.kt @@ -1,34 +1,27 @@ -package com.skedgo.tripkit; +package com.skedgo.tripkit -import java.util.concurrent.Callable; -import java.util.concurrent.atomic.AtomicReference; +import io.reactivex.Observable +import io.reactivex.schedulers.Schedulers +import java.util.concurrent.Callable +import java.util.concurrent.atomic.AtomicReference -import io.reactivex.Observable; -import io.reactivex.functions.Consumer; -import io.reactivex.schedulers.Schedulers; +abstract class DataLoader : Callable> { + private val memoryCache = AtomicReference() - -abstract class DataLoader implements Callable> { - private final AtomicReference memoryCache = new AtomicReference<>(); - - @Override - public synchronized Observable call() { - final Observable fromMemory = (memoryCache.get() == null) ? Observable.empty() : Observable.just(memoryCache.get()); - final Observable fromDisk = getDataAsync().subscribeOn(Schedulers.io()); + @Synchronized + override fun call(): Observable { + val fromMemory = memoryCache.get().let { Observable.just(it) } ?: Observable.empty() + val fromDisk = getDataAsync().subscribeOn(Schedulers.io()) return Observable.concat(fromMemory, fromDisk) - .filter(data -> data != null) - .firstOrError().toObservable() - .doOnNext(new Consumer() { - @Override - public void accept(TData data) { - memoryCache.set(data); - } - }); + .filter { it != null } + .firstOrError() + .toObservable() + .doOnNext { data -> memoryCache.set(data) } } - public void invalidate() { - memoryCache.set(null); + fun invalidate() { + memoryCache.set(null) } - protected abstract Observable getDataAsync(); + protected abstract fun getDataAsync(): Observable } \ No newline at end of file diff --git a/TripKitAndroid/src/main/java/com/skedgo/tripkit/DefaultCo2Preferences.kt b/TripKitAndroid/src/main/java/com/skedgo/tripkit/DefaultCo2Preferences.kt index 0b86831a..3d55c203 100644 --- a/TripKitAndroid/src/main/java/com/skedgo/tripkit/DefaultCo2Preferences.kt +++ b/TripKitAndroid/src/main/java/com/skedgo/tripkit/DefaultCo2Preferences.kt @@ -1,35 +1,23 @@ -package com.skedgo.tripkit; +package com.skedgo.tripkit -import android.content.SharedPreferences; +import android.content.SharedPreferences +import androidx.collection.ArrayMap +import java.util.Collections -import java.util.Collections; -import java.util.Map; - -import androidx.annotation.NonNull; -import androidx.collection.ArrayMap; - -public final class DefaultCo2Preferences implements Co2Preferences { - private final SharedPreferences preferences; - - /** - * @param preferences This {@link SharedPreferences} should only be used to store CO2 profile. - */ - public DefaultCo2Preferences(@NonNull SharedPreferences preferences) { - this.preferences = preferences; - } - - @NonNull - @Override - public Map getCo2Profile() { - final Map all = preferences.getAll(); - final Map co2Profile = new ArrayMap<>(all.size()); - for (Map.Entry entry : all.entrySet()) { - co2Profile.put(entry.getKey(), (Float) entry.getValue()); +class DefaultCo2Preferences +/** + * @param preferences This [SharedPreferences] should only be used to store CO2 profile. + */(private val preferences: SharedPreferences) : Co2Preferences { + override fun getCo2Profile(): Map { + val all = preferences.all + val co2Profile: MutableMap = ArrayMap(all.size) + for ((key, value) in all) { + co2Profile[key] = value as Float } - return Collections.unmodifiableMap(co2Profile); + return Collections.unmodifiableMap(co2Profile) } - public void setEmissions(@NonNull String modeId, float gramsCO2PerKm) { - preferences.edit().putFloat(modeId, gramsCO2PerKm).apply(); + override fun setEmissions(modeId: String, gramsCO2PerKm: Float) { + preferences.edit().putFloat(modeId, gramsCO2PerKm).apply() } } \ No newline at end of file diff --git a/TripKitAndroid/src/main/java/com/skedgo/tripkit/ExternalActionParams.kt b/TripKitAndroid/src/main/java/com/skedgo/tripkit/ExternalActionParams.kt index 74c66e75..0a2ab616 100644 --- a/TripKitAndroid/src/main/java/com/skedgo/tripkit/ExternalActionParams.kt +++ b/TripKitAndroid/src/main/java/com/skedgo/tripkit/ExternalActionParams.kt @@ -1,35 +1,33 @@ -package com.skedgo.tripkit; +package com.skedgo.tripkit -import com.skedgo.tripkit.routing.TripSegment; +import com.skedgo.tripkit.routing.TripSegment +import org.immutables.value.Value.Immutable +import org.immutables.value.Value.Style +import org.immutables.value.Value.Style.BuilderVisibility.PACKAGE +import org.immutables.value.Value.Style.ImplementationVisibility.PRIVATE -import org.immutables.value.Value; +@Immutable +@Style(visibility = PRIVATE, builderVisibility = PACKAGE) +abstract class ExternalActionParams { + abstract fun action(): String -import androidx.annotation.Nullable; + abstract fun segment(): TripSegment -import static org.immutables.value.Value.Style.BuilderVisibility.PACKAGE; -import static org.immutables.value.Value.Style.ImplementationVisibility.PRIVATE; + abstract fun flitWaysPartnerKey(): String? -@Value.Immutable -@Value.Style(visibility = PRIVATE, builderVisibility = PACKAGE) -public abstract class ExternalActionParams { - public static Builder builder() { - return new ExternalActionParamsBuilder(); - } - - public abstract String action(); - - public abstract TripSegment segment(); + interface Builder { + fun action(action: String): Builder - @Nullable - public abstract String flitWaysPartnerKey(); + fun segment(segment: TripSegment?): Builder - public interface Builder { - Builder action(String action); + fun flitWaysPartnerKey(flitWaysPartnerKey: String): Builder - Builder segment(TripSegment segment); - - Builder flitWaysPartnerKey(String flitWaysPartnerKey); + fun build(): ExternalActionParams + } - ExternalActionParams build(); + companion object { + fun builder(): Builder { + return ExternalActionParamsBuilder() + } } } \ No newline at end of file diff --git a/TripKitAndroid/src/main/java/com/skedgo/tripkit/LineSegment.kt b/TripKitAndroid/src/main/java/com/skedgo/tripkit/LineSegment.kt index 8605fee8..83401701 100644 --- a/TripKitAndroid/src/main/java/com/skedgo/tripkit/LineSegment.kt +++ b/TripKitAndroid/src/main/java/com/skedgo/tripkit/LineSegment.kt @@ -1,25 +1,17 @@ -package com.skedgo.tripkit; +package com.skedgo.tripkit -import com.skedgo.tripkit.common.util.TripKitLatLng; -import com.skedgo.tripkit.routing.Trip; +import com.skedgo.tripkit.common.util.TripKitLatLng /** - * Represents a segment of a polyline denoting a {@link Trip}. + * Represents a segment of a polyline denoting a [Trip]. */ -public final class LineSegment { - public final TripKitLatLng start; - public final TripKitLatLng end; - public final int color; - public final String tag; - - public LineSegment(TripKitLatLng start, TripKitLatLng end, int color, String tag) { - this.start = start; - this.end = end; - this.color = color; - this.tag = tag; - } - - public enum Tag { +class LineSegment( + val start: TripKitLatLng, + val end: TripKitLatLng, + val color: Int, + val tag: String +) { + enum class Tag { SHAPE, STREET } diff --git a/TripKitAndroid/src/main/java/com/skedgo/tripkit/LocationInfo.kt b/TripKitAndroid/src/main/java/com/skedgo/tripkit/LocationInfo.kt index c5afd394..72df6014 100644 --- a/TripKitAndroid/src/main/java/com/skedgo/tripkit/LocationInfo.kt +++ b/TripKitAndroid/src/main/java/com/skedgo/tripkit/LocationInfo.kt @@ -1,28 +1,25 @@ -package com.skedgo.tripkit; +package com.skedgo.tripkit -import com.google.gson.annotations.JsonAdapter; -import com.skedgo.tripkit.common.model.stop.ScheduledStop; +import com.google.gson.annotations.JsonAdapter +import com.skedgo.tripkit.common.model.stop.ScheduledStop +import org.immutables.gson.Gson.TypeAdapters +import org.immutables.value.Value.Immutable +import org.immutables.value.Value.Style -import org.immutables.gson.Gson; -import org.immutables.value.Value; +@TypeAdapters +@Immutable +@Style(passAnnotations = [JsonAdapter::class]) +@JsonAdapter( + GsonAdaptersLocationInfo::class +) +interface LocationInfo { + fun details(): LocationInfoDetails? -import androidx.annotation.Nullable; + fun stop(): ScheduledStop? -@Gson.TypeAdapters -@Value.Immutable -@Value.Style(passAnnotations = JsonAdapter.class) -@JsonAdapter(GsonAdaptersLocationInfo.class) -public interface LocationInfo { - @Nullable - LocationInfoDetails details(); + fun carPark(): CarPark? - @Nullable - ScheduledStop stop(); + fun lat(): Double - @Nullable - CarPark carPark(); - - double lat(); - - double lng(); + fun lng(): Double } \ No newline at end of file diff --git a/TripKitAndroid/src/main/java/com/skedgo/tripkit/LocationInfoApi.kt b/TripKitAndroid/src/main/java/com/skedgo/tripkit/LocationInfoApi.kt index 486f8761..2698d976 100644 --- a/TripKitAndroid/src/main/java/com/skedgo/tripkit/LocationInfoApi.kt +++ b/TripKitAndroid/src/main/java/com/skedgo/tripkit/LocationInfoApi.kt @@ -1,15 +1,15 @@ -package com.skedgo.tripkit; +package com.skedgo.tripkit -import io.reactivex.Observable; -import retrofit2.http.GET; -import retrofit2.http.Query; -import retrofit2.http.Url; +import io.reactivex.Observable +import retrofit2.http.GET +import retrofit2.http.Query +import retrofit2.http.Url interface LocationInfoApi { @GET - Observable fetchLocationInfoAsync( - @Url String url, - @Query("lat") double lat, - @Query("lng") double lng - ); + fun fetchLocationInfoAsync( + @Url url: String, + @Query("lat") lat: Double?, + @Query("lng") lng: Double? + ): Observable } \ No newline at end of file diff --git a/TripKitAndroid/src/main/java/com/skedgo/tripkit/LocationInfoDetails.kt b/TripKitAndroid/src/main/java/com/skedgo/tripkit/LocationInfoDetails.kt index a31378ce..c6940cf6 100644 --- a/TripKitAndroid/src/main/java/com/skedgo/tripkit/LocationInfoDetails.kt +++ b/TripKitAndroid/src/main/java/com/skedgo/tripkit/LocationInfoDetails.kt @@ -1,20 +1,18 @@ -package com.skedgo.tripkit; +package com.skedgo.tripkit -import com.google.gson.annotations.JsonAdapter; +import com.google.gson.annotations.JsonAdapter +import org.immutables.gson.Gson.TypeAdapters +import org.immutables.value.Value.Immutable +import org.immutables.value.Value.Style -import org.immutables.gson.Gson; -import org.immutables.value.Value; +@TypeAdapters +@Immutable +@Style(passAnnotations = [JsonAdapter::class]) +@JsonAdapter( + GsonAdaptersLocationInfoDetails::class +) +abstract class LocationInfoDetails { + abstract fun w3w(): String? -import androidx.annotation.Nullable; - -@Gson.TypeAdapters -@Value.Immutable -@Value.Style(passAnnotations = JsonAdapter.class) -@JsonAdapter(GsonAdaptersLocationInfoDetails.class) -public abstract class LocationInfoDetails { - @Nullable - public abstract String w3w(); - - @Nullable - public abstract String w3wInfoURL(); + abstract fun w3wInfoURL(): String? } \ No newline at end of file diff --git a/TripKitAndroid/src/main/java/com/skedgo/tripkit/LocationInfoService.kt b/TripKitAndroid/src/main/java/com/skedgo/tripkit/LocationInfoService.kt index 200e2c4f..a782f1a9 100644 --- a/TripKitAndroid/src/main/java/com/skedgo/tripkit/LocationInfoService.kt +++ b/TripKitAndroid/src/main/java/com/skedgo/tripkit/LocationInfoService.kt @@ -1,9 +1,8 @@ -package com.skedgo.tripkit; +package com.skedgo.tripkit -import com.skedgo.tripkit.common.model.location.Location; +import com.skedgo.tripkit.common.model.location.Location +import io.reactivex.Observable -import io.reactivex.Observable; - -public interface LocationInfoService { - Observable getLocationInfoAsync(Location location); +interface LocationInfoService { + fun getLocationInfoAsync(location: Location?): Observable } \ No newline at end of file diff --git a/TripKitAndroid/src/main/java/com/skedgo/tripkit/LocationInfoServiceImpl.kt b/TripKitAndroid/src/main/java/com/skedgo/tripkit/LocationInfoServiceImpl.kt index 4426dd99..071b4895 100644 --- a/TripKitAndroid/src/main/java/com/skedgo/tripkit/LocationInfoServiceImpl.kt +++ b/TripKitAndroid/src/main/java/com/skedgo/tripkit/LocationInfoServiceImpl.kt @@ -1,40 +1,34 @@ -package com.skedgo.tripkit; +package com.skedgo.tripkit -import com.skedgo.tripkit.common.model.location.Location; -import com.skedgo.tripkit.common.model.region.Region; -import com.skedgo.tripkit.data.regions.RegionService; +import com.skedgo.tripkit.common.model.location.Location +import com.skedgo.tripkit.common.model.region.Region +import com.skedgo.tripkit.data.regions.RegionService +import io.reactivex.Observable +import io.reactivex.functions.Function +import okhttp3.HttpUrl.Companion.toHttpUrl -import androidx.annotation.NonNull; -import io.reactivex.Observable; -import io.reactivex.functions.Function; -import okhttp3.HttpUrl; - -final class LocationInfoServiceImpl implements LocationInfoService { - private final LocationInfoApi api; - private final RegionService regionService; - - LocationInfoServiceImpl( - @NonNull LocationInfoApi api, - @NonNull RegionService regionService) { - this.api = api; - this.regionService = regionService; - } - - @Override - public Observable getLocationInfoAsync(final Location location) { +internal class LocationInfoServiceImpl( + private val api: LocationInfoApi, + private val regionService: RegionService +) : LocationInfoService { + override fun getLocationInfoAsync(location: Location?): Observable { return regionService.getRegionByLocationAsync(location) - .flatMap((Function>) region -> Observable.fromIterable(region.getURLs())) - .concatMap((Function>) baseUrl -> { - final String url = HttpUrl.parse(baseUrl).newBuilder() + .flatMap(Function> { region: Region -> + Observable.fromIterable( + region.getURLs() + ) + }) + .concatMap(Function> { baseUrl: String -> + val url: String = baseUrl.toHttpUrl().newBuilder() .addPathSegment("locationInfo.json") .build() - .toString(); - return api.fetchLocationInfoAsync( + .toString() + api.fetchLocationInfoAsync( url, - location.getLat(), - location.getLon() - ); + location?.lat, + location?.lon + ) }) - .filter(response -> response != null).firstElement().toObservable(); + .filter { response: LocationInfo? -> response != null }.firstElement().toObservable() } } \ No newline at end of file diff --git a/TripKitAndroid/src/main/java/com/skedgo/tripkit/MainModule.kt b/TripKitAndroid/src/main/java/com/skedgo/tripkit/MainModule.kt index fa9c02e9..581c23a6 100644 --- a/TripKitAndroid/src/main/java/com/skedgo/tripkit/MainModule.kt +++ b/TripKitAndroid/src/main/java/com/skedgo/tripkit/MainModule.kt @@ -1,136 +1,109 @@ -package com.skedgo.tripkit; - -import android.content.Context; -import android.util.Log; - -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; -import com.skedgo.TripKit; -import com.skedgo.tripkit.a2brouting.FailoverA2bRoutingApi; -import com.skedgo.tripkit.a2brouting.RouteService; -import com.skedgo.tripkit.bookingproviders.BookingResolver; -import com.skedgo.tripkit.bookingproviders.BookingResolverImpl; -import com.skedgo.tripkit.common.model.booking.GsonAdaptersBooking; -import com.skedgo.tripkit.common.model.region.Region; -import com.skedgo.tripkit.common.model.TransportMode; -import com.skedgo.tripkit.common.util.Gsons; -import com.skedgo.tripkit.common.util.LowercaseEnumTypeAdapterFactory; -import com.skedgo.tripkit.configuration.ServerManager; -import com.skedgo.tripkit.data.regions.RegionService; -import com.skedgo.tripkit.data.tsp.GsonAdaptersRegionInfo; -import com.skedgo.tripkit.tsp.GsonAdaptersRegionInfoBody; -import com.skedgo.tripkit.tsp.GsonAdaptersRegionInfoResponse; -import com.skedgo.tripkit.tsp.RegionInfoRepository; - -import java.util.List; -import java.util.Map; -import java.util.concurrent.Callable; - -import javax.inject.Singleton; - -import androidx.annotation.NonNull; -import dagger.Module; -import dagger.Provides; -import io.reactivex.functions.Consumer; -import io.reactivex.schedulers.Schedulers; -import okhttp3.OkHttpClient; -import retrofit2.Retrofit; -import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory; -import retrofit2.converter.gson.GsonConverterFactory; +package com.skedgo.tripkit + +import android.content.Context +import android.util.Log +import com.google.gson.Gson +import com.google.gson.GsonBuilder +import com.skedgo.TripKit +import com.skedgo.tripkit.a2brouting.FailoverA2bRoutingApi +import com.skedgo.tripkit.a2brouting.RouteService +import com.skedgo.tripkit.bookingproviders.BookingResolver +import com.skedgo.tripkit.bookingproviders.BookingResolverImpl +import com.skedgo.tripkit.common.model.TransportMode +import com.skedgo.tripkit.common.model.booking.GsonAdaptersBooking +import com.skedgo.tripkit.common.model.region.Region +import com.skedgo.tripkit.common.util.Gsons +import com.skedgo.tripkit.common.util.LowercaseEnumTypeAdapterFactory +import com.skedgo.tripkit.configuration.ServerManager +import com.skedgo.tripkit.data.regions.RegionService +import com.skedgo.tripkit.data.tsp.GsonAdaptersRegionInfo +import com.skedgo.tripkit.tsp.GsonAdaptersRegionInfoBody +import com.skedgo.tripkit.tsp.GsonAdaptersRegionInfoResponse +import com.skedgo.tripkit.tsp.RegionInfoRepository +import dagger.Module +import dagger.Provides +import io.reactivex.functions.Consumer +import io.reactivex.schedulers.Schedulers +import okhttp3.OkHttpClient +import retrofit2.Retrofit +import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory +import retrofit2.converter.gson.GsonConverterFactory +import javax.inject.Singleton @Module -public class MainModule { - private final Configs configs; - private final Context context; +class MainModule(private val configs: Configs) { - public MainModule(@NonNull Configs configs) { - this.configs = configs; - context = configs.context().getApplicationContext(); - } + private val context: Context = configs.context().applicationContext @Provides - Configs configs() { - return configs; - } + fun configs(): Configs = configs @Provides - RegionsApi getRegionsApi(OkHttpClient httpClient) { - return new Retrofit.Builder() - .baseUrl(ServerManager.INSTANCE.getConfiguration().getApiTripGoUrl()) + fun getRegionsApi(httpClient: OkHttpClient): RegionsApi { + return Retrofit.Builder() + .baseUrl(ServerManager.configuration.apiTripGoUrl) .addConverterFactory(GsonConverterFactory.create(Gsons.createForRegion())) .addCallAdapterFactory(RxJava2CallAdapterFactory.createWithScheduler(Schedulers.io())) .client(httpClient) .build() - .create(RegionsApi.class); + .create(RegionsApi::class.java) } @Singleton @Provides - RegionDatabaseHelper getRegionDatabaseHelper() { - return new RegionDatabaseHelper( - context, - "regions.db" - ); + fun getRegionDatabaseHelper(): RegionDatabaseHelper { + return RegionDatabaseHelper(context, "regions.db") } @Singleton @Provides - RegionService getRegionService( - RegionDatabaseHelper databaseHelper, - RegionsApi regionsApi, - RegionInfoRepository regionInfoRepository) { - - final RegionsFetcher regionsFetcher = new RegionsFetcherImpl( - regionsApi, - databaseHelper - ); - final Cache> regionCache = new CacheImpl<>( + fun getRegionService( + databaseHelper: RegionDatabaseHelper, + regionsApi: RegionsApi, + regionInfoRepository: RegionInfoRepository + ): RegionService { + val regionsFetcher = RegionsFetcherImpl(regionsApi, databaseHelper) + val regionCache: Cache> = CacheImpl( regionsFetcher.fetchAsync(), databaseHelper.loadRegionsAsync() - ); - final Cache> modeCache = new CacheImpl<>( + ) + val modeCache: Cache> = CacheImpl( regionsFetcher.fetchAsync(), databaseHelper.loadModesAsync() - ); - return new RegionServiceImpl( + ) + return RegionServiceImpl( regionCache, modeCache, regionsFetcher, regionInfoRepository, - new RegionFinder() - ); + RegionFinder() + ) } @Singleton @Provides - RouteService routeService( - FailoverA2bRoutingApi routingApi, - RegionService regionService, - Configs configs, - RegionInfoRepository regionInfoRepository - ) { - Co2Preferences co2Preferences = null; - final Callable co2PreferencesFactory = configs.co2PreferencesFactory(); - if (co2PreferencesFactory != null) { - try { - co2Preferences = co2PreferencesFactory.call(); - } catch (Exception e) { - e.printStackTrace(); - } + fun routeService( + routingApi: FailoverA2bRoutingApi, + regionService: RegionService, + configs: Configs, + regionInfoRepository: RegionInfoRepository + ): RouteService { + val co2Preferences: Co2Preferences? = try { + configs.co2PreferencesFactory()?.call() + } catch (e: Exception) { + e.printStackTrace() + null } - TripPreferences tripPreferences = null; - final Callable tripPreferencesFactory = configs.tripPreferencesFactory(); - if (tripPreferencesFactory != null) { - try { - tripPreferences = tripPreferencesFactory.call(); - } catch (Exception e) { - e.printStackTrace(); - } + val tripPreferences: TripPreferences? = try { + configs.tripPreferencesFactory()?.call() + } catch (e: Exception) { + e.printStackTrace() + null } - final QueryGeneratorImpl queryGenerator = new QueryGeneratorImpl(regionService); - return new RouteServiceImpl( + val queryGenerator = QueryGeneratorImpl(regionService) + return RouteServiceImpl( context, queryGenerator, co2Preferences, @@ -138,69 +111,64 @@ public class MainModule { configs.extraQueryMapProvider(), routingApi, regionInfoRepository - ); + ) } @Provides - Context context() { - return configs.context(); - } + fun context(): Context = configs.context() @Provides - BookingResolver getBookingResolver() { - return new BookingResolverImpl( - context.getResources(), - context.getPackageManager(), - new AndroidGeocoder(context) - ); + fun getBookingResolver(): BookingResolver { + return BookingResolverImpl( + context.resources, + context.packageManager, + AndroidGeocoder(context) + ) } - @Provides - LocationInfoApi getLocationInfoApi(Gson gson, OkHttpClient httpClient) { - return new Retrofit.Builder() - /* This base url is ignored as the api relies on @Url. */ - .baseUrl(ServerManager.INSTANCE.getConfiguration().getApiTripGoUrl()) + fun getLocationInfoApi(gson: Gson, httpClient: OkHttpClient): LocationInfoApi { + return Retrofit.Builder() + .baseUrl(ServerManager.configuration.apiTripGoUrl) // Ignored base URL .addCallAdapterFactory(RxJava2CallAdapterFactory.createWithScheduler(Schedulers.io())) .addConverterFactory(GsonConverterFactory.create(gson)) .client(httpClient) .build() - .create(LocationInfoApi.class); + .create(LocationInfoApi::class.java) } @Provides - LocationInfoService getLocationInfoService( - LocationInfoApi locationInfoApi, - RegionService regionService) { - return new LocationInfoServiceImpl(locationInfoApi, regionService); + fun getLocationInfoService( + locationInfoApi: LocationInfoApi, + regionService: RegionService + ): LocationInfoService { + return LocationInfoServiceImpl(locationInfoApi, regionService) } @Singleton @Provides - Gson getGson() { - return new GsonBuilder() - .registerTypeAdapterFactory(new LowercaseEnumTypeAdapterFactory()) - .registerTypeAdapterFactory(new GsonAdaptersRegionInfoBody()) - .registerTypeAdapterFactory(new GsonAdaptersRegionInfo()) - .registerTypeAdapterFactory(new GsonAdaptersRegionInfoResponse()) - .registerTypeAdapterFactory(new GsonAdaptersLocationInfo()) - .registerTypeAdapterFactory(new GsonAdaptersLocationInfoDetails()) - .registerTypeAdapterFactory(new GsonAdaptersCarPark()) - .registerTypeAdapterFactory(new GsonAdaptersBooking()) - .create(); + fun getGson(): Gson { + return GsonBuilder() + .registerTypeAdapterFactory(LowercaseEnumTypeAdapterFactory()) + .registerTypeAdapterFactory(GsonAdaptersRegionInfoBody()) + .registerTypeAdapterFactory(GsonAdaptersRegionInfo()) + .registerTypeAdapterFactory(GsonAdaptersRegionInfoResponse()) + .registerTypeAdapterFactory(GsonAdaptersLocationInfo()) + .registerTypeAdapterFactory(GsonAdaptersLocationInfoDetails()) + .registerTypeAdapterFactory(GsonAdaptersCarPark()) + .registerTypeAdapterFactory(GsonAdaptersBooking()) + .create() } @Singleton @Provides - Consumer getErrorHandler() { - final Consumer errorHandler = configs.errorHandler(); - return error -> { + fun getErrorHandler(): Consumer { + val errorHandler = configs.errorHandler() + return Consumer { error -> if (configs.debuggable()) { - Log.e(TripKit.class.getSimpleName(), error.getMessage(), error); + Log.e(TripKit::class.java.simpleName, error.message, error) } - if (errorHandler != null) { - errorHandler.accept(error); - } - }; + errorHandler?.accept(error) + } } } diff --git a/TripKitAndroid/src/main/java/com/skedgo/tripkit/RegionDatabaseHelper.kt b/TripKitAndroid/src/main/java/com/skedgo/tripkit/RegionDatabaseHelper.kt index 6a848c51..d3a985d4 100644 --- a/TripKitAndroid/src/main/java/com/skedgo/tripkit/RegionDatabaseHelper.kt +++ b/TripKitAndroid/src/main/java/com/skedgo/tripkit/RegionDatabaseHelper.kt @@ -1,54 +1,44 @@ -package com.skedgo.tripkit; - -import android.content.Context; -import android.database.sqlite.SQLiteDatabase; -import android.database.sqlite.SQLiteOpenHelper; - -import com.skedgo.sqlite.Cursors; -import com.skedgo.tripkit.common.model.region.Region; -import com.skedgo.tripkit.common.model.TransportMode; - -import java.util.List; -import java.util.Map; - -import io.reactivex.Observable; -import io.reactivex.schedulers.Schedulers; - -final class RegionDatabaseHelper extends SQLiteOpenHelper { - RegionDatabaseHelper(Context context, String name) { - super(context, name, null, 2); - } - - @Override - public void onCreate(SQLiteDatabase db) { - db.execSQL(Tables.REGIONS.getCreateSql()); - db.execSQL(Tables.TRANSPORT_MODES.getCreateSql()); +package com.skedgo.tripkit + +import android.content.Context +import android.database.sqlite.SQLiteDatabase +import android.database.sqlite.SQLiteOpenHelper +import com.skedgo.sqlite.Cursors.flattenCursor +import com.skedgo.tripkit.common.model.TransportMode +import com.skedgo.tripkit.common.model.region.Region +import io.reactivex.Observable +import io.reactivex.schedulers.Schedulers + +class RegionDatabaseHelper(context: Context?, name: String?) : + SQLiteOpenHelper(context, name, null, 2) { + override fun onCreate(db: SQLiteDatabase) { + db.execSQL(Tables.REGIONS.getCreateSql()) + db.execSQL(Tables.TRANSPORT_MODES.getCreateSql()) } - @Override - public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { - db.delete(Tables.REGIONS.getName(), null, null); - db.delete(Tables.TRANSPORT_MODES.getName(), null, null); + override fun onUpgrade(db: SQLiteDatabase, oldVersion: Int, newVersion: Int) { + db.delete(Tables.REGIONS.name, null, null) + db.delete(Tables.TRANSPORT_MODES.name, null, null) } - public Observable> loadRegionsAsync() { + fun loadRegionsAsync(): Observable> { return Observable - .create(new OnSubscribeLoadRegions(this)) - .flatMap(Cursors.flattenCursor()) - .map(new CursorToRegionConverter()) + .create(OnSubscribeLoadRegions(this)) + .flatMap(flattenCursor()) + .map(CursorToRegionConverter()) .toList() - .filter(Utils.isNotEmpty()).toObservable().firstOrError().toObservable() - .subscribeOn(Schedulers.io()); + .filter(Utils.isNotEmpty()).toObservable().firstOrError().toObservable() + .subscribeOn(Schedulers.io()) } - public Observable> loadModesAsync() { + fun loadModesAsync(): Observable> { return Observable - .create(new OnSubscribeLoadTransportModes(this)) - .flatMap(Cursors.flattenCursor()) - .map(new CursorToTransportModeConverter()) + .create(OnSubscribeLoadTransportModes(this)) + .flatMap(flattenCursor()) + .map(CursorToTransportModeConverter()) .toList() - .filter(Utils.isNotEmpty()).toObservable() + .filter(Utils.isNotEmpty()).toObservable() .map(Utils.toModeMap()) - .subscribeOn(Schedulers.io()); + .subscribeOn(Schedulers.io()) } } \ No newline at end of file diff --git a/TripKitAndroid/src/main/java/com/skedgo/tripkit/RegionFinder.kt b/TripKitAndroid/src/main/java/com/skedgo/tripkit/RegionFinder.kt index 6484cfba..ae4cbd92 100644 --- a/TripKitAndroid/src/main/java/com/skedgo/tripkit/RegionFinder.kt +++ b/TripKitAndroid/src/main/java/com/skedgo/tripkit/RegionFinder.kt @@ -1,33 +1,33 @@ -package com.skedgo.tripkit; +package com.skedgo.tripkit -import com.skedgo.tripkit.common.model.region.Region; -import com.skedgo.tripkit.common.util.PolyUtil; -import com.skedgo.tripkit.common.util.TripKitLatLng; - -import java.util.List; -import java.util.Map; -import java.util.concurrent.ConcurrentHashMap; +import com.skedgo.tripkit.common.model.region.Region +import com.skedgo.tripkit.common.util.PolyUtil +import com.skedgo.tripkit.common.util.TripKitLatLng +import java.util.concurrent.ConcurrentHashMap class RegionFinder { - private final Map> polygonCache = new ConcurrentHashMap<>(); - public boolean contains(Region region, double lat, double lng) { - final List polygon = getPolygon(region, polygonCache); - return polygon != null - && PolyUtil.containsLocation(lat, lng, polygon, true); + private val polygonCache: MutableMap> = ConcurrentHashMap() + + fun contains(region: Region, lat: Double, lng: Double): Boolean { + val polygon = getPolygon(region, polygonCache) + return polygon != null && PolyUtil.containsLocation(lat, lng, polygon, true) } - public void invalidate() { - polygonCache.clear(); + fun invalidate() { + polygonCache.clear() } - private List getPolygon(Region region, Map> polygonCache) { - final String name = region.getName(); - List polygon = polygonCache.get(name); + private fun getPolygon( + region: Region, + polygonCache: MutableMap> + ): List? { + val name = region.name.orEmpty() + var polygon = polygonCache[name] if (polygon == null) { - polygon = PolyUtil.decode(region.getEncodedPolyline()); - polygonCache.put(name, polygon); + polygon = PolyUtil.decode(region.encodedPolyline) + polygonCache[name] = polygon } - return polygon; + return polygon } } diff --git a/TripKitAndroid/src/main/java/com/skedgo/tripkit/RegionServiceImpl.kt b/TripKitAndroid/src/main/java/com/skedgo/tripkit/RegionServiceImpl.kt index f6020b4e..025958c8 100644 --- a/TripKitAndroid/src/main/java/com/skedgo/tripkit/RegionServiceImpl.kt +++ b/TripKitAndroid/src/main/java/com/skedgo/tripkit/RegionServiceImpl.kt @@ -22,7 +22,7 @@ internal class RegionServiceImpl( private val regionFinder: RegionFinder ) : RegionService { override fun getRegionsAsync(): Observable> = - regionCache.async.toObservable() + regionCache.getAsync().toObservable() override fun getRegionByNameAsync(regionName: String): Observable = getRegionsAsync() @@ -31,7 +31,7 @@ internal class RegionServiceImpl( .first(Region()).toObservable() override fun getTransportModesAsync(): Observable> = - modeCache.async.toObservable() + modeCache.getAsync().toObservable() override fun getRegionByLocationAsync(latitude: Double, longitude: Double): Observable = getRegionsAsync() diff --git a/TripKitAndroid/src/main/java/com/skedgo/tripkit/RegionsApi.kt b/TripKitAndroid/src/main/java/com/skedgo/tripkit/RegionsApi.kt index e2f0d915..6e89ef87 100644 --- a/TripKitAndroid/src/main/java/com/skedgo/tripkit/RegionsApi.kt +++ b/TripKitAndroid/src/main/java/com/skedgo/tripkit/RegionsApi.kt @@ -1,29 +1,21 @@ -package com.skedgo.tripkit; +package com.skedgo.tripkit -import com.google.gson.annotations.SerializedName; -import com.skedgo.tripkit.common.model.region.RegionsResponse; - -import io.reactivex.Observable; -import io.reactivex.Single; -import retrofit2.http.Body; -import retrofit2.http.POST; +import com.google.gson.annotations.SerializedName +import com.skedgo.tripkit.common.model.region.RegionsResponse +import io.reactivex.Observable +import io.reactivex.Single +import retrofit2.http.Body +import retrofit2.http.POST interface RegionsApi { @POST("regions.json") - Single fetchRegionsAsyncAsSingle(@Body RequestBodyContent bodyContent); + fun fetchRegionsAsyncAsSingle(@Body bodyContent: RequestBodyContent): Single @POST("regions.json") - Observable fetchRegionsAsync(@Body RequestBodyContent bodyContent); - - final class RequestBodyContent { - @SerializedName("v") - private int apiVersion; - @SerializedName("app") - private String appFlavor; + fun fetchRegionsAsync(@Body bodyContent: RequestBodyContent): Observable - public RequestBodyContent(int apiVersion, String appFlavor) { - this.apiVersion = apiVersion; - this.appFlavor = appFlavor; - } - } + class RequestBodyContent( + @SerializedName("v") private val apiVersion: Int, + @SerializedName("app") private val appFlavr: String? + ) } \ No newline at end of file diff --git a/TripKitAndroid/src/main/java/com/skedgo/tripkit/RouteServiceImpl.kt b/TripKitAndroid/src/main/java/com/skedgo/tripkit/RouteServiceImpl.kt index 4f02d935..9c62e957 100644 --- a/TripKitAndroid/src/main/java/com/skedgo/tripkit/RouteServiceImpl.kt +++ b/TripKitAndroid/src/main/java/com/skedgo/tripkit/RouteServiceImpl.kt @@ -69,7 +69,7 @@ internal class RouteServiceImpl( if (co2Preferences != null) { - val co2Profile = co2Preferences.co2Profile + val co2Profile = co2Preferences.getCo2Profile() for ((key, value) in co2Profile) { map["co2[$key]"] = value } diff --git a/TripKitAndroid/src/main/java/com/skedgo/tripkit/ServiceApi.kt b/TripKitAndroid/src/main/java/com/skedgo/tripkit/ServiceApi.kt index 13e2f535..1bc55953 100644 --- a/TripKitAndroid/src/main/java/com/skedgo/tripkit/ServiceApi.kt +++ b/TripKitAndroid/src/main/java/com/skedgo/tripkit/ServiceApi.kt @@ -1,18 +1,18 @@ -package com.skedgo.tripkit; +package com.skedgo.tripkit -import io.reactivex.Observable; -import retrofit2.http.GET; -import retrofit2.http.Query; +import io.reactivex.Observable +import retrofit2.http.GET +import retrofit2.http.Query -public interface ServiceApi { +interface ServiceApi { @GET("service.json") - Observable getServiceAsync( - @Query("region") String region, - @Query("serviceTripID") String serviceTripId, - @Query("operator") String operator, - @Query("startStopCode") String startStopCode, - @Query("endStopCode") String endStopCode, - @Query("embarkationDate") long timeInSecs, - @Query("encode") boolean encode - ); + fun getServiceAsync( + @Query("region") region: String, + @Query("serviceTripID") serviceTripId: String, + @Query("operator") operator: String?, + @Query("startStopCode") startStopCode: String, + @Query("endStopCode") endStopCode: String?, + @Query("embarkationDate") timeInSecs: Long, + @Query("encode") encode: Boolean + ): Observable } \ No newline at end of file From f04204a70f286e38e00a962a6b74f73ea78bf42e Mon Sep 17 00:00:00 2001 From: Michael Angelo Reyes Date: Mon, 11 Nov 2024 14:55:45 +0800 Subject: [PATCH 13/25] Rename .java to .kt --- .../src/main/java/com/skedgo/{TripKit.java => TripKit.kt} | 0 .../{ModeCombinationStrategy.java => ModeCombinationStrategy.kt} | 0 .../{OnSubscribeLoadRegions.java => OnSubscribeLoadRegions.kt} | 0 ...beLoadTransportModes.java => OnSubscribeLoadTransportModes.kt} | 0 ...SaveRegionsResponse.java => OnSubscribeSaveRegionsResponse.kt} | 0 .../{OutOfRegionsException.java => OutOfRegionsException.kt} | 0 ...pUpdateReceiver.java => PeriodicRealTimeTripUpdateReceiver.kt} | 0 ...lTimeTripUpdateReceiver.java => RealTimeTripUpdateReceiver.kt} | 0 .../com/skedgo/tripkit/{ServiceExtras.java => ServiceExtras.kt} | 0 .../src/main/java/com/skedgo/tripkit/{Tables.java => Tables.kt} | 0 .../skedgo/tripkit/{TemporaryUrlApi.java => TemporaryUrlApi.kt} | 0 .../com/skedgo/tripkit/{TransitService.java => TransitService.kt} | 0 .../com/skedgo/tripkit/{TripKitConfigs.java => TripKitConfigs.kt} | 0 .../skedgo/tripkit/{TripPreferences.java => TripPreferences.kt} | 0 .../src/main/java/com/skedgo/tripkit/{Utils.java => Utils.kt} | 0 .../com/skedgo/tripkit/{UuidProvider.java => UuidProvider.kt} | 0 16 files changed, 0 insertions(+), 0 deletions(-) rename TripKitAndroid/src/main/java/com/skedgo/{TripKit.java => TripKit.kt} (100%) rename TripKitAndroid/src/main/java/com/skedgo/tripkit/{ModeCombinationStrategy.java => ModeCombinationStrategy.kt} (100%) rename TripKitAndroid/src/main/java/com/skedgo/tripkit/{OnSubscribeLoadRegions.java => OnSubscribeLoadRegions.kt} (100%) rename TripKitAndroid/src/main/java/com/skedgo/tripkit/{OnSubscribeLoadTransportModes.java => OnSubscribeLoadTransportModes.kt} (100%) rename TripKitAndroid/src/main/java/com/skedgo/tripkit/{OnSubscribeSaveRegionsResponse.java => OnSubscribeSaveRegionsResponse.kt} (100%) rename TripKitAndroid/src/main/java/com/skedgo/tripkit/{OutOfRegionsException.java => OutOfRegionsException.kt} (100%) rename TripKitAndroid/src/main/java/com/skedgo/tripkit/{PeriodicRealTimeTripUpdateReceiver.java => PeriodicRealTimeTripUpdateReceiver.kt} (100%) rename TripKitAndroid/src/main/java/com/skedgo/tripkit/{RealTimeTripUpdateReceiver.java => RealTimeTripUpdateReceiver.kt} (100%) rename TripKitAndroid/src/main/java/com/skedgo/tripkit/{ServiceExtras.java => ServiceExtras.kt} (100%) rename TripKitAndroid/src/main/java/com/skedgo/tripkit/{Tables.java => Tables.kt} (100%) rename TripKitAndroid/src/main/java/com/skedgo/tripkit/{TemporaryUrlApi.java => TemporaryUrlApi.kt} (100%) rename TripKitAndroid/src/main/java/com/skedgo/tripkit/{TransitService.java => TransitService.kt} (100%) rename TripKitAndroid/src/main/java/com/skedgo/tripkit/{TripKitConfigs.java => TripKitConfigs.kt} (100%) rename TripKitAndroid/src/main/java/com/skedgo/tripkit/{TripPreferences.java => TripPreferences.kt} (100%) rename TripKitAndroid/src/main/java/com/skedgo/tripkit/{Utils.java => Utils.kt} (100%) rename TripKitAndroid/src/main/java/com/skedgo/tripkit/{UuidProvider.java => UuidProvider.kt} (100%) diff --git a/TripKitAndroid/src/main/java/com/skedgo/TripKit.java b/TripKitAndroid/src/main/java/com/skedgo/TripKit.kt similarity index 100% rename from TripKitAndroid/src/main/java/com/skedgo/TripKit.java rename to TripKitAndroid/src/main/java/com/skedgo/TripKit.kt diff --git a/TripKitAndroid/src/main/java/com/skedgo/tripkit/ModeCombinationStrategy.java b/TripKitAndroid/src/main/java/com/skedgo/tripkit/ModeCombinationStrategy.kt similarity index 100% rename from TripKitAndroid/src/main/java/com/skedgo/tripkit/ModeCombinationStrategy.java rename to TripKitAndroid/src/main/java/com/skedgo/tripkit/ModeCombinationStrategy.kt diff --git a/TripKitAndroid/src/main/java/com/skedgo/tripkit/OnSubscribeLoadRegions.java b/TripKitAndroid/src/main/java/com/skedgo/tripkit/OnSubscribeLoadRegions.kt similarity index 100% rename from TripKitAndroid/src/main/java/com/skedgo/tripkit/OnSubscribeLoadRegions.java rename to TripKitAndroid/src/main/java/com/skedgo/tripkit/OnSubscribeLoadRegions.kt diff --git a/TripKitAndroid/src/main/java/com/skedgo/tripkit/OnSubscribeLoadTransportModes.java b/TripKitAndroid/src/main/java/com/skedgo/tripkit/OnSubscribeLoadTransportModes.kt similarity index 100% rename from TripKitAndroid/src/main/java/com/skedgo/tripkit/OnSubscribeLoadTransportModes.java rename to TripKitAndroid/src/main/java/com/skedgo/tripkit/OnSubscribeLoadTransportModes.kt diff --git a/TripKitAndroid/src/main/java/com/skedgo/tripkit/OnSubscribeSaveRegionsResponse.java b/TripKitAndroid/src/main/java/com/skedgo/tripkit/OnSubscribeSaveRegionsResponse.kt similarity index 100% rename from TripKitAndroid/src/main/java/com/skedgo/tripkit/OnSubscribeSaveRegionsResponse.java rename to TripKitAndroid/src/main/java/com/skedgo/tripkit/OnSubscribeSaveRegionsResponse.kt diff --git a/TripKitAndroid/src/main/java/com/skedgo/tripkit/OutOfRegionsException.java b/TripKitAndroid/src/main/java/com/skedgo/tripkit/OutOfRegionsException.kt similarity index 100% rename from TripKitAndroid/src/main/java/com/skedgo/tripkit/OutOfRegionsException.java rename to TripKitAndroid/src/main/java/com/skedgo/tripkit/OutOfRegionsException.kt diff --git a/TripKitAndroid/src/main/java/com/skedgo/tripkit/PeriodicRealTimeTripUpdateReceiver.java b/TripKitAndroid/src/main/java/com/skedgo/tripkit/PeriodicRealTimeTripUpdateReceiver.kt similarity index 100% rename from TripKitAndroid/src/main/java/com/skedgo/tripkit/PeriodicRealTimeTripUpdateReceiver.java rename to TripKitAndroid/src/main/java/com/skedgo/tripkit/PeriodicRealTimeTripUpdateReceiver.kt diff --git a/TripKitAndroid/src/main/java/com/skedgo/tripkit/RealTimeTripUpdateReceiver.java b/TripKitAndroid/src/main/java/com/skedgo/tripkit/RealTimeTripUpdateReceiver.kt similarity index 100% rename from TripKitAndroid/src/main/java/com/skedgo/tripkit/RealTimeTripUpdateReceiver.java rename to TripKitAndroid/src/main/java/com/skedgo/tripkit/RealTimeTripUpdateReceiver.kt diff --git a/TripKitAndroid/src/main/java/com/skedgo/tripkit/ServiceExtras.java b/TripKitAndroid/src/main/java/com/skedgo/tripkit/ServiceExtras.kt similarity index 100% rename from TripKitAndroid/src/main/java/com/skedgo/tripkit/ServiceExtras.java rename to TripKitAndroid/src/main/java/com/skedgo/tripkit/ServiceExtras.kt diff --git a/TripKitAndroid/src/main/java/com/skedgo/tripkit/Tables.java b/TripKitAndroid/src/main/java/com/skedgo/tripkit/Tables.kt similarity index 100% rename from TripKitAndroid/src/main/java/com/skedgo/tripkit/Tables.java rename to TripKitAndroid/src/main/java/com/skedgo/tripkit/Tables.kt diff --git a/TripKitAndroid/src/main/java/com/skedgo/tripkit/TemporaryUrlApi.java b/TripKitAndroid/src/main/java/com/skedgo/tripkit/TemporaryUrlApi.kt similarity index 100% rename from TripKitAndroid/src/main/java/com/skedgo/tripkit/TemporaryUrlApi.java rename to TripKitAndroid/src/main/java/com/skedgo/tripkit/TemporaryUrlApi.kt diff --git a/TripKitAndroid/src/main/java/com/skedgo/tripkit/TransitService.java b/TripKitAndroid/src/main/java/com/skedgo/tripkit/TransitService.kt similarity index 100% rename from TripKitAndroid/src/main/java/com/skedgo/tripkit/TransitService.java rename to TripKitAndroid/src/main/java/com/skedgo/tripkit/TransitService.kt diff --git a/TripKitAndroid/src/main/java/com/skedgo/tripkit/TripKitConfigs.java b/TripKitAndroid/src/main/java/com/skedgo/tripkit/TripKitConfigs.kt similarity index 100% rename from TripKitAndroid/src/main/java/com/skedgo/tripkit/TripKitConfigs.java rename to TripKitAndroid/src/main/java/com/skedgo/tripkit/TripKitConfigs.kt diff --git a/TripKitAndroid/src/main/java/com/skedgo/tripkit/TripPreferences.java b/TripKitAndroid/src/main/java/com/skedgo/tripkit/TripPreferences.kt similarity index 100% rename from TripKitAndroid/src/main/java/com/skedgo/tripkit/TripPreferences.java rename to TripKitAndroid/src/main/java/com/skedgo/tripkit/TripPreferences.kt diff --git a/TripKitAndroid/src/main/java/com/skedgo/tripkit/Utils.java b/TripKitAndroid/src/main/java/com/skedgo/tripkit/Utils.kt similarity index 100% rename from TripKitAndroid/src/main/java/com/skedgo/tripkit/Utils.java rename to TripKitAndroid/src/main/java/com/skedgo/tripkit/Utils.kt diff --git a/TripKitAndroid/src/main/java/com/skedgo/tripkit/UuidProvider.java b/TripKitAndroid/src/main/java/com/skedgo/tripkit/UuidProvider.kt similarity index 100% rename from TripKitAndroid/src/main/java/com/skedgo/tripkit/UuidProvider.java rename to TripKitAndroid/src/main/java/com/skedgo/tripkit/UuidProvider.kt From 63be4e17a4f8c443362a542f376049e52e9be3d2 Mon Sep 17 00:00:00 2001 From: Michael Angelo Reyes Date: Mon, 11 Nov 2024 14:55:45 +0800 Subject: [PATCH 14/25] [22682] - [TripKit] convert ModeCombinationStrategy.java to kotlin - [TripKit] convert OnSubscribeLoadRegions.java to kotlin - [TripKit] convert OnSubscribeLoadTransportModes.java to kotlin - [TripKit] convert OnSubscribeSaveRegionsResponse.java to kotlin - [TripKit] convert OutOfRegionsException.java to kotlin - [TripKit] convert PeriodicRealTimeTripUpdateReceiver.java to kotlin - [TripKit] convert RealTimeTripUpdateReceiver.java to kotlin - [TripKit] convert ServiceExtras.java to kotlin - [TripKit] convert Tables.java to kotlin - [TripKit] convert TemporaryUrlApi.java to kotlin - [TripKit] convert TransitService.java to kotlin - [TripKit] convert TripKit.java to kotlin - [TripKit] convert TripKitConfigs.java to kotlin - [TripKit] convert TripPreferences.java to kotlin - [TripKit] convert Utils.java to kotlin - [TripKit] convert UuidProvider.java to kotlin - [TripKitUI] update affected classes --- .../src/main/java/com/skedgo/TripKit.kt | 257 +++++++++--------- .../skedgo/tripkit/ModeCombinationStrategy.kt | 91 +++---- .../skedgo/tripkit/OnSubscribeLoadRegions.kt | 46 ++-- .../tripkit/OnSubscribeLoadTransportModes.kt | 46 ++-- .../tripkit/OnSubscribeSaveRegionsResponse.kt | 94 +++---- .../skedgo/tripkit/OutOfRegionsException.kt | 32 +-- .../PeriodicRealTimeTripUpdateReceiver.kt | 151 +++++----- .../tripkit/RealTimeTripUpdateReceiver.kt | 16 +- .../com/skedgo/tripkit/RegionServiceImpl.kt | 2 +- .../com/skedgo/tripkit/RouteServiceImpl.kt | 2 +- .../java/com/skedgo/tripkit/ServiceExtras.kt | 24 +- .../main/java/com/skedgo/tripkit/Tables.kt | 27 +- .../com/skedgo/tripkit/TemporaryUrlApi.kt | 32 +-- .../java/com/skedgo/tripkit/TransitService.kt | 38 ++- .../java/com/skedgo/tripkit/TripKitConfigs.kt | 47 ++-- .../com/skedgo/tripkit/TripPreferences.kt | 29 +- .../src/main/java/com/skedgo/tripkit/Utils.kt | 130 ++++----- .../java/com/skedgo/tripkit/UuidProvider.kt | 44 ++- 18 files changed, 494 insertions(+), 614 deletions(-) diff --git a/TripKitAndroid/src/main/java/com/skedgo/TripKit.kt b/TripKitAndroid/src/main/java/com/skedgo/TripKit.kt index 2efe1ceb..41de447d 100644 --- a/TripKitAndroid/src/main/java/com/skedgo/TripKit.kt +++ b/TripKitAndroid/src/main/java/com/skedgo/TripKit.kt @@ -1,148 +1,143 @@ -package com.skedgo; - -import android.app.NotificationChannel; -import android.content.Context; -import android.os.Build; - -import com.skedgo.tripkit.Configs; -import com.skedgo.tripkit.HttpClientModule; -import com.skedgo.tripkit.LocationInfoService; -import com.skedgo.tripkit.MainModule; -import com.skedgo.tripkit.TripUpdater; -import com.skedgo.tripkit.a2brouting.A2bRoutingDataModule; -import com.skedgo.tripkit.a2brouting.RouteService; -import com.skedgo.tripkit.android.A2bRoutingComponent; -import com.skedgo.tripkit.android.AnalyticsComponent; -import com.skedgo.tripkit.android.DateTimeComponent; -import com.skedgo.tripkit.android.FetchRegionsService; -import com.skedgo.tripkit.bookingproviders.BookingResolver; -import com.skedgo.tripkit.data.TripKitPreferencesModule; -import com.skedgo.tripkit.data.regions.RegionService; -import com.skedgo.tripkit.notification.NotificationKt; -import com.skedgo.tripkit.routing.GeoLocation; -import com.skedgo.tripkit.routing.GetOffAlertCache; -import com.skedgo.tripkit.tsp.TspModule; - -import net.danlew.android.joda.JodaTimeAndroid; - -import java.util.ArrayList; -import java.util.List; - -import javax.inject.Singleton; - -import androidx.annotation.NonNull; -import dagger.Component; -import io.reactivex.functions.Consumer; - -import static com.skedgo.tripkit.routing.TripAlarmBroadcastReceiver.NOTIFICATION_CHANNEL_START_TRIP; -import static com.skedgo.tripkit.routing.TripAlarmBroadcastReceiver.NOTIFICATION_CHANNEL_START_TRIP_ID; +package com.skedgo + +import android.app.NotificationChannel +import android.content.Context +import android.os.Build.VERSION +import android.os.Build.VERSION_CODES +import com.skedgo.tripkit.Configs +import com.skedgo.tripkit.HttpClientModule +import com.skedgo.tripkit.LocationInfoService +import com.skedgo.tripkit.MainModule +import com.skedgo.tripkit.TripUpdater +import com.skedgo.tripkit.a2brouting.A2bRoutingDataModule +import com.skedgo.tripkit.a2brouting.RouteService +import com.skedgo.tripkit.android.A2bRoutingComponent +import com.skedgo.tripkit.android.AnalyticsComponent +import com.skedgo.tripkit.android.DateTimeComponent +import com.skedgo.tripkit.android.FetchRegionsService +import com.skedgo.tripkit.android.FetchRegionsService.Companion.scheduleAsync +import com.skedgo.tripkit.bookingproviders.BookingResolver +import com.skedgo.tripkit.data.TripKitPreferencesModule +import com.skedgo.tripkit.data.regions.RegionService +import com.skedgo.tripkit.notification.createChannel +import com.skedgo.tripkit.notification.createNotificationChannels +import com.skedgo.tripkit.routing.GeoLocation +import com.skedgo.tripkit.routing.GetOffAlertCache +import com.skedgo.tripkit.routing.TripAlarmBroadcastReceiver +import com.skedgo.tripkit.tsp.TspModule +import dagger.Component +import io.reactivex.functions.Consumer +import net.danlew.android.joda.JodaTimeAndroid +import okhttp3.OkHttpClient +import javax.inject.Singleton @Singleton -@Component(modules = { - HttpClientModule.class, - A2bRoutingDataModule.class, - TspModule.class, - MainModule.class, - TripKitPreferencesModule.class -}) -public abstract class TripKit { - private static TripKit instance; - - public static TripKit getInstance() { - synchronized (TripKit.class) { - if (instance == null) { - throw new IllegalStateException("Must initialize TripKit before using getInstance()"); - } - - return instance; - } - } - - /** - * This gives a chance to provide a custom {@link TripKit}. - * One idea is that we can create {@link DaggerTripKit} - * w/ some customized modules. - *

- * Note that you should only use this - * when you totally understand what you're doing. - * Otherwise, just go with {@link #initialize(Configs)} instead. - * - * @param context A {@link Context} to launch {@link FetchRegionsService}. - * @param tripKit Can be created via {@link DaggerTripKit}. - */ - public static void initialize(@NonNull Context context, @NonNull TripKit tripKit) { - synchronized (TripKit.class) { - if (instance == null) { - instance = tripKit; - } - FetchRegionsService.Companion.scheduleAsync(context) - .subscribe(unused -> { - }, instance.getErrorHandler()); - } - } - - public static boolean isInitialized() { - return (instance != null); - } +@Component( + modules = [ + HttpClientModule::class, + A2bRoutingDataModule::class, + TspModule::class, + MainModule::class, + TripKitPreferencesModule::class + ] +) +abstract class TripKit { + abstract fun configs(): Configs - public static void initialize(Configs configs) { - synchronized (TripKit.class) { - if (configs == null) { - throw new IllegalStateException("Must initialize Configs before using initialize()"); - } + abstract val regionService: RegionService - if (instance == null) { - instance = DaggerTripKit.builder() - .mainModule(new MainModule(configs)) - .httpClientModule(new HttpClientModule( - null, - null, - configs, - null, - null - )) - .build(); - JodaTimeAndroid.init(configs.context()); - GetOffAlertCache.INSTANCE.init(configs.context()); - GeoLocation.INSTANCE.init(configs.context()); - if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { - List channels = new ArrayList<>(); - channels.add(NotificationKt.createChannel( - NOTIFICATION_CHANNEL_START_TRIP_ID, - NOTIFICATION_CHANNEL_START_TRIP) - ); - NotificationKt.createNotificationChannels( - configs.context(), - channels - ); - } - } + abstract val routeService: RouteService - FetchRegionsService.Companion.scheduleAsync(configs.context()) - .subscribe(unused -> { - }, instance.getErrorHandler()); - } - } + abstract val okHttpClient3: OkHttpClient - public abstract Configs configs(); + abstract val bookingResolver: BookingResolver - public abstract RegionService getRegionService(); + abstract val locationInfoService: LocationInfoService - public abstract RouteService getRouteService(); + abstract val tripUpdater: TripUpdater - public abstract okhttp3.OkHttpClient getOkHttpClient3(); + abstract fun a2bRoutingComponent(): A2bRoutingComponent - public abstract BookingResolver getBookingResolver(); + abstract fun analyticsComponent(): AnalyticsComponent - public abstract LocationInfoService getLocationInfoService(); + abstract fun dateTimeComponent(): DateTimeComponent - public abstract TripUpdater getTripUpdater(); + abstract val errorHandler: Consumer - public abstract A2bRoutingComponent a2bRoutingComponent(); + companion object { + private var instance: TripKit? = null - public abstract AnalyticsComponent analyticsComponent(); + fun getInstance(): TripKit { + synchronized(TripKit::class.java) { + checkNotNull(instance) { "Must initialize TripKit before using getInstance()" } + return instance!! + } + } - public abstract DateTimeComponent dateTimeComponent(); + /** + * This gives a chance to provide a custom [TripKit]. + * One idea is that we can create [DaggerTripKit] + * w/ some customized modules. + * + * + * Note that you should only use this + * when you totally understand what you're doing. + * Otherwise, just go with [.initialize] instead. + * + * @param context A [Context] to launch [FetchRegionsService]. + * @param tripKit Can be created via [DaggerTripKit]. + */ + @JvmStatic + fun initialize(context: Context, tripKit: TripKit) { + synchronized(TripKit::class.java) { + if (instance == null) { + instance = tripKit + } + scheduleAsync(context) + .subscribe({ unused: Void? -> }, instance!!.errorHandler) + } + } - public abstract Consumer getErrorHandler(); + @JvmStatic + val isInitialized: Boolean + get() = (instance != null) + + @JvmStatic + fun initialize(configs: Configs) { + synchronized(TripKit::class.java) { + if (instance == null) { + instance = DaggerTripKit.builder() + .mainModule(MainModule(configs)) + .httpClientModule( + HttpClientModule( + null, + null, + configs, + null, + null + ) + ) + .build() + JodaTimeAndroid.init(configs.context()) + GetOffAlertCache.init(configs.context()) + GeoLocation.init(configs.context()) + if (VERSION.SDK_INT >= VERSION_CODES.O) { + val channels: MutableList = ArrayList() + channels.add( + createChannel( + TripAlarmBroadcastReceiver.NOTIFICATION_CHANNEL_START_TRIP_ID, + TripAlarmBroadcastReceiver.NOTIFICATION_CHANNEL_START_TRIP + ) + ) + configs.context() + .createNotificationChannels( + channels + ) + } + } + scheduleAsync(configs.context()) + .subscribe({ unused: Void -> }, instance?.errorHandler) + } + } + } } diff --git a/TripKitAndroid/src/main/java/com/skedgo/tripkit/ModeCombinationStrategy.kt b/TripKitAndroid/src/main/java/com/skedgo/tripkit/ModeCombinationStrategy.kt index 454c3819..6d44247d 100644 --- a/TripKitAndroid/src/main/java/com/skedgo/tripkit/ModeCombinationStrategy.kt +++ b/TripKitAndroid/src/main/java/com/skedgo/tripkit/ModeCombinationStrategy.kt @@ -1,56 +1,47 @@ -package com.skedgo.tripkit; +package com.skedgo.tripkit -import com.skedgo.tripkit.common.model.TransportMode; - -import org.apache.commons.collections4.CollectionUtils; - -import java.util.Arrays; -import java.util.HashSet; -import java.util.LinkedList; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.regex.Pattern; - -import androidx.annotation.NonNull; -import io.reactivex.functions.BiFunction; +import com.skedgo.tripkit.common.model.TransportMode +import io.reactivex.functions.BiFunction +import org.apache.commons.collections4.CollectionUtils +import java.util.Arrays +import java.util.LinkedList +import java.util.regex.Pattern // TODO convert to kotlin and add coroutine version. -final class ModeCombinationStrategy implements +class ModeCombinationStrategy : BiFunction, List, List>> { - @Override - public List> apply( - @NonNull Map modeMap, - @NonNull List modeIds - ) { - final Set seenModeIds = new HashSet<>(); - final List> modeIdSets = new LinkedList<>(); + override fun apply( + modeMap: Map, + modeIds: List + ): List> { + val seenModeIds: MutableSet = HashSet() + val modeIdSets: MutableList> = LinkedList() - for (String modeId : modeIds) { + for (modeId in modeIds) { if (seenModeIds.contains(modeId)) { - continue; + continue } - final Set newSet = new HashSet<>(); - newSet.add(modeId); + val newSet: MutableSet = HashSet() + newSet.add(modeId) - TransportMode foundMode; + var foundMode: TransportMode? // For modes from modeIdentifiers, e.g. `pt_ltd_SCHOOLBUS_2029`, `pt_ltd_SCHOOLBUS_2031`, etc. // to remove numeric suffix to get base modeId for checking if exist on modeMap - String baseModeId = Pattern.compile("_\\d+$").matcher(modeId).replaceAll(""); + val baseModeId = Pattern.compile("_\\d+$").matcher(modeId).replaceAll("") // Check if the baseModeId is present in the modeMap - foundMode = modeMap.get(baseModeId); + foundMode = modeMap[baseModeId] if (foundMode != null) { - boolean shouldMerge = false; - final List implies = foundMode.getImplies(); + var shouldMerge = false + val implies = foundMode.implies?.toList() if (CollectionUtils.isNotEmpty(implies)) { - newSet.addAll(implies); + newSet.addAll(implies!!) - for (String imply : implies) { + for (imply in implies) { if (seenModeIds.contains(imply)) { - shouldMerge = true; - break; + shouldMerge = true + break } } } @@ -60,37 +51,37 @@ final class ModeCombinationStrategy implements // Then we have to find [A, C] to merge with [B, C]. // [A, C] then will become [A, B, C]. // If we don't do so, we may end up duplicate routes. - for (Set existingSet : modeIdSets) { - for (String imply : implies) { + for (existingSet in modeIdSets) { + for (imply in implies!!) { if (existingSet.contains(imply)) { - existingSet.addAll(newSet); - break; + existingSet.addAll(newSet) + break } } } } else { - modeIdSets.add(newSet); + modeIdSets.add(newSet) } } else { - modeIdSets.add(newSet); + modeIdSets.add(newSet) } - seenModeIds.addAll(newSet); + seenModeIds.addAll(newSet) } - HashSet multiModal = new HashSet<>(modeIds); - multiModal.remove(TransportMode.ID_WALK); - if (multiModal.size() > 1) { - modeIdSets.add(multiModal); + val multiModal = HashSet(modeIds) + multiModal.remove(TransportMode.ID_WALK) + if (multiModal.size > 1) { + modeIdSets.add(multiModal) } //Will remove ps_drt and wa_whe hash set since result is just the same with ps_drt mode modeIdSets.remove( - new HashSet<>( + HashSet( Arrays.asList(TransportMode.ID_PS_DRT, TransportMode.ID_WHEEL_CHAIR) ) - ); + ) - return modeIdSets; + return modeIdSets } } \ No newline at end of file diff --git a/TripKitAndroid/src/main/java/com/skedgo/tripkit/OnSubscribeLoadRegions.kt b/TripKitAndroid/src/main/java/com/skedgo/tripkit/OnSubscribeLoadRegions.kt index 69d6ca7a..b50d23c6 100644 --- a/TripKitAndroid/src/main/java/com/skedgo/tripkit/OnSubscribeLoadRegions.kt +++ b/TripKitAndroid/src/main/java/com/skedgo/tripkit/OnSubscribeLoadRegions.kt @@ -1,36 +1,28 @@ -package com.skedgo.tripkit; +package com.skedgo.tripkit -import android.database.Cursor; -import android.database.sqlite.SQLiteDatabase; -import android.database.sqlite.SQLiteOpenHelper; +import android.database.Cursor +import android.database.sqlite.SQLiteOpenHelper +import io.reactivex.ObservableEmitter +import io.reactivex.ObservableOnSubscribe -import io.reactivex.ObservableEmitter; -import io.reactivex.ObservableOnSubscribe; - -final class OnSubscribeLoadRegions implements ObservableOnSubscribe { - private final SQLiteOpenHelper databaseHelper; - - OnSubscribeLoadRegions(SQLiteOpenHelper databaseHelper) { - this.databaseHelper = databaseHelper; - } - - @Override - public void subscribe(ObservableEmitter emitter) throws Exception { - Cursor cursor = null; +class OnSubscribeLoadRegions(private val databaseHelper: SQLiteOpenHelper) : + ObservableOnSubscribe { + @Throws(Exception::class) + override fun subscribe(emitter: ObservableEmitter) { + var cursor: Cursor? = null try { - final SQLiteDatabase database = databaseHelper.getReadableDatabase(); - cursor = database.rawQuery("select * from " + Tables.REGIONS.getName(), null); - emitter.onNext(cursor); - if (!emitter.isDisposed()) { - emitter.onComplete(); + val database = databaseHelper.readableDatabase + cursor = database.rawQuery("select * from " + Tables.REGIONS.name, null) + emitter.onNext(cursor) + if (!emitter.isDisposed) { + emitter.onComplete() } - } catch (Exception e) { - emitter.onError(e); + } catch (e: Exception) { + emitter.onError(e) } finally { - if (cursor != null && !cursor.isClosed()) { - cursor.close(); + if (cursor != null && !cursor.isClosed) { + cursor.close() } } - } } \ No newline at end of file diff --git a/TripKitAndroid/src/main/java/com/skedgo/tripkit/OnSubscribeLoadTransportModes.kt b/TripKitAndroid/src/main/java/com/skedgo/tripkit/OnSubscribeLoadTransportModes.kt index c48619ec..52b5e8c3 100644 --- a/TripKitAndroid/src/main/java/com/skedgo/tripkit/OnSubscribeLoadTransportModes.kt +++ b/TripKitAndroid/src/main/java/com/skedgo/tripkit/OnSubscribeLoadTransportModes.kt @@ -1,36 +1,28 @@ -package com.skedgo.tripkit; +package com.skedgo.tripkit -import android.database.Cursor; -import android.database.sqlite.SQLiteDatabase; -import android.database.sqlite.SQLiteOpenHelper; +import android.database.Cursor +import android.database.sqlite.SQLiteOpenHelper +import io.reactivex.ObservableEmitter +import io.reactivex.ObservableOnSubscribe -import io.reactivex.ObservableEmitter; -import io.reactivex.ObservableOnSubscribe; - -final class OnSubscribeLoadTransportModes implements ObservableOnSubscribe { - private final SQLiteOpenHelper databaseHelper; - - OnSubscribeLoadTransportModes(SQLiteOpenHelper databaseHelper) { - this.databaseHelper = databaseHelper; - } - - @Override - public void subscribe(ObservableEmitter emitter) throws Exception { - Cursor cursor = null; +internal class OnSubscribeLoadTransportModes(private val databaseHelper: SQLiteOpenHelper) : + ObservableOnSubscribe { + @Throws(Exception::class) + override fun subscribe(emitter: ObservableEmitter) { + var cursor: Cursor? = null try { - final SQLiteDatabase database = databaseHelper.getReadableDatabase(); - cursor = database.rawQuery("select * from " + Tables.TRANSPORT_MODES.getName(), null); - emitter.onNext(cursor); - if (!emitter.isDisposed()) { - emitter.onComplete(); + val database = databaseHelper.readableDatabase + cursor = database.rawQuery("select * from " + Tables.TRANSPORT_MODES.name, null) + emitter.onNext(cursor) + if (!emitter.isDisposed) { + emitter.onComplete() } - } catch (Exception e) { - emitter.onError(e); + } catch (e: Exception) { + emitter.onError(e) } finally { - if (cursor != null && !cursor.isClosed()) { - cursor.close(); + if (cursor != null && !cursor.isClosed) { + cursor.close() } } - } } \ No newline at end of file diff --git a/TripKitAndroid/src/main/java/com/skedgo/tripkit/OnSubscribeSaveRegionsResponse.kt b/TripKitAndroid/src/main/java/com/skedgo/tripkit/OnSubscribeSaveRegionsResponse.kt index d315309a..40a21525 100644 --- a/TripKitAndroid/src/main/java/com/skedgo/tripkit/OnSubscribeSaveRegionsResponse.kt +++ b/TripKitAndroid/src/main/java/com/skedgo/tripkit/OnSubscribeSaveRegionsResponse.kt @@ -1,82 +1,68 @@ -package com.skedgo.tripkit; +package com.skedgo.tripkit -import android.content.ContentValues; -import android.database.sqlite.SQLiteDatabase; +import android.content.ContentValues +import android.database.sqlite.SQLiteDatabase +import com.google.gson.Gson +import com.skedgo.tripkit.common.model.TransportMode +import com.skedgo.tripkit.common.model.region.Region +import com.skedgo.tripkit.common.model.region.RegionsResponse +import io.reactivex.ObservableEmitter +import io.reactivex.ObservableOnSubscribe -import com.google.gson.Gson; -import com.skedgo.tripkit.common.model.region.Region; -import com.skedgo.tripkit.common.model.region.RegionsResponse; -import com.skedgo.tripkit.common.model.TransportMode; +class OnSubscribeSaveRegionsResponse( + private val database: SQLiteDatabase, + private val response: RegionsResponse +) : ObservableOnSubscribe { + private val gson = Gson() -import java.util.ArrayList; -import java.util.Collection; - -import androidx.annotation.NonNull; -import io.reactivex.ObservableEmitter; -import io.reactivex.ObservableOnSubscribe; - - -final class OnSubscribeSaveRegionsResponse implements ObservableOnSubscribe { - private final Gson gson = new Gson(); - private final SQLiteDatabase database; - private final RegionsResponse response; - - OnSubscribeSaveRegionsResponse( - @NonNull SQLiteDatabase database, - @NonNull RegionsResponse response) { - this.database = database; - this.response = response; - } - - @Override - public void subscribe(ObservableEmitter emitter) throws Exception { + @Throws(Exception::class) + override fun subscribe(emitter: ObservableEmitter) { try { - database.beginTransaction(); + database.beginTransaction() - database.delete(Tables.REGIONS.getName(), null, null); - database.delete(Tables.TRANSPORT_MODES.getName(), null, null); + database.delete(Tables.REGIONS.name, null, null) + database.delete(Tables.TRANSPORT_MODES.name, null, null) - final ArrayList regions = response.regions; + val regions = response.regions if (regions != null) { - for (Region region : regions) { + for (region in regions) { database.insert( - Tables.REGIONS.getName(), + Tables.REGIONS.name, null, toRegionValues(region) - ); + ) } } - final Collection modes = response.getTransportModes(); + val modes = response.transportModes if (modes != null) { - for (TransportMode mode : modes) { + for (mode in modes) { database.insert( - Tables.TRANSPORT_MODES.getName(), + Tables.TRANSPORT_MODES.name, null, toTransportModeValues(mode) - ); + ) } } - database.setTransactionSuccessful(); - emitter.onComplete(); - } catch (Exception e) { - emitter.onError(e); + database.setTransactionSuccessful() + emitter.onComplete() + } catch (e: Exception) { + emitter.onError(e) } finally { - database.endTransaction(); + database.endTransaction() } } - ContentValues toRegionValues(Region region) { - final ContentValues values = new ContentValues(1); - values.put(Tables.FIELD_JSON.name, gson.toJson(region)); - return values; + fun toRegionValues(region: Region): ContentValues { + val values = ContentValues(1) + values.put(Tables.FIELD_JSON.name, gson.toJson(region)) + return values } - ContentValues toTransportModeValues(TransportMode mode) { - final ContentValues values = new ContentValues(1); - values.put(Tables.FIELD_JSON.name, gson.toJson(mode)); - return values; + fun toTransportModeValues(mode: TransportMode): ContentValues { + val values = ContentValues(1) + values.put(Tables.FIELD_JSON.name, gson.toJson(mode)) + return values } - } \ No newline at end of file diff --git a/TripKitAndroid/src/main/java/com/skedgo/tripkit/OutOfRegionsException.kt b/TripKitAndroid/src/main/java/com/skedgo/tripkit/OutOfRegionsException.kt index e3cc3f45..d3f6b910 100644 --- a/TripKitAndroid/src/main/java/com/skedgo/tripkit/OutOfRegionsException.kt +++ b/TripKitAndroid/src/main/java/com/skedgo/tripkit/OutOfRegionsException.kt @@ -1,25 +1,15 @@ -package com.skedgo.tripkit; - -import androidx.annotation.Nullable; - -public final class OutOfRegionsException extends RuntimeException { - private final double latitude; - private final double longitude; - - public OutOfRegionsException( - @Nullable String detailMessage, - double latitude, - double longitude) { - super(detailMessage); - this.latitude = latitude; - this.longitude = longitude; - } - - public double latitude() { - return latitude; +package com.skedgo.tripkit + +class OutOfRegionsException( + detailMessage: String?, + private val latitude: Double, + private val longitude: Double +) : RuntimeException(detailMessage) { + fun latitude(): Double { + return latitude } - public double longitude() { - return longitude; + fun longitude(): Double { + return longitude } } diff --git a/TripKitAndroid/src/main/java/com/skedgo/tripkit/PeriodicRealTimeTripUpdateReceiver.kt b/TripKitAndroid/src/main/java/com/skedgo/tripkit/PeriodicRealTimeTripUpdateReceiver.kt index 600acbf7..4622b318 100644 --- a/TripKitAndroid/src/main/java/com/skedgo/tripkit/PeriodicRealTimeTripUpdateReceiver.kt +++ b/TripKitAndroid/src/main/java/com/skedgo/tripkit/PeriodicRealTimeTripUpdateReceiver.kt @@ -1,99 +1,86 @@ -package com.skedgo.tripkit; - -import com.skedgo.TripKit; -import com.skedgo.tripkit.routing.Trip; -import com.skedgo.tripkit.routing.TripGroup; - -import org.immutables.value.Value; -import org.reactivestreams.Publisher; - -import java.util.concurrent.TimeUnit; -import java.util.concurrent.atomic.AtomicReference; - -import io.reactivex.BackpressureStrategy; -import io.reactivex.Flowable; -import io.reactivex.FlowableTransformer; -import io.reactivex.Observable; -import io.reactivex.functions.Consumer; -import io.reactivex.functions.Function; -import io.reactivex.schedulers.Schedulers; -import io.reactivex.subjects.PublishSubject; -import kotlin.Pair; - -import static org.immutables.value.Value.Style.BuilderVisibility.PACKAGE; -import static org.immutables.value.Value.Style.ImplementationVisibility.PRIVATE; - -@Value.Immutable -@Value.Style(visibility = PRIVATE, builderVisibility = PACKAGE) -public abstract class PeriodicRealTimeTripUpdateReceiver implements RealTimeTripUpdateReceiver { - private final PublishSubject stop = PublishSubject.create(); - - public static Builder builder() { - return new PeriodicRealTimeTripUpdateReceiverBuilder() - .tripUpdater(TripKit.getInstance().getTripUpdater()); - } - - @Override - public Flowable> startAsync() { - return Flowable.interval(initialDelay(), period(), timeUnit(), Schedulers.trampoline()) - .map(new Function() { - @Override - public String apply(Long aLong) { - return group().getDisplayTrip().getUpdateURL(); - } - }) +package com.skedgo.tripkit + +import com.skedgo.TripKit +import com.skedgo.tripkit.routing.Trip +import com.skedgo.tripkit.routing.TripGroup +import io.reactivex.BackpressureStrategy.BUFFER +import io.reactivex.Flowable +import io.reactivex.Observable +import io.reactivex.functions.Consumer +import io.reactivex.functions.Function +import io.reactivex.schedulers.Schedulers +import io.reactivex.subjects.PublishSubject +import org.immutables.value.Value.Immutable +import org.immutables.value.Value.Style +import org.immutables.value.Value.Style.BuilderVisibility.PACKAGE +import org.immutables.value.Value.Style.ImplementationVisibility.PRIVATE +import java.util.concurrent.TimeUnit +import java.util.concurrent.atomic.AtomicReference + +@Immutable +@Style(visibility = PRIVATE, builderVisibility = PACKAGE) +abstract class PeriodicRealTimeTripUpdateReceiver : RealTimeTripUpdateReceiver { + private val stop = PublishSubject.create() + + override fun startAsync(): Flowable> { + return Flowable.interval( + initialDelay().toLong(), + period().toLong(), + timeUnit(), + Schedulers.trampoline() + ) + .map { group().displayTrip!!.updateURL!! } .onBackpressureDrop() - .compose(new FlowableTransformer() { - public Publisher apply(Flowable updateUrl) { - final AtomicReference url = new AtomicReference(); - return updateUrl - .flatMap((Function>) s -> { - final String lastUrl = url.get(); - return tripUpdater().getUpdateAsync(lastUrl != null ? lastUrl : s) - .onErrorResumeNext(Observable.empty()).toFlowable(BackpressureStrategy.BUFFER); - }) - .doOnNext(new Consumer() { - @Override - public void accept(Trip trip) { - url.set(trip.getUpdateURL()); - } - }); - } + .compose { updateUrl -> + val url = AtomicReference() + updateUrl + .flatMap { s: String -> + val lastUrl = url.get() + tripUpdater().getUpdateAsync(lastUrl ?: s) + .onErrorResumeNext(Observable.empty()).toFlowable(BUFFER) + } + .doOnNext { trip -> url.set(trip.updateURL) } + } + .map>(Function> { trip -> + Pair( + trip, + group() + ) }) - .map(new Function>() { - @Override - public Pair apply(Trip trip) { - return new Pair<>(trip, group()); - } - }) - .takeUntil(stop.toFlowable(BackpressureStrategy.BUFFER)) - .subscribeOn(Schedulers.io()); + .takeUntil(stop.toFlowable(BUFFER)) + .subscribeOn(Schedulers.io()) } - @Override - public void stop() { - stop.onNext(new Object()); + override fun stop() { + stop.onNext(Any()) } - abstract TripUpdater tripUpdater(); + abstract fun tripUpdater(): TripUpdater + + abstract fun group(): TripGroup - abstract TripGroup group(); + abstract fun initialDelay(): Int - abstract int initialDelay(); + abstract fun period(): Int - abstract int period(); + abstract fun timeUnit(): TimeUnit - abstract TimeUnit timeUnit(); + interface Builder { + fun group(group: TripGroup?): Builder - public interface Builder { - Builder group(TripGroup group); + fun initialDelay(initialDelay: Int): Builder - Builder initialDelay(int initialDelay); + fun period(period: Int): Builder - Builder period(int period); + fun timeUnit(timeUnit: TimeUnit): Builder - Builder timeUnit(TimeUnit timeUnit); + fun build(): RealTimeTripUpdateReceiver + } - RealTimeTripUpdateReceiver build(); + companion object { + fun builder(): Builder { + return PeriodicRealTimeTripUpdateReceiverBuilder() + .tripUpdater(TripKit.getInstance().tripUpdater) + } } } diff --git a/TripKitAndroid/src/main/java/com/skedgo/tripkit/RealTimeTripUpdateReceiver.kt b/TripKitAndroid/src/main/java/com/skedgo/tripkit/RealTimeTripUpdateReceiver.kt index 840b6560..0ff55698 100644 --- a/TripKitAndroid/src/main/java/com/skedgo/tripkit/RealTimeTripUpdateReceiver.kt +++ b/TripKitAndroid/src/main/java/com/skedgo/tripkit/RealTimeTripUpdateReceiver.kt @@ -1,14 +1,12 @@ -package com.skedgo.tripkit; +package com.skedgo.tripkit +import com.skedgo.tripkit.routing.Trip +import com.skedgo.tripkit.routing.TripGroup +import io.reactivex.Flowable -import com.skedgo.tripkit.routing.Trip; -import com.skedgo.tripkit.routing.TripGroup; -import io.reactivex.Flowable; -import kotlin.Pair; +interface RealTimeTripUpdateReceiver { + fun startAsync(): Flowable> -public interface RealTimeTripUpdateReceiver { - Flowable> startAsync(); - - void stop(); + fun stop() } \ No newline at end of file diff --git a/TripKitAndroid/src/main/java/com/skedgo/tripkit/RegionServiceImpl.kt b/TripKitAndroid/src/main/java/com/skedgo/tripkit/RegionServiceImpl.kt index 025958c8..579001e5 100644 --- a/TripKitAndroid/src/main/java/com/skedgo/tripkit/RegionServiceImpl.kt +++ b/TripKitAndroid/src/main/java/com/skedgo/tripkit/RegionServiceImpl.kt @@ -64,7 +64,7 @@ internal class RegionServiceImpl( override fun getCitiesAsync(): Observable = getRegionsAsync() .flatMap { regions -> Observable.fromIterable(regions) } - .compose(com.skedgo.tripkit.Utils.getCities()) + .compose(Utils.cities) override fun getCitiesByNameAsync(name: String?): Observable = getCitiesAsync().filter(com.skedgo.tripkit.Utils.matchCityName(name)) diff --git a/TripKitAndroid/src/main/java/com/skedgo/tripkit/RouteServiceImpl.kt b/TripKitAndroid/src/main/java/com/skedgo/tripkit/RouteServiceImpl.kt index 9c62e957..480a00b0 100644 --- a/TripKitAndroid/src/main/java/com/skedgo/tripkit/RouteServiceImpl.kt +++ b/TripKitAndroid/src/main/java/com/skedgo/tripkit/RouteServiceImpl.kt @@ -62,7 +62,7 @@ internal class RouteServiceImpl( fun getParamsByPreferences(): Map { val map = ArrayMap() if (tripPreferences != null) { - if (tripPreferences.isConcessionPricingPreferred) { + if (tripPreferences.isConcessionPricingPreferred()) { map["conc"] = true } } diff --git a/TripKitAndroid/src/main/java/com/skedgo/tripkit/ServiceExtras.kt b/TripKitAndroid/src/main/java/com/skedgo/tripkit/ServiceExtras.kt index 8b541baa..2ff01757 100644 --- a/TripKitAndroid/src/main/java/com/skedgo/tripkit/ServiceExtras.kt +++ b/TripKitAndroid/src/main/java/com/skedgo/tripkit/ServiceExtras.kt @@ -1,20 +1,8 @@ -package com.skedgo.tripkit; +package com.skedgo.tripkit -import com.skedgo.tripkit.common.model.stop.ServiceStop; +import com.skedgo.tripkit.common.model.stop.ServiceStop -import java.util.List; - -import androidx.annotation.Nullable; - -public final class ServiceExtras { - @Nullable - public final String platform; - @Nullable - public final List stops; - - public ServiceExtras(@Nullable String platform, - @Nullable List stops) { - this.platform = platform; - this.stops = stops; - } -} \ No newline at end of file +class ServiceExtras( + val platform: String?, + val stops: List? +) \ No newline at end of file diff --git a/TripKitAndroid/src/main/java/com/skedgo/tripkit/Tables.kt b/TripKitAndroid/src/main/java/com/skedgo/tripkit/Tables.kt index c1a320b8..8aabbcb2 100644 --- a/TripKitAndroid/src/main/java/com/skedgo/tripkit/Tables.kt +++ b/TripKitAndroid/src/main/java/com/skedgo/tripkit/Tables.kt @@ -1,20 +1,19 @@ -package com.skedgo.tripkit; +package com.skedgo.tripkit +import com.skedgo.sqlite.DatabaseField +import com.skedgo.sqlite.DatabaseTable -import com.skedgo.sqlite.DatabaseField; -import com.skedgo.sqlite.DatabaseTable; -final class Tables { - public static final DatabaseField FIELD_JSON = new DatabaseField("json", "TEXT"); - public static final DatabaseTable TRANSPORT_MODES = new DatabaseTable( +internal object Tables { + val FIELD_JSON: DatabaseField = DatabaseField("json", "TEXT") + @JvmField + val TRANSPORT_MODES: DatabaseTable = DatabaseTable( "transport_modes", - new DatabaseField[]{FIELD_JSON} - ); - public static final DatabaseTable REGIONS = new DatabaseTable( + arrayOf(FIELD_JSON) + ) + @JvmField + val REGIONS: DatabaseTable = DatabaseTable( "regions", - new DatabaseField[]{FIELD_JSON} - ); - - private Tables() { - } + arrayOf(FIELD_JSON) + ) } \ No newline at end of file diff --git a/TripKitAndroid/src/main/java/com/skedgo/tripkit/TemporaryUrlApi.kt b/TripKitAndroid/src/main/java/com/skedgo/tripkit/TemporaryUrlApi.kt index 62c459fa..494eb4eb 100644 --- a/TripKitAndroid/src/main/java/com/skedgo/tripkit/TemporaryUrlApi.kt +++ b/TripKitAndroid/src/main/java/com/skedgo/tripkit/TemporaryUrlApi.kt @@ -1,26 +1,22 @@ -package com.skedgo.tripkit; +package com.skedgo.tripkit -import com.skedgo.tripkit.routing.RoutingResponse; -import com.skedgo.tripkit.routing.Trip; - -import java.util.Map; - -import io.reactivex.Observable; -import retrofit2.http.GET; -import retrofit2.http.QueryMap; -import retrofit2.http.Url; +import com.skedgo.tripkit.routing.RoutingResponse +import io.reactivex.Observable +import retrofit2.http.GET +import retrofit2.http.QueryMap +import retrofit2.http.Url /** - * Handles downloading trip via {@link Trip#getTemporaryURL()}. + * Handles downloading trip via [Trip.getTemporaryURL]. */ -public interface TemporaryUrlApi { +interface TemporaryUrlApi { /** - * @param url Should be {@link Trip#getTemporaryURL()}. - * @param config Described in Default configuration parameters. + * @param url Should be [Trip.getTemporaryURL]. + * @param config Described in [Default configuration parameters](https://redmine.buzzhives.com/projects/buzzhives/wiki/Main_API_formats#Default-configuration-parameters). */ @GET - Observable requestTemporaryUrlAsync( - @Url String url, - @QueryMap Map config - ); + fun requestTemporaryUrlAsync( + @Url url: String?, + @QueryMap config: Map + ): Observable } \ No newline at end of file diff --git a/TripKitAndroid/src/main/java/com/skedgo/tripkit/TransitService.kt b/TripKitAndroid/src/main/java/com/skedgo/tripkit/TransitService.kt index 0160c5a8..8eae7970 100644 --- a/TripKitAndroid/src/main/java/com/skedgo/tripkit/TransitService.kt +++ b/TripKitAndroid/src/main/java/com/skedgo/tripkit/TransitService.kt @@ -1,26 +1,24 @@ -package com.skedgo.tripkit; +package com.skedgo.tripkit -import com.google.gson.annotations.JsonAdapter; -import com.skedgo.tripkit.routing.RealTimeVehicle; -import com.skedgo.tripkit.routing.Shape; +import com.google.gson.annotations.JsonAdapter +import com.skedgo.tripkit.routing.RealTimeVehicle +import com.skedgo.tripkit.routing.Shape +import org.immutables.gson.Gson.TypeAdapters +import org.immutables.value.Value.Immutable +import org.immutables.value.Value.Style -import org.immutables.gson.Gson; -import org.immutables.value.Value; +@Immutable +@TypeAdapters +@JsonAdapter( + GsonAdaptersTransitService::class +) +@Style(passAnnotations = [JsonAdapter::class]) +interface TransitService { + fun shapes(): List -import java.util.List; + fun realTimeStatus(): String -@Value.Immutable -@Gson.TypeAdapters -@JsonAdapter(GsonAdaptersTransitService.class) -@Value.Style(passAnnotations = JsonAdapter.class) -public interface TransitService { - - List shapes(); - - String realTimeStatus(); - - RealTimeVehicle realtimeVehicle(); - - List realtimeAlternativeVehicle(); + fun realtimeVehicle(): RealTimeVehicle + fun realtimeAlternativeVehicle(): List } \ No newline at end of file diff --git a/TripKitAndroid/src/main/java/com/skedgo/tripkit/TripKitConfigs.kt b/TripKitAndroid/src/main/java/com/skedgo/tripkit/TripKitConfigs.kt index e16cb780..91f84aa3 100644 --- a/TripKitAndroid/src/main/java/com/skedgo/tripkit/TripKitConfigs.kt +++ b/TripKitAndroid/src/main/java/com/skedgo/tripkit/TripKitConfigs.kt @@ -1,36 +1,37 @@ -package com.skedgo.tripkit; +package com.skedgo.tripkit -import org.immutables.value.Value; +import org.immutables.value.Value.Default +import org.immutables.value.Value.Immutable -@Value.Immutable -public abstract class TripKitConfigs implements Configs { - public static ImmutableTripKitConfigs.Builder builder() { - return ImmutableTripKitConfigs.builder(); +@Immutable +abstract class TripKitConfigs : Configs { + companion object { + fun builder(): ImmutableTripKitConfigs.Builder { + return ImmutableTripKitConfigs.builder() + } } - - @Value.Default - public boolean debuggable() { - return false; + @Default + override fun debuggable(): Boolean { + return false } - @Value.Default - public boolean isUuidOptedOut() { - return false; + @Default + override fun isUuidOptedOut(): Boolean { + return false } - @Value.Default - public boolean hideTripMetrics() { - return false; + @Default + override fun hideTripMetrics(): Boolean { + return false } - @Value.Default - public boolean showReportProblemOnTripAction() { - return false; + @Default + override fun showReportProblemOnTripAction(): Boolean { + return false } - @Value.Default - public boolean showOperatorNames() { - return false; + @Default + override fun showOperatorNames(): Boolean { + return false } - } diff --git a/TripKitAndroid/src/main/java/com/skedgo/tripkit/TripPreferences.kt b/TripKitAndroid/src/main/java/com/skedgo/tripkit/TripPreferences.kt index 61d8d8ff..585436a0 100644 --- a/TripKitAndroid/src/main/java/com/skedgo/tripkit/TripPreferences.kt +++ b/TripKitAndroid/src/main/java/com/skedgo/tripkit/TripPreferences.kt @@ -1,33 +1,30 @@ -package com.skedgo.tripkit; +package com.skedgo.tripkit -import com.skedgo.tripkit.data.tsp.RegionInfo; +import io.reactivex.Observable -import io.reactivex.Observable; +interface TripPreferences { -public interface TripPreferences { /** - * This option should be used when {@link RegionInfo#supportsConcessionPricing()} is true. + * This option should be used when [RegionInfo.supportsConcessionPricing] is true. */ - boolean isConcessionPricingPreferred(); + fun isConcessionPricingPreferred(): Boolean - void setConcessionPricingPreferred(boolean isConcessionPricingPreferred); + fun setConcessionPricingPreferred(isConcessionPricingPreferred: Boolean) /** - * @return An {@link Observable} which emits value of {@link #isConcessionPricingPreferred()} - * when it has changed. + * An [Observable] which emits the value of [isConcessionPricingPreferred] when it changes. */ - Observable whenConcessionPricingPreferenceChanges(); + fun whenConcessionPricingPreferenceChanges(): Observable /** - * This option should be used when {@link RegionInfo#transitWheelchairAccessibility()} is true. + * This option should be used when [RegionInfo.transitWheelchairAccessibility] is true. */ - boolean isWheelchairPreferred(); + fun isWheelchairPreferred(): Boolean - void setWheelchairPreferred(boolean isWheelchairPreferred); + fun setWheelchairPreferred(isWheelchairPreferred: Boolean) /** - * @return An {@link Observable} which emits value of {@link #isWheelchairPreferred()} - * when it has changed. + * An [Observable] which emits the value of [isWheelchairPreferred] when it changes. */ - Observable whenWheelchairPreferenceChanges(); + fun whenWheelchairPreferenceChanges(): Observable } diff --git a/TripKitAndroid/src/main/java/com/skedgo/tripkit/Utils.kt b/TripKitAndroid/src/main/java/com/skedgo/tripkit/Utils.kt index 8b8b1d8e..45fdd33d 100644 --- a/TripKitAndroid/src/main/java/com/skedgo/tripkit/Utils.kt +++ b/TripKitAndroid/src/main/java/com/skedgo/tripkit/Utils.kt @@ -1,104 +1,80 @@ -package com.skedgo.tripkit; +package com.skedgo.tripkit -import android.text.TextUtils; +import android.text.TextUtils +import com.skedgo.tripkit.common.model.TransportMode +import com.skedgo.tripkit.common.model.location.Location +import com.skedgo.tripkit.common.model.region.Region +import com.skedgo.tripkit.common.model.region.Region.City +import io.reactivex.Observable +import io.reactivex.ObservableTransformer +import io.reactivex.functions.Function +import io.reactivex.functions.Predicate +import org.apache.commons.collections4.CollectionUtils +import java.util.Locale -import com.skedgo.tripkit.common.model.location.Location; -import com.skedgo.tripkit.common.model.region.Region; -import com.skedgo.tripkit.common.model.TransportMode; - -import org.apache.commons.collections4.CollectionUtils; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import androidx.annotation.NonNull; -import androidx.annotation.Nullable; -import io.reactivex.Observable; -import io.reactivex.ObservableTransformer; -import io.reactivex.functions.Function; -import io.reactivex.functions.Predicate; - -final class Utils { - private Utils() { - } - - @NonNull - static ObservableTransformer getCities() { - return new ObservableTransformer() { - @Override - public Observable apply(Observable observable) { +object Utils { + @JvmStatic + val cities: ObservableTransformer + get() = object : ObservableTransformer { + override fun apply(observable: Observable): Observable { return observable - .flatMap((Function>) region -> { - final ArrayList cities = region.getCities(); + .flatMap(Function { region: Region -> + val cities = region.cities if (cities != null) { - return Observable.fromIterable(cities); + return@Function Observable.fromIterable(cities) } else { - return Observable.empty(); + return@Function Observable.empty() } }) - .map(city -> city); + .map { city: City -> city } } - }; - } + } /** * @return True for either null or "" string or string having only spaces. * Also true if the city name contains the keyword. Otherwise, false. */ - @NonNull - static Predicate matchCityName(@Nullable final String name) { - final String lowerCaseName = name != null ? name.toLowerCase() : null; - return city -> { - final String name1 = city.getName(); - return isNullOrEmpty(lowerCaseName) || - (name1 != null && name1.toLowerCase().contains(lowerCaseName)); - }; + @JvmStatic + fun matchCityName(name: String?): Predicate { + val lowerCaseName = name?.lowercase(Locale.getDefault()) + return Predicate { city: Location -> + val name1 = city.name + isNullOrEmpty(lowerCaseName) || + (name1 != null && name1.lowercase(Locale.getDefault()).contains( + lowerCaseName.orEmpty() + )) + } } - static boolean isNullOrEmpty(CharSequence s) { - return s == null || TextUtils.getTrimmedLength(s) == 0; + fun isNullOrEmpty(s: CharSequence?): Boolean { + return s == null || TextUtils.getTrimmedLength(s) == 0 } - @NonNull - static Function, List> findModesByIds(final List modeIds) { - return modeMap -> { - final List modes = new ArrayList<>(modeIds.size()); - for (String modeId : modeIds) { - final TransportMode mode = modeMap.get(modeId); + fun findModesByIds(modeIds: List): Function, List> { + return Function { modeMap: Map -> + val modes: MutableList = ArrayList(modeIds.size) + for (modeId in modeIds) { + val mode = modeMap[modeId] if (mode != null) { - modes.add(mode); + modes.add(mode) } } - - return modes; - }; + modes + } } - @NonNull - static Function, Map> toModeMap() { - return new Function, Map>() { - @Override - public Map apply(List modes) { - final HashMap modeMap = new HashMap<>(); - if (modes != null) { - for (TransportMode mode : modes) { - modeMap.put(mode.getId(), mode); - } - } - - return modeMap; + @JvmStatic + fun toModeMap(): Function, Map> { + return Function, Map> { modes -> + val modeMap = HashMap() + for (mode in modes) { + modeMap[mode.id] = mode } - }; + modeMap + } } - static Predicate> isNotEmpty() { - return new Predicate>() { - @Override - public boolean test(List items) { - return CollectionUtils.isNotEmpty(items); - } - }; + fun isNotEmpty(): Predicate> { + return Predicate> { items -> CollectionUtils.isNotEmpty(items) } } } \ No newline at end of file diff --git a/TripKitAndroid/src/main/java/com/skedgo/tripkit/UuidProvider.kt b/TripKitAndroid/src/main/java/com/skedgo/tripkit/UuidProvider.kt index fd87e63f..f777449c 100644 --- a/TripKitAndroid/src/main/java/com/skedgo/tripkit/UuidProvider.kt +++ b/TripKitAndroid/src/main/java/com/skedgo/tripkit/UuidProvider.kt @@ -1,32 +1,26 @@ -package com.skedgo.tripkit; +package com.skedgo.tripkit -import android.content.SharedPreferences; +import android.content.SharedPreferences +import java.util.UUID +import java.util.concurrent.Callable +import javax.inject.Inject +import javax.inject.Named -import java.util.UUID; -import java.util.concurrent.Callable; - -import javax.inject.Inject; -import javax.inject.Named; - - -class UuidProvider implements Callable { - private static final String KEY_UUID = "UUID"; - private final SharedPreferences preferences; - - @Inject - UuidProvider(@Named("TripKitPrefs") SharedPreferences preferences) { - this.preferences = preferences; - } - - @Override - public synchronized String call() { - final String uuid = preferences.getString(KEY_UUID, null); +internal class UuidProvider @Inject constructor(@param:Named("TripKitPrefs") private val preferences: SharedPreferences) : + Callable { + @Synchronized + override fun call(): String { + val uuid = preferences.getString(KEY_UUID, null) if (uuid != null) { - return uuid; + return uuid } else { - final String newUuid = UUID.randomUUID().toString(); - preferences.edit().putString(KEY_UUID, newUuid).apply(); - return newUuid; + val newUuid = UUID.randomUUID().toString() + preferences.edit().putString(KEY_UUID, newUuid).apply() + return newUuid } } + + companion object { + private const val KEY_UUID = "UUID" + } } \ No newline at end of file From b2e6ddaca5cd053e2b30125bcbdc02923e16bba0 Mon Sep 17 00:00:00 2001 From: Michael Angelo Reyes Date: Mon, 11 Nov 2024 14:56:52 +0800 Subject: [PATCH 15/25] [22682] - [TripGov5] update affected classes --- .../java/com/skedgo/tripkit/booking/ui/BookingUiModule.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/trip-kit-booking-ui/src/main/java/com/skedgo/tripkit/booking/ui/BookingUiModule.java b/trip-kit-booking-ui/src/main/java/com/skedgo/tripkit/booking/ui/BookingUiModule.java index 488d7018..e1549a6a 100644 --- a/trip-kit-booking-ui/src/main/java/com/skedgo/tripkit/booking/ui/BookingUiModule.java +++ b/trip-kit-booking-ui/src/main/java/com/skedgo/tripkit/booking/ui/BookingUiModule.java @@ -37,7 +37,7 @@ Resources resources() { @Provides OkHttpClient httpClient() { - return TripKit.getInstance().getOkHttpClient3(); + return TripKit.Companion.getInstance().getOkHttpClient3(); } @Provides From c0ec20867b573f1176873cd2bfc8c1f0e2a6a7a6 Mon Sep 17 00:00:00 2001 From: Michael Angelo Reyes Date: Tue, 12 Nov 2024 00:26:04 +0800 Subject: [PATCH 16/25] Rename .java to .kt --- .../tripkit/{AndroidGeocoderTest.java => AndroidGeocoderTest.kt} | 0 ...{RegionDatabaseHelperTest.java => RegionDatabaseHelperTest.kt} | 0 2 files changed, 0 insertions(+), 0 deletions(-) rename TripKitAndroid/src/androidTest/java/com/skedgo/tripkit/{AndroidGeocoderTest.java => AndroidGeocoderTest.kt} (100%) rename TripKitAndroid/src/androidTest/java/com/skedgo/tripkit/{RegionDatabaseHelperTest.java => RegionDatabaseHelperTest.kt} (100%) diff --git a/TripKitAndroid/src/androidTest/java/com/skedgo/tripkit/AndroidGeocoderTest.java b/TripKitAndroid/src/androidTest/java/com/skedgo/tripkit/AndroidGeocoderTest.kt similarity index 100% rename from TripKitAndroid/src/androidTest/java/com/skedgo/tripkit/AndroidGeocoderTest.java rename to TripKitAndroid/src/androidTest/java/com/skedgo/tripkit/AndroidGeocoderTest.kt diff --git a/TripKitAndroid/src/androidTest/java/com/skedgo/tripkit/RegionDatabaseHelperTest.java b/TripKitAndroid/src/androidTest/java/com/skedgo/tripkit/RegionDatabaseHelperTest.kt similarity index 100% rename from TripKitAndroid/src/androidTest/java/com/skedgo/tripkit/RegionDatabaseHelperTest.java rename to TripKitAndroid/src/androidTest/java/com/skedgo/tripkit/RegionDatabaseHelperTest.kt From 84ce247761a5aad976364dc086f3b54002456f39 Mon Sep 17 00:00:00 2001 From: Michael Angelo Reyes Date: Tue, 12 Nov 2024 00:26:05 +0800 Subject: [PATCH 17/25] [22682] - [TripKit] convert AndroidGeocoderTest.java to kotlin - [TripKit] convert RegionDatabaseHelperTest.java to kotlin --- .../com/skedgo/tripkit/AndroidGeocoderTest.kt | 37 ++++----- .../tripkit/RegionDatabaseHelperTest.kt | 80 +++++++++---------- .../bookingproviders/SmsBookingResolver.kt | 2 +- 3 files changed, 54 insertions(+), 65 deletions(-) diff --git a/TripKitAndroid/src/androidTest/java/com/skedgo/tripkit/AndroidGeocoderTest.kt b/TripKitAndroid/src/androidTest/java/com/skedgo/tripkit/AndroidGeocoderTest.kt index 04f55cbb..48dd0085 100644 --- a/TripKitAndroid/src/androidTest/java/com/skedgo/tripkit/AndroidGeocoderTest.kt +++ b/TripKitAndroid/src/androidTest/java/com/skedgo/tripkit/AndroidGeocoderTest.kt @@ -1,30 +1,27 @@ -package com.skedgo.tripkit; +package com.skedgo.tripkit -import com.skedgo.tripkit.geocoding.ReverseGeocodable; +import androidx.test.InstrumentationRegistry +import androidx.test.ext.junit.runners.AndroidJUnit4 +import com.skedgo.tripkit.geocoding.ReverseGeocodable +import org.junit.Before +import org.junit.Test +import org.junit.runner.RunWith -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; - -import androidx.test.InstrumentationRegistry; -import androidx.test.ext.junit.runners.AndroidJUnit4; -import io.reactivex.observers.TestObserver; - -@RunWith(AndroidJUnit4.class) -public class AndroidGeocoderTest { - private ReverseGeocodable factory; +@RunWith(AndroidJUnit4::class) +class AndroidGeocoderTest { + private var factory: ReverseGeocodable? = null @Before - public void before() { - factory = new AndroidGeocoder(InstrumentationRegistry.getInstrumentation().getTargetContext()); + fun before() { + factory = AndroidGeocoder(InstrumentationRegistry.getInstrumentation().targetContext) } /* This test may fail if devices don't have network. */ @Test - public void reverseGeocodeInCA() { - final TestObserver subscriber = factory.getAddress(33.956252, -118.217896).test(); - subscriber.awaitTerminalEvent(); - subscriber.assertNoErrors(); - subscriber.assertValue("8677 Evergreen Ave, South Gate, CA 90280, USA"); + fun reverseGeocodeInCA() { + val subscriber = factory!!.getAddress(33.956252, -118.217896).test() + subscriber.awaitTerminalEvent() + subscriber.assertNoErrors() + subscriber.assertValue("8677 Evergreen Ave, South Gate, CA 90280, USA") } } \ No newline at end of file diff --git a/TripKitAndroid/src/androidTest/java/com/skedgo/tripkit/RegionDatabaseHelperTest.kt b/TripKitAndroid/src/androidTest/java/com/skedgo/tripkit/RegionDatabaseHelperTest.kt index a881f44d..7a2ece3d 100644 --- a/TripKitAndroid/src/androidTest/java/com/skedgo/tripkit/RegionDatabaseHelperTest.kt +++ b/TripKitAndroid/src/androidTest/java/com/skedgo/tripkit/RegionDatabaseHelperTest.kt @@ -1,63 +1,55 @@ -package com.skedgo.tripkit; - -import android.content.Context; -import android.database.Cursor; -import android.database.sqlite.SQLiteDatabase; - -import com.skedgo.sqlite.DatabaseTable; - -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; - -import java.io.File; - -import androidx.test.InstrumentationRegistry; -import androidx.test.ext.junit.runners.AndroidJUnit4; - -import static junit.framework.Assert.assertTrue; - -@RunWith(AndroidJUnit4.class) -public class RegionDatabaseHelperTest { - private RegionDatabaseHelper databaseHelper; - private String databaseName; - private Context context; +package com.skedgo.tripkit + +import android.content.Context +import androidx.test.InstrumentationRegistry +import androidx.test.ext.junit.runners.AndroidJUnit4 +import com.skedgo.sqlite.DatabaseTable +import junit.framework.Assert +import org.junit.After +import org.junit.Before +import org.junit.Test +import org.junit.runner.RunWith + +@RunWith(AndroidJUnit4::class) +class RegionDatabaseHelperTest { + private var databaseHelper: RegionDatabaseHelper? = null + private var databaseName: String? = null + private var context: Context? = null @Before - public void before() { - databaseName = RegionDatabaseHelperTest.class.getSimpleName(); - context = InstrumentationRegistry.getInstrumentation().getTargetContext(); - databaseHelper = new RegionDatabaseHelper( + fun before() { + databaseName = RegionDatabaseHelperTest::class.java.simpleName + context = InstrumentationRegistry.getInstrumentation().targetContext + databaseHelper = RegionDatabaseHelper( context, databaseName - ); + ) // To trigger table creation. - databaseHelper.getReadableDatabase().close(); + databaseHelper!!.readableDatabase.close() } @Test - public void RegionsTableExists() { - checkTable(Tables.REGIONS); + fun RegionsTableExists() { + checkTable(Tables.REGIONS) } @Test - public void TransportModesTableExists() { - checkTable(Tables.TRANSPORT_MODES); + fun TransportModesTableExists() { + checkTable(Tables.TRANSPORT_MODES) } @After - public void after() { - databaseHelper.close(); - final File databasePath = context.getDatabasePath(databaseName); - assertTrue(databasePath.delete()); + fun after() { + databaseHelper?.close() + val databasePath = context!!.getDatabasePath(databaseName) + Assert.assertTrue(databasePath.delete()) } - private void checkTable(DatabaseTable table) { - final SQLiteDatabase database = databaseHelper.getReadableDatabase(); - final Cursor cursor = database.rawQuery("SELECT * FROM " + table.getName(), null); - cursor.close(); - database.close(); + private fun checkTable(table: DatabaseTable) { + val database = databaseHelper!!.readableDatabase + val cursor = database.rawQuery("SELECT * FROM " + table.name, null) + cursor.close() + database.close() } } \ No newline at end of file diff --git a/TripKitAndroid/src/main/java/com/skedgo/tripkit/bookingproviders/SmsBookingResolver.kt b/TripKitAndroid/src/main/java/com/skedgo/tripkit/bookingproviders/SmsBookingResolver.kt index 5a3b49f3..f6e1d137 100644 --- a/TripKitAndroid/src/main/java/com/skedgo/tripkit/bookingproviders/SmsBookingResolver.kt +++ b/TripKitAndroid/src/main/java/com/skedgo/tripkit/bookingproviders/SmsBookingResolver.kt @@ -6,7 +6,7 @@ import com.skedgo.tripkit.BookingAction import com.skedgo.tripkit.ExternalActionParams import io.reactivex.Observable -internal class SmsBookingResolver : BookingResolver { +class SmsBookingResolver : BookingResolver { override fun performExternalActionAsync(params: ExternalActionParams): Observable { val action = BookingAction.builder() .bookingProvider(BookingResolver.SMS) From 566fa2c601c88700446d6680582ec1d9d0ff6d9d Mon Sep 17 00:00:00 2001 From: Michael Angelo Reyes Date: Tue, 12 Nov 2024 00:30:00 +0800 Subject: [PATCH 18/25] Rename .java to .kt --- .../{RouteServiceImplTest.java => RouteServiceImplTest.kt} | 0 .../test/java/com/skedgo/tripkit/{UtilsTest.java => UtilsTest.kt} | 0 ...electBestDisplayTripTest.java => SelectBestDisplayTripTest.kt} | 0 .../alerts/{RealtimeAlertApiTest.java => RealtimeAlertApiTest.kt} | 0 ...{RealtimeAlertServiceTest.java => RealtimeAlertServiceTest.kt} | 0 .../{BookingResolverImplTest.java => BookingResolverImplTest.kt} | 0 .../{SmsBookingResolverTest.java => SmsBookingResolverTest.kt} | 0 .../tripkit/tsp/{RegionInfoApiTest.java => RegionInfoApiTest.kt} | 0 .../tsp/{RegionInfoServiceTest.java => RegionInfoServiceTest.kt} | 0 9 files changed, 0 insertions(+), 0 deletions(-) rename TripKitAndroid/src/test/java/com/skedgo/tripkit/{RouteServiceImplTest.java => RouteServiceImplTest.kt} (100%) rename TripKitAndroid/src/test/java/com/skedgo/tripkit/{UtilsTest.java => UtilsTest.kt} (100%) rename TripKitAndroid/src/test/java/com/skedgo/tripkit/a2brouting/{SelectBestDisplayTripTest.java => SelectBestDisplayTripTest.kt} (100%) rename TripKitAndroid/src/test/java/com/skedgo/tripkit/alerts/{RealtimeAlertApiTest.java => RealtimeAlertApiTest.kt} (100%) rename TripKitAndroid/src/test/java/com/skedgo/tripkit/alerts/{RealtimeAlertServiceTest.java => RealtimeAlertServiceTest.kt} (100%) rename TripKitAndroid/src/test/java/com/skedgo/tripkit/bookingproviders/{BookingResolverImplTest.java => BookingResolverImplTest.kt} (100%) rename TripKitAndroid/src/test/java/com/skedgo/tripkit/bookingproviders/{SmsBookingResolverTest.java => SmsBookingResolverTest.kt} (100%) rename TripKitAndroid/src/test/java/com/skedgo/tripkit/tsp/{RegionInfoApiTest.java => RegionInfoApiTest.kt} (100%) rename TripKitAndroid/src/test/java/com/skedgo/tripkit/tsp/{RegionInfoServiceTest.java => RegionInfoServiceTest.kt} (100%) diff --git a/TripKitAndroid/src/test/java/com/skedgo/tripkit/RouteServiceImplTest.java b/TripKitAndroid/src/test/java/com/skedgo/tripkit/RouteServiceImplTest.kt similarity index 100% rename from TripKitAndroid/src/test/java/com/skedgo/tripkit/RouteServiceImplTest.java rename to TripKitAndroid/src/test/java/com/skedgo/tripkit/RouteServiceImplTest.kt diff --git a/TripKitAndroid/src/test/java/com/skedgo/tripkit/UtilsTest.java b/TripKitAndroid/src/test/java/com/skedgo/tripkit/UtilsTest.kt similarity index 100% rename from TripKitAndroid/src/test/java/com/skedgo/tripkit/UtilsTest.java rename to TripKitAndroid/src/test/java/com/skedgo/tripkit/UtilsTest.kt diff --git a/TripKitAndroid/src/test/java/com/skedgo/tripkit/a2brouting/SelectBestDisplayTripTest.java b/TripKitAndroid/src/test/java/com/skedgo/tripkit/a2brouting/SelectBestDisplayTripTest.kt similarity index 100% rename from TripKitAndroid/src/test/java/com/skedgo/tripkit/a2brouting/SelectBestDisplayTripTest.java rename to TripKitAndroid/src/test/java/com/skedgo/tripkit/a2brouting/SelectBestDisplayTripTest.kt diff --git a/TripKitAndroid/src/test/java/com/skedgo/tripkit/alerts/RealtimeAlertApiTest.java b/TripKitAndroid/src/test/java/com/skedgo/tripkit/alerts/RealtimeAlertApiTest.kt similarity index 100% rename from TripKitAndroid/src/test/java/com/skedgo/tripkit/alerts/RealtimeAlertApiTest.java rename to TripKitAndroid/src/test/java/com/skedgo/tripkit/alerts/RealtimeAlertApiTest.kt diff --git a/TripKitAndroid/src/test/java/com/skedgo/tripkit/alerts/RealtimeAlertServiceTest.java b/TripKitAndroid/src/test/java/com/skedgo/tripkit/alerts/RealtimeAlertServiceTest.kt similarity index 100% rename from TripKitAndroid/src/test/java/com/skedgo/tripkit/alerts/RealtimeAlertServiceTest.java rename to TripKitAndroid/src/test/java/com/skedgo/tripkit/alerts/RealtimeAlertServiceTest.kt diff --git a/TripKitAndroid/src/test/java/com/skedgo/tripkit/bookingproviders/BookingResolverImplTest.java b/TripKitAndroid/src/test/java/com/skedgo/tripkit/bookingproviders/BookingResolverImplTest.kt similarity index 100% rename from TripKitAndroid/src/test/java/com/skedgo/tripkit/bookingproviders/BookingResolverImplTest.java rename to TripKitAndroid/src/test/java/com/skedgo/tripkit/bookingproviders/BookingResolverImplTest.kt diff --git a/TripKitAndroid/src/test/java/com/skedgo/tripkit/bookingproviders/SmsBookingResolverTest.java b/TripKitAndroid/src/test/java/com/skedgo/tripkit/bookingproviders/SmsBookingResolverTest.kt similarity index 100% rename from TripKitAndroid/src/test/java/com/skedgo/tripkit/bookingproviders/SmsBookingResolverTest.java rename to TripKitAndroid/src/test/java/com/skedgo/tripkit/bookingproviders/SmsBookingResolverTest.kt diff --git a/TripKitAndroid/src/test/java/com/skedgo/tripkit/tsp/RegionInfoApiTest.java b/TripKitAndroid/src/test/java/com/skedgo/tripkit/tsp/RegionInfoApiTest.kt similarity index 100% rename from TripKitAndroid/src/test/java/com/skedgo/tripkit/tsp/RegionInfoApiTest.java rename to TripKitAndroid/src/test/java/com/skedgo/tripkit/tsp/RegionInfoApiTest.kt diff --git a/TripKitAndroid/src/test/java/com/skedgo/tripkit/tsp/RegionInfoServiceTest.java b/TripKitAndroid/src/test/java/com/skedgo/tripkit/tsp/RegionInfoServiceTest.kt similarity index 100% rename from TripKitAndroid/src/test/java/com/skedgo/tripkit/tsp/RegionInfoServiceTest.java rename to TripKitAndroid/src/test/java/com/skedgo/tripkit/tsp/RegionInfoServiceTest.kt From 9230da8fb659a0e7a1825fe40389c816c2fbe91d Mon Sep 17 00:00:00 2001 From: Michael Angelo Reyes Date: Tue, 12 Nov 2024 00:30:00 +0800 Subject: [PATCH 19/25] [22682] - [TripKit] re-enable, convert and update BookingResolverImplTest.java to kotlin - [TripKit] convert, fix and update RealtimeAlertApiTest.java to kotlin - [TripKit] convert, fix and update RealtimeAlertServiceTest.java to kotlin - [TripKit] convert, fix and update RegionInfoApiTest.java to kotlin - [TripKit] convert, fix and update RegionInfoServiceTest.java to kotlin - [TripKit] convert, fix and update RouteServiceImplTest.java to kotlin - [TripKit] convert, fix and update SelectBestDisplayTripTest.java to kotlin - [TripKit] convert, fix and update SmsBookingResolverTest.java to kotlin - [TripKit] re-enable and fix UberBookingResolverTest.kt - [TripKit] convert, fix and update UtilsTest.java to kotlin --- .../java/com/skedgo/tripkit/CacheImplTest.kt | 6 +- .../skedgo/tripkit/RegionServiceImplTest.kt | 10 +- .../skedgo/tripkit/RouteServiceImplTest.kt | 241 +++--- .../com/skedgo/tripkit/TripUpdaterImplTest.kt | 4 - .../test/java/com/skedgo/tripkit/UtilsTest.kt | 252 +++--- .../a2brouting/SelectBestDisplayTripTest.kt | 104 +-- .../tripkit/alerts/RealtimeAlertApiTest.kt | 148 ++-- .../alerts/RealtimeAlertServiceTest.kt | 196 ++--- .../BookingResolverImplTest.kt | 719 +++++++----------- .../SmsBookingResolverTest.kt | 59 +- .../UberBookingResolverTest.kt | 121 +-- .../skedgo/tripkit/tsp/RegionInfoApiTest.kt | 103 +-- .../tripkit/tsp/RegionInfoServiceTest.kt | 227 +++--- .../src/test/resources/alerts-transit.json | 34 + 14 files changed, 1100 insertions(+), 1124 deletions(-) diff --git a/TripKitAndroid/src/test/java/com/skedgo/tripkit/CacheImplTest.kt b/TripKitAndroid/src/test/java/com/skedgo/tripkit/CacheImplTest.kt index feec2329..2c05a9f1 100644 --- a/TripKitAndroid/src/test/java/com/skedgo/tripkit/CacheImplTest.kt +++ b/TripKitAndroid/src/test/java/com/skedgo/tripkit/CacheImplTest.kt @@ -28,18 +28,18 @@ class CacheImplTest : TripKitAndroidRobolectricTest() { }) val cache = CacheImpl(fetcher, loader) - assertThat(cache.async.map { it.toList() }.blockingGet()) + assertThat(cache.getAsync().map { it.toList() }.blockingGet()) .describedAs("Should hit loader to retrieve data") .containsExactly("1".first()) assertThat(fetcherHitCounter.get()) .describedAs("Should hit fetcher to retrieve data") .isEqualTo(1) - assertThat(cache.async.map { it.toList() }.blockingGet()) + assertThat(cache.getAsync().map { it.toList() }.blockingGet()) .describedAs("Should give data cached in memory") .containsExactly("1".first()) cache.invalidate() - assertThat(cache.async.map { it.toList() }.blockingGet()) + assertThat(cache.getAsync().map { it.toList() }.blockingGet()) .describedAs("After invalidation, should re-hit loader to retrieve data") .containsExactly("2".first()) assertThat(fetcherHitCounter.get()) diff --git a/TripKitAndroid/src/test/java/com/skedgo/tripkit/RegionServiceImplTest.kt b/TripKitAndroid/src/test/java/com/skedgo/tripkit/RegionServiceImplTest.kt index 9e939305..e3455c76 100644 --- a/TripKitAndroid/src/test/java/com/skedgo/tripkit/RegionServiceImplTest.kt +++ b/TripKitAndroid/src/test/java/com/skedgo/tripkit/RegionServiceImplTest.kt @@ -62,7 +62,7 @@ class RegionServiceImplTest : TripKitAndroidRobolectricTest() { NewYork.name = "US_NY_NewYorkCity" NewYork.encodedPolyline = "oecvFnzhdM_}tA??o~oE~|tA?" - whenever(regionCache.async) + whenever(regionCache.getAsync()) .thenReturn(Single.just(Arrays.asList(Sydney, NewYork))) whenever( regionFinder.contains( @@ -96,7 +96,7 @@ class RegionServiceImplTest : TripKitAndroidRobolectricTest() { NewYork.name = "US_NY_NewYorkCity" NewYork.encodedPolyline = "oecvFnzhdM_}tA??o~oE~|tA?" - whenever(regionCache.async) + whenever(regionCache.getAsync()) .thenReturn(Single.just(Arrays.asList(Sydney, NewYork))) val subscriber = TestObserver() @@ -132,7 +132,7 @@ class RegionServiceImplTest : TripKitAndroidRobolectricTest() { SanJose.name = "San Jose" US.cities = ArrayList(Arrays.asList(NewYork, SanJose)) - whenever(regionCache.async) + whenever(regionCache.getAsync()) .thenReturn(Single.just(Arrays.asList(AU, US))) val subscriber = TestObserver() @@ -148,7 +148,7 @@ class RegionServiceImplTest : TripKitAndroidRobolectricTest() { val modeMap = HashMap() modeMap.put("car", TransportMode()) modeMap.put("walk", TransportMode()) - whenever(modeCache.async).thenReturn(Single.just>(modeMap)) + whenever(modeCache.getAsync()).thenReturn(Single.just>(modeMap)) val subscriber = TestObserver>() regionService.getTransportModesAsync().subscribe(subscriber) @@ -164,7 +164,7 @@ class RegionServiceImplTest : TripKitAndroidRobolectricTest() { Region(), Region() ) - whenever(regionCache.async).thenReturn(Single.just(regions)) + whenever(regionCache.getAsync()).thenReturn(Single.just(regions)) val subscriber = regionService.getRegionsAsync().test() subscriber.awaitTerminalEvent() diff --git a/TripKitAndroid/src/test/java/com/skedgo/tripkit/RouteServiceImplTest.kt b/TripKitAndroid/src/test/java/com/skedgo/tripkit/RouteServiceImplTest.kt index 32eefeaa..c6b07263 100644 --- a/TripKitAndroid/src/test/java/com/skedgo/tripkit/RouteServiceImplTest.kt +++ b/TripKitAndroid/src/test/java/com/skedgo/tripkit/RouteServiceImplTest.kt @@ -1,77 +1,87 @@ -package com.skedgo.tripkit; - -import com.skedgo.tripkit.a2brouting.FailoverA2bRoutingApi; -import com.skedgo.tripkit.common.model.location.Location; -import com.skedgo.tripkit.common.model.Query; -import com.skedgo.tripkit.common.model.time.TimeTag; -import com.skedgo.tripkit.data.tsp.RegionInfo; -import com.skedgo.tripkit.routing.ExtraQueryMapProvider; -import com.skedgo.tripkit.tsp.RegionInfoRepository; - -import org.assertj.core.data.MapEntry; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.Mock; -import org.mockito.MockitoAnnotations; - -import java.util.Collections; -import java.util.HashMap; -import java.util.Map; - -import androidx.test.core.app.ApplicationProvider; -import androidx.test.ext.junit.runners.AndroidJUnit4; -import io.reactivex.Observable; - -import static org.assertj.core.api.Java6Assertions.assertThat; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.Mockito.when; - -@RunWith(AndroidJUnit4.class) -public class RouteServiceImplTest { - @Mock - QueryGenerator queryGenerator; - @Mock - Co2Preferences co2Preferences; - @Mock - TripPreferences tripPreferences; - @Mock - ExtraQueryMapProvider extraQueryMapProvider; - @Mock - FailoverA2bRoutingApi routingApi; - @Mock - RegionInfoRepository regionInfoRepository; - @Mock - RegionInfo regionInfo; - private RouteServiceImpl routeService; +package com.skedgo.tripkit + +import android.content.Context +import androidx.arch.core.executor.testing.InstantTaskExecutorRule +import androidx.test.core.app.ApplicationProvider +import androidx.test.ext.junit.runners.AndroidJUnit4 +import com.skedgo.tripkit.a2brouting.FailoverA2bRoutingApi +import com.skedgo.tripkit.booking.ui.base.MockKTest +import com.skedgo.tripkit.common.model.Query +import com.skedgo.tripkit.common.model.location.Location +import com.skedgo.tripkit.common.model.time.TimeTag +import com.skedgo.tripkit.data.tsp.RegionInfo +import com.skedgo.tripkit.routing.ExtraQueryMapProvider +import com.skedgo.tripkit.tsp.RegionInfoRepository +import io.mockk.MockKAnnotations +import io.mockk.every +import io.mockk.mockk +import io.reactivex.Observable +import org.assertj.core.api.Assertions.assertThat +import org.junit.After +import org.junit.Before +import org.junit.Rule +import org.junit.Test +import org.junit.runner.RunWith + +@RunWith(AndroidJUnit4::class) +class RouteServiceImplTest: MockKTest() { + + @get:Rule + val rule = InstantTaskExecutorRule() + + private val queryGenerator: QueryGenerator = mockk() + private val co2Preferences: Co2Preferences = mockk() + private val tripPreferences: TripPreferences = mockk() + private val extraQueryMapProvider: ExtraQueryMapProvider = mockk() + private val routingApi: FailoverA2bRoutingApi = mockk() + private val regionInfoRepository: RegionInfoRepository = mockk() + private val regionInfo: RegionInfo = mockk() + private lateinit var routeService: RouteServiceImpl @Before - public void before() { - MockitoAnnotations.initMocks(this); - routeService = new RouteServiceImpl(ApplicationProvider.getApplicationContext(), + fun setUp() { + MockKAnnotations.init(this) + initRx() + routeService = RouteServiceImpl( + ApplicationProvider.getApplicationContext(), queryGenerator, co2Preferences, tripPreferences, extraQueryMapProvider, routingApi, regionInfoRepository - ); - when(extraQueryMapProvider.call()) - .thenReturn(Collections.emptyMap()); - when(regionInfoRepository.getRegionInfoByRegion(any())).thenReturn(Observable.just(regionInfo)); - when(regionInfo.transitWheelchairAccessibility()).thenReturn(false); + ) + + every { extraQueryMapProvider.call() } returns emptyMap() + every { regionInfoRepository.getRegionInfoByRegion(any()) } returns Observable.just(regionInfo) + every { regionInfo.transitWheelchairAccessibility() } returns false + + every { extraQueryMapProvider.call() } returns emptyMap() + every { regionInfoRepository.getRegionInfoByRegion(any()) } returns Observable.just(regionInfo) + every { regionInfo.transitWheelchairAccessibility() } returns false + + // Mock the call to isConcessionPricingPreferred + every { tripPreferences.isConcessionPricingPreferred() } returns false + every { co2Preferences.getCo2Profile() } returns mapOf("a" to 2f, "b" to 5f) + } + + @After + fun tearDown() { + tearDownRx() } @Test - public void shouldIncludeSomeOptions() { - final Query query = createQuery(); - query.setTimeTag(TimeTag.createForArriveBy(25251325)); - query.setCyclingSpeed(3); + fun `should include some options`() { + val query = createQuery().apply { + timeTag = TimeTag.createForArriveBy(25251325) + cyclingSpeed = 3 + } + + val options = routeService.toOptions(query) - final Map options = routeService.toOptions(query); assertThat(options) .containsEntry("v", "12") - .containsEntry("unit", query.getUnit()) + .containsEntry("unit", query.unit) .containsEntry("from", "(1.0,2.0)") .containsEntry("to", "(3.0,4.0)") .containsEntry("arriveBefore", "25251325") @@ -79,104 +89,95 @@ public class RouteServiceImplTest { .containsEntry("tt", "2") .containsEntry("ws", "4") .containsEntry("cs", "3") - .doesNotContainKey("ir"); + .doesNotContainKey("ir") } @Test - public void shouldIncludeAddressString() { - final Query query = createQuery(); - query.getFromLocation().setAddress("from address"); - query.getToLocation().setAddress("to address"); + fun `should include address string`() { + val query = createQuery().apply { + fromLocation?.address = "from address" + toLocation?.address = "to address" + } + + val options = routeService.toOptions(query) - final Map options = routeService.toOptions(query); assertThat(options) .containsEntry("from", "(1.0,2.0)\"from address\"") - .containsEntry("to", "(3.0,4.0)\"to address\""); + .containsEntry("to", "(3.0,4.0)\"to address\"") } - /** - * Given an {@link ExtraQueryMapProvider} that returns an extra query map, - * we expect that the query map returned by {@link RouteServiceImpl#toOptions(Query, RegionInfo)} - * should contain all the entries from the extra query map. - */ @Test - public void shouldIncludeExtraQueryMap() { - final Query query = createQuery(); - query.setTimeTag(TimeTag.createForArriveBy(25251325)); + fun `should include extra query map`() { + val query = createQuery().apply { + timeTag = TimeTag.createForArriveBy(25251325) + } + + val extraQueryMap = mapOf("bsb" to 1) + every { extraQueryMapProvider.call() } returns extraQueryMap - final Map extraQueryMap = new HashMap<>(); - extraQueryMap.put("bsb", 1); - when(extraQueryMapProvider.call()) - .thenReturn(extraQueryMap); + val options = routeService.toOptions(query) - final Map options = routeService.toOptions(query); - assertThat(options).contains(MapEntry.entry("bsb", 1)); + assertThat(options).containsEntry("bsb", 1) } @Test - public void includeConcessionPricing() { - when(tripPreferences.isConcessionPricingPreferred()).thenReturn(true); - assertThat(routeService.getParamsByPreferences()).containsEntry("conc", true); + fun `include concession pricing`() { + every { tripPreferences.isConcessionPricingPreferred() } returns true + assertThat(routeService.getParamsByPreferences()).containsEntry("conc", true) } @Test - public void excludeConcessionPricing() { - when(tripPreferences.isConcessionPricingPreferred()).thenReturn(false); - assertThat(routeService.getParamsByPreferences()).doesNotContainKey("conc"); + fun `exclude concession pricing`() { + every { tripPreferences.isConcessionPricingPreferred() } returns false + assertThat(routeService.getParamsByPreferences()).doesNotContainKey("conc") } - /* See https://redmine.buzzhives.com/issues/7663. */ @Test - public void excludeWheelchairInfo() { - when(tripPreferences.isWheelchairPreferred()).thenReturn(false); - assertThat(routeService.getParamsByPreferences()).doesNotContainKey("wheelchair"); + fun `exclude wheelchair info`() { + every { tripPreferences.isWheelchairPreferred() } returns false + assertThat(routeService.getParamsByPreferences()).doesNotContainKey("wheelchair") } @Test - public void shouldIncludeOptionDepartAfter() { - final Query query = createQuery(); - query.setTimeTag(TimeTag.createForLeaveAfter(25251325)); + fun `should include option depart after`() { + val query = createQuery().apply { + timeTag = TimeTag.createForLeaveAfter(25251325) + } + + val options = routeService.toOptions(query) - final Map options = routeService.toOptions(query); assertThat(options) .containsEntry("arriveBefore", "0") - .containsEntry("departAfter", "25251325"); + .containsEntry("departAfter", "25251325") } @Test - public void shouldContainOptionIncludeStops() { - final Query query = createQuery(); - final Map options = routeService.toOptions(query); - assertThat(options).containsEntry("includeStops", "1"); - } + fun `should contain option include stops`() { + val query = createQuery() - @Test - public void shouldContainOptionIncludeStopsByDefault() { - final Query query = createQuery(); + val options = routeService.toOptions(query) - final Map options = routeService.toOptions(query); - assertThat(options).containsEntry("includeStops", "1"); + assertThat(options).containsEntry("includeStops", "1") } @Test - public void includeCo2Profile() { - final Map co2Profile = new HashMap<>(); - co2Profile.put("a", 2f); - co2Profile.put("b", 5f); - when(co2Preferences.getCo2Profile()).thenReturn(co2Profile); + fun `include CO2 profile`() { + val co2Profile = mapOf("a" to 2f, "b" to 5f) + every { co2Preferences.getCo2Profile() } returns co2Profile + assertThat(routeService.getParamsByPreferences()) .hasSize(2) .containsEntry("co2[a]", 2f) - .containsEntry("co2[b]", 5f); + .containsEntry("co2[b]", 5f) } - private Query createQuery() { - final Query query = new Query(); - query.setFromLocation(new Location(1.0, 2.0)); - query.setToLocation(new Location(3.0, 4.0)); - query.setTransferTime(2); - query.setWalkingSpeed(4); - query.setUnit("mi"); - return query; + private fun createQuery(): Query { + return Query().apply { + fromLocation = Location(1.0, 2.0) + toLocation = Location(3.0, 4.0) + transferTime = 2 + walkingSpeed = 4 + unit = "mi" + } } } diff --git a/TripKitAndroid/src/test/java/com/skedgo/tripkit/TripUpdaterImplTest.kt b/TripKitAndroid/src/test/java/com/skedgo/tripkit/TripUpdaterImplTest.kt index d7021ad7..43f6ad9e 100644 --- a/TripKitAndroid/src/test/java/com/skedgo/tripkit/TripUpdaterImplTest.kt +++ b/TripKitAndroid/src/test/java/com/skedgo/tripkit/TripUpdaterImplTest.kt @@ -3,7 +3,6 @@ package com.skedgo.tripkit import android.content.res.Resources import androidx.test.ext.junit.runners.AndroidJUnit4 import com.google.gson.Gson -import com.nhaarman.mockitokotlin2.whenever import com.skedgo.tripkit.routing.RoutingResponse import com.skedgo.tripkit.routing.Trip import com.skedgo.tripkit.routing.TripGroup @@ -17,9 +16,6 @@ import org.assertj.core.api.Java6Assertions.assertThat import org.junit.Before import org.junit.Test import org.junit.runner.RunWith -import org.mockito.Mock -import org.mockito.Mockito.mock -import org.mockito.MockitoAnnotations @RunWith(AndroidJUnit4::class) class TripUpdaterImplTest { diff --git a/TripKitAndroid/src/test/java/com/skedgo/tripkit/UtilsTest.kt b/TripKitAndroid/src/test/java/com/skedgo/tripkit/UtilsTest.kt index cfedda2f..a9d4efcf 100644 --- a/TripKitAndroid/src/test/java/com/skedgo/tripkit/UtilsTest.kt +++ b/TripKitAndroid/src/test/java/com/skedgo/tripkit/UtilsTest.kt @@ -1,169 +1,181 @@ -package com.skedgo.tripkit; +package com.skedgo.tripkit + +import androidx.test.ext.junit.runners.AndroidJUnit4 +import com.skedgo.tripkit.Utils.cities +import com.skedgo.tripkit.Utils.findModesByIds +import com.skedgo.tripkit.Utils.matchCityName +import com.skedgo.tripkit.Utils.toModeMap +import com.skedgo.tripkit.common.model.TransportMode +import com.skedgo.tripkit.common.model.TransportMode.Companion.fromId +import com.skedgo.tripkit.common.model.location.Location +import com.skedgo.tripkit.common.model.region.Region +import com.skedgo.tripkit.common.model.region.Region.City +import io.reactivex.Observable +import io.reactivex.observers.TestObserver +import org.assertj.core.api.Assertions.assertThat +import org.assertj.core.api.Java6Assertions +import org.junit.Test +import org.junit.runner.RunWith +import java.util.Arrays + +@RunWith(AndroidJUnit4::class) +class UtilsTest { -import com.skedgo.tripkit.common.model.location.Location; -import com.skedgo.tripkit.common.model.region.Region; -import com.skedgo.tripkit.common.model.TransportMode; - -import org.junit.Test; -import org.junit.runner.RunWith; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import androidx.test.ext.junit.runners.AndroidJUnit4; -import io.reactivex.Observable; -import io.reactivex.observers.TestObserver; - -import static org.assertj.core.api.Java6Assertions.assertThat; - -@RunWith(AndroidJUnit4.class) -public class UtilsTest { @Test - public void getCities_shouldReceiveCitiesFromRegion() { - final Region region = new Region(); - final ArrayList expectedCities = new ArrayList<>(Arrays.asList( - new Region.City(), - new Region.City(), - new Region.City() - )); - region.setCities(expectedCities); - - final TestObserver subscriber = Observable.just(region) - .compose(Utils.getCities()) - .test(); - subscriber.assertNoErrors(); - final List events = subscriber.values(); - assertThat(events).isEqualTo(expectedCities); + fun `getCities should receive cities from region`() { + // Arrange + val region = Region() + val expectedCities = listOf(Region.City(), Region.City(), Region.City()) + region.cities = ArrayList(expectedCities) + + // Act + val testObserver: TestObserver = Observable.just(region) + .compose(Utils.cities) + .test() + + // Assert + testObserver.assertNoErrors() + val events = testObserver.values() + assertThat(events).isEqualTo(expectedCities) } @Test - public void getCities_shouldReceiveEmptyListForRegionHavingEmptyCityList() { - final Region region = new Region(); - region.setCities(new ArrayList()); - - final TestObserver subscriber = Observable.just(region) - .compose(Utils.getCities()) - .test(); - subscriber.assertNoErrors(); - subscriber.assertValueSequence(Collections.emptyList()); + fun `getCities should receive empty list for region having empty city list`() { + // Arrange + val region = Region() + region.cities = ArrayList(emptyList()) + + // Act + val testObserver: TestObserver = Observable.just(region) + .compose(cities) + .test() + + // Assert + testObserver.assertNoErrors() + testObserver.assertValueSequence(emptyList()) } @Test - public void getCities_shouldReceiveEmptyListForRegionHavingNullCityList() { - final Region region = new Region(); - final TestObserver subscriber = Observable.just(region) - .compose(Utils.getCities()) - .test(); - subscriber.assertNoErrors(); - subscriber.assertValueSequence(Collections.emptyList()); + fun `getCities should receive empty list for region having null city list`() { + // Arrange + val region = Region() + region.cities = null + + // Act + val testObserver: TestObserver = Observable.just(region) + .compose(cities) + .test() + + // Assert + testObserver.assertNoErrors() + testObserver.assertValueSequence(emptyList()) } @Test - public void matchCityName_trueForNullKeyword() throws Exception { - final Region.City city = new Region.City(); - assertThat(Utils.matchCityName(null).test(city)).isTrue(); + fun `matchCityName should return true for null keyword`() { + val city = Region.City() + assertThat(Utils.matchCityName(null).test(city)).isTrue } @Test - public void matchCityName_trueForEmptyKeyword() throws Exception { - final Region.City city = new Region.City(); - assertThat(Utils.matchCityName("").test(city)).isTrue(); + fun `matchCityName should return true for empty keyword`() { + val city = Region.City() + assertThat(Utils.matchCityName("").test(city)).isTrue } @Test - public void matchCityName_trueForOnlySpaceKeyword() throws Exception { - final Region.City city = new Region.City(); - assertThat(Utils.matchCityName(" ").test(city)).isTrue(); + fun `matchCityName should return true for only space keyword`() { + val city = Region.City() + assertThat(Utils.matchCityName(" ").test(city)).isTrue } @Test - public void matchCityName_trueIfContainingKeyword() throws Exception { - final Region.City city = new Region.City(); - city.setName("Holy coOl!"); - assertThat(Utils.matchCityName("Cool").test(city)).isTrue(); + fun `matchCityName should return true if city name contains keyword`() { + val city = Region.City().apply { name = "Holy coOl!" } + assertThat(Utils.matchCityName("Cool").test(city)).isTrue } @Test - public void matchCityName_falseIfNotContainingKeyword() throws Exception { - final Region.City city = new Region.City(); - city.setName("Holy cool!"); - assertThat(Utils.matchCityName("awesome").test(city)).isFalse(); + fun `matchCityName should return false if city name does not contain keyword`() { + val city = Region.City().apply { name = "Holy cool!" } + assertThat(Utils.matchCityName("awesome").test(city)).isFalse } @Test - public void findModesByIds_shouldReturnModesCorrespondingToRequestedIds() throws Exception { - final HashMap modeMap = new HashMap<>(); - for (String modeId : Arrays.asList("bus", "car", "motorbike", "taxi", "bicycle")) { - final TransportMode mode = new TransportMode(); - mode.setId(modeId); - modeMap.put(modeId, mode); + fun `findModesByIds should return modes corresponding to requested ids`() { + // Arrange + val modeMap = hashMapOf() + listOf("bus", "car", "motorbike", "taxi", "bicycle").forEach { modeId -> + val mode = TransportMode().apply { id = modeId } + modeMap[modeId] = mode } - final List modeIds = Arrays.asList("car", "motorbike", "bicycle"); - final List result = Utils.findModesByIds(modeIds).apply(modeMap); + val modeIds = listOf("car", "motorbike", "bicycle") + + // Act + val result = Utils.findModesByIds(modeIds).apply(modeMap) + + // Assert assertThat(result) - .isNotNull() - .extractingResultOf("getId") - .hasSize(modeIds.size()) - .containsAll(modeIds); + .isNotNull + .extracting("id") + .containsExactlyElementsOf(modeIds) } - /** - * If mode map doesn't have modes requested by ids, just return whatever we can find. - */ @Test - public void findModesByIds_shouldIgnoreModesThatAreNotFound() throws Exception { - // "motorbike" isn't found in this map. - final HashMap modeMap = new HashMap<>(); - for (String modeId : Arrays.asList("bus", "car", "walk", "taxi", "bicycle")) { - final TransportMode mode = new TransportMode(); - mode.setId(modeId); - modeMap.put(modeId, mode); + fun `findModesByIds should ignore modes that are not found`() { + // Arrange + val modeMap = hashMapOf() + listOf("bus", "car", "walk", "taxi", "bicycle").forEach { modeId -> + val mode = TransportMode().apply { id = modeId } + modeMap[modeId] = mode } - final List modeIds = Arrays.asList("car", "motorbike", "bicycle"); - final List result = Utils.findModesByIds(modeIds).apply(modeMap); + val modeIds = listOf("car", "motorbike", "bicycle") + + // Act + val result = Utils.findModesByIds(modeIds).apply(modeMap) + + // Assert assertThat(result) - .isNotNull() - .extractingResultOf("getId") - .hasSize(2) - .containsAll(Arrays.asList("car", "bicycle")); + .isNotNull + .extracting("id") + .containsExactly("car", "bicycle") } @Test - public void findModesByIds_shouldReturnEmptyListIfAllModesCannotBeFound() throws Exception { - final HashMap modeMap = new HashMap<>(); - for (String modeId : Arrays.asList("bus", "tram", "walk", "taxi", "ferry")) { - final TransportMode mode = new TransportMode(); - mode.setId(modeId); - modeMap.put(modeId, mode); + fun `findModesByIds should return empty list if all modes cannot be found`() { + // Arrange + val modeMap = hashMapOf() + listOf("bus", "tram", "walk", "taxi", "ferry").forEach { modeId -> + val mode = TransportMode().apply { id = modeId } + modeMap[modeId] = mode } - final List modeIds = Arrays.asList("car", "motorbike", "bicycle"); - final List result = Utils.findModesByIds(modeIds).apply(modeMap); - assertThat(result).isEmpty(); + val modeIds = listOf("car", "motorbike", "bicycle") + + // Act + val result = Utils.findModesByIds(modeIds).apply(modeMap) + + // Assert + assertThat(result).isEmpty() } @Test - public void toModeMap_shouldProduceEntryHavingKeyAsModeId() throws Exception { - final TransportMode bus = TransportMode.fromId("bus"); - final TransportMode walk = TransportMode.fromId("walk"); - final TransportMode car = TransportMode.fromId("car"); - final Map modeMap = Utils.toModeMap().apply(Arrays.asList(bus, walk, car)); + fun `toModeMap should produce entry having key as mode id`() { + // Arrange + val bus = TransportMode.fromId("bus") + val walk = TransportMode.fromId("walk") + val car = TransportMode.fromId("car") + + // Act + val modeMap = Utils.toModeMap().apply(listOf(bus, walk, car)) + + // Assert assertThat(modeMap) .hasSize(3) .containsEntry("bus", bus) .containsEntry("walk", walk) - .containsEntry("car", car); - } - - @Test - public void toModeMap_shouldProduceEmptyMap() throws Exception { - final Map modeMap = Utils.toModeMap().apply(null); - assertThat(modeMap).isEmpty(); + .containsEntry("car", car) } } \ No newline at end of file diff --git a/TripKitAndroid/src/test/java/com/skedgo/tripkit/a2brouting/SelectBestDisplayTripTest.kt b/TripKitAndroid/src/test/java/com/skedgo/tripkit/a2brouting/SelectBestDisplayTripTest.kt index 5c896d32..44fdb5e0 100644 --- a/TripKitAndroid/src/test/java/com/skedgo/tripkit/a2brouting/SelectBestDisplayTripTest.kt +++ b/TripKitAndroid/src/test/java/com/skedgo/tripkit/a2brouting/SelectBestDisplayTripTest.kt @@ -1,66 +1,80 @@ -package com.skedgo.tripkit.a2brouting; +package com.skedgo.tripkit.a2brouting -import com.skedgo.tripkit.routing.Trip; -import com.skedgo.tripkit.routing.TripGroup; +import androidx.test.ext.junit.runners.AndroidJUnit4 +import com.skedgo.tripkit.routing.Trip +import com.skedgo.tripkit.routing.TripGroup +import org.assertj.core.api.Assertions.assertThat +import org.assertj.core.api.Java6Assertions +import org.junit.Test +import org.junit.runner.RunWith +import java.util.Arrays -import org.junit.Test; -import org.junit.runner.RunWith; +@RunWith(AndroidJUnit4::class) +class SelectBestDisplayTripTest { -import java.util.ArrayList; -import java.util.Arrays; - -import androidx.test.ext.junit.runners.AndroidJUnit4; - -import static org.assertj.core.api.Java6Assertions.assertThat; - -@RunWith(AndroidJUnit4.class) -public class SelectBestDisplayTripTest { @Test - public void selectDisplayTripHavingLowestWeightedScore() { - final Trip a = new Trip(); - a.setTripId(0); - a.setWeightedScore(3f); + fun `select display trip having lowest weighted score`() { + // Arrange + val tripA = Trip().apply { + tripId = 0 + weightedScore = 3f + } - // This is the best display trip. - final Trip b = new Trip(); - b.setTripId(1); - b.setWeightedScore(1f); + val tripB = Trip().apply { + tripId = 1 + weightedScore = 1f + } - final Trip c = new Trip(); - c.setTripId(2); - c.setWeightedScore(2f); + val tripC = Trip().apply { + tripId = 2 + weightedScore = 2f + } - final TripGroup group = new TripGroup(); - group.setTrips(new ArrayList<>(Arrays.asList(a, b, c))); + val group = TripGroup().apply { + setTrips(ArrayList(listOf(tripA, tripB, tripC))) + } - final TripGroup actual = new SelectBestDisplayTrip().apply(group); - assertThat(actual).isNotNull().isSameAs(group); - assertThat(actual.getTrips()) + // Act + val actual = SelectBestDisplayTrip().apply(group) + + // Assert + assertThat(actual).isNotNull.isSameAs(group) + assertThat(actual.trips) .describedAs("Sort trips by weighted score") - .containsExactly(b, c, a); - assertThat(actual.getDisplayTripId()) + .containsExactly(tripB, tripC, tripA) + assertThat(actual.displayTripId) .describedAs("Select display trip having lowest weighted score") - .isEqualTo(b.getTripId()); - assertThat(actual.getDisplayTrip()) + .isEqualTo(tripB.tripId) + assertThat(actual.displayTrip) .describedAs("Select display trip having lowest weighted score") - .isSameAs(b); + .isSameAs(tripB) } @Test - public void doNothingIfNoTripsAvailable_null() { - final TripGroup group = new TripGroup(); - group.setTrips(null); + fun `do nothing if no trips available - null`() { + // Arrange + val group = TripGroup().apply { + setTrips(null) + } + + // Act + val actual = SelectBestDisplayTrip().apply(group) - final TripGroup actual = new SelectBestDisplayTrip().apply(group); - assertThat(actual).isNotNull().isSameAs(group); + // Assert + assertThat(actual).isNotNull.isSameAs(group) } @Test - public void doNothingIfNoTripsAvailable_empty() { - final TripGroup group = new TripGroup(); - group.setTrips(new ArrayList()); + fun `do nothing if no trips available - empty`() { + // Arrange + val group = TripGroup().apply { + setTrips(ArrayList(emptyList())) + } + + // Act + val actual = SelectBestDisplayTrip().apply(group) - final TripGroup actual = new SelectBestDisplayTrip().apply(group); - assertThat(actual).isNotNull().isSameAs(group); + // Assert + assertThat(actual).isNotNull.isSameAs(group) } } \ No newline at end of file diff --git a/TripKitAndroid/src/test/java/com/skedgo/tripkit/alerts/RealtimeAlertApiTest.kt b/TripKitAndroid/src/test/java/com/skedgo/tripkit/alerts/RealtimeAlertApiTest.kt index e86b7dbc..929c676e 100644 --- a/TripKitAndroid/src/test/java/com/skedgo/tripkit/alerts/RealtimeAlertApiTest.kt +++ b/TripKitAndroid/src/test/java/com/skedgo/tripkit/alerts/RealtimeAlertApiTest.kt @@ -1,81 +1,101 @@ -package com.skedgo.tripkit.alerts; +package com.skedgo.tripkit.alerts -import com.skedgo.tripkit.TripKitAndroidRobolectricTest; -import com.skedgo.tripkit.common.model.realtimealert.ImmutableRealtimeAlert; +import androidx.test.ext.junit.runners.AndroidJUnit4 +import com.skedgo.tripkit.booking.ui.base.MockKTest +import com.skedgo.tripkit.common.model.realtimealert.ImmutableRealtimeAlert +import io.reactivex.observers.TestObserver +import io.reactivex.schedulers.Schedulers +import okhttp3.mockwebserver.MockResponse +import okhttp3.mockwebserver.MockWebServer +import org.junit.Before +import org.junit.Rule +import org.junit.Test +import org.junit.runner.RunWith +import retrofit2.Retrofit +import retrofit2.Retrofit.Builder +import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory +import retrofit2.converter.gson.GsonConverterFactory +import thuytrinh.mockwebserverrule.MockWebServerRule.createMockResponse -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.junit.runner.RunWith; +import java.io.IOException -import java.io.IOException; -import java.util.Arrays; +@RunWith(AndroidJUnit4::class) +class RealtimeAlertApiTest: MockKTest() { -import androidx.test.ext.junit.runners.AndroidJUnit4; -import io.reactivex.observers.TestObserver; -import retrofit2.Retrofit; -import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory; -import retrofit2.converter.gson.GsonConverterFactory; -import thuytrinh.mockwebserverrule.MockWebServerRule; - -import static io.reactivex.schedulers.Schedulers.trampoline; -import static thuytrinh.mockwebserverrule.MockWebServerRule.createMockResponse; - -@RunWith(AndroidJUnit4.class) -public class RealtimeAlertApiTest extends TripKitAndroidRobolectricTest { - @Rule - public final MockWebServerRule serverRule = new MockWebServerRule(); - private RealtimeAlertApi api; + @get:Rule + val server = MockWebServer() + private lateinit var api: RealtimeAlertApi @Before - public void before() { - api = new Retrofit.Builder() - .baseUrl(serverRule.server.url("/")) + fun setUp() { + api = Retrofit.Builder() + .baseUrl(server.url("/")) .addConverterFactory(GsonConverterFactory.create()) - .addCallAdapterFactory(RxJava2CallAdapterFactory.createWithScheduler(trampoline())) + .addCallAdapterFactory(RxJava2CallAdapterFactory.createWithScheduler(Schedulers.trampoline())) .build() - .create(RealtimeAlertApi.class); + .create(RealtimeAlertApi::class.java) } @Test - public void fetchRealtimeAlertsSuccessfully() throws IOException { - serverRule.server.enqueue(createMockResponse("/alerts-transit.json")); - final String regionName = "AU_NSW_Sydney"; + @Throws(IOException::class) + fun `fetch realtime alerts successfully`() { + // Arrange + server.enqueue(createMockResponse("/alerts-transit.json")) + val regionName = "AU_NSW_Sydney" - final TestObserver subscriber = api.fetchRealtimeAlertsAsync( - serverRule.server.url("/").toString(), + // Act + val testObserver: TestObserver = api.fetchRealtimeAlertsAsync( + server.url("/").toString(), regionName - ).test(); + ).test() - subscriber.awaitTerminalEvent(); - subscriber.assertNoErrors(); + // Assert + testObserver.awaitTerminalEvent() + testObserver.assertNoErrors() + + val expectedResponse = ImmutableRealtimeAlertResponse.builder() + .alerts( + listOf( + ImmutableAlertBlock.builder() + .alert( + ImmutableRealtimeAlert.builder() + .remoteHashCode(707713596) + .severity("warning") + .title("Trackwork - Blue Mountains Line") + .text("Monday 29 August to Friday 2 September \n\n- Buses replace trains between Mount Victoria and Lithgow.\n- Trains to and from Bathurst run to a changed timetable.") + .url("http://www.sydneytrains.info/service_updates/service_interruptions/") + .build() + ).operators("operator1", "operator2") + .stopCodes("stopCode1", "stopCode2") + .serviceTripIDs("test1", "test2") + .routes( + ImmutableRoute.builder() + .id("test") + .build() + ) + .build(), + ImmutableAlertBlock.builder() + .alert( + ImmutableRealtimeAlert.builder() + .remoteHashCode(697250695) + .severity("warning") + .title("Wharf Closed") + .text("McMahons Point Wharf Closed. Wharf closed for planned upgrade.") + .url("") + .build() + ).operators("operator1", "operator2") + .stopCodes("stopCode1", "stopCode2") + .serviceTripIDs("test1", "test2") + .routes( + ImmutableRoute.builder() + .id("test") + .build() + ) + .build() + ) + ) + .build() - final RealtimeAlertResponse response = ImmutableRealtimeAlertResponse.builder() - .alerts(Arrays.asList( - ImmutableAlertBlock.builder() - .alert( - ImmutableRealtimeAlert.builder() - .remoteHashCode(707713596) - .severity("warning") - .title("Trackwork - Blue Mountains Line") - .text("Monday 29 August to Friday 2 September \n\n- Buses replace trains between Mount Victoria and Lithgow.\n- Trains to and from Bathurst run to a changed timetable.") - .url("http://www.sydneytrains.info/service_updates/service_interruptions/") - .build() - ) - .build(), - ImmutableAlertBlock.builder() - .alert( - ImmutableRealtimeAlert.builder() - .remoteHashCode(697250695) - .severity("warning") - .title("Wharf Closed") - .text("McMahons Point Wharf Closed. Wharf closed for planned upgrade.") - .url("") - .build() - ) - .build() - )) - .build(); - subscriber.assertValue(response); + testObserver.assertValue(expectedResponse) } } \ No newline at end of file diff --git a/TripKitAndroid/src/test/java/com/skedgo/tripkit/alerts/RealtimeAlertServiceTest.kt b/TripKitAndroid/src/test/java/com/skedgo/tripkit/alerts/RealtimeAlertServiceTest.kt index 091c3b4d..d9c6f127 100644 --- a/TripKitAndroid/src/test/java/com/skedgo/tripkit/alerts/RealtimeAlertServiceTest.kt +++ b/TripKitAndroid/src/test/java/com/skedgo/tripkit/alerts/RealtimeAlertServiceTest.kt @@ -1,115 +1,121 @@ -package com.skedgo.tripkit.alerts; - -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.Mock; -import org.mockito.junit.MockitoJUnit; -import org.mockito.junit.MockitoRule; -import org.robolectric.RobolectricTestRunner; - -import java.util.Arrays; -import java.util.List; - -import androidx.test.ext.junit.runners.AndroidJUnit4; -import io.reactivex.Observable; -import io.reactivex.exceptions.CompositeException; -import io.reactivex.observers.TestObserver; - -import static org.mockito.Matchers.anyString; -import static org.mockito.Mockito.eq; -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; - -@RunWith(AndroidJUnit4.class) -public class RealtimeAlertServiceTest { - @Rule - public final MockitoRule rule = MockitoJUnit.rule(); - @Mock - RealtimeAlertApi api; - private RealtimeAlertService service; +package com.skedgo.tripkit.alerts + +import androidx.test.ext.junit.runners.AndroidJUnit4 +import io.mockk.every +import io.mockk.mockk +import io.mockk.verify +import io.reactivex.Observable +import io.reactivex.exceptions.CompositeException +import io.reactivex.observers.TestObserver +import org.junit.Before +import org.junit.Rule +import org.junit.Test +import org.junit.runner.RunWith +import org.mockito.ArgumentMatchers +import org.mockito.Mock +import org.mockito.Mockito +import org.mockito.junit.MockitoJUnit +import org.mockito.junit.MockitoRule + +@RunWith(AndroidJUnit4::class) +class RealtimeAlertServiceTest { + + private val api: RealtimeAlertApi = mockk() + private lateinit var service: RealtimeAlertService @Before - public void before() { - service = new RealtimeAlertService(api); + fun setUp() { + service = RealtimeAlertService(api) } /** - * We manage to fetch via first server, then we ignore second server. + * We manage to fetch via the first server, then we ignore the second server. */ @Test - public void fetchRealtimeAlertsSuccessfully() { - final List baseUrls = Arrays.asList( - "http://tripgo.com/", - "http://riogo.com/" - ); - final RealtimeAlertResponse response = ImmutableRealtimeAlertResponse.builder().build(); - when(api.fetchRealtimeAlertsAsync( - eq("http://tripgo.com/alerts/transit.json"), - eq("sydney") - )).thenReturn(Observable.just(response)); - - final TestObserver subscriber = service.fetchRealtimeAlertsAsync(baseUrls, "sydney").test(); - subscriber.awaitTerminalEvent(); - subscriber.assertNoErrors(); - subscriber.assertValue(response); - - verify(api).fetchRealtimeAlertsAsync( - eq("http://tripgo.com/alerts/transit.json"), - eq("sydney") - ); + fun `fetch realtime alerts successfully`() { + // Arrange + val baseUrls = listOf("http://tripgo.com/", "http://riogo.com/") + val response = ImmutableRealtimeAlertResponse.builder().build() + + every { + api.fetchRealtimeAlertsAsync( + "http://tripgo.com/alerts/transit.json", + "sydney" + ) + } returns Observable.just(response) + + // Act + val testObserver: TestObserver = service + .fetchRealtimeAlertsAsync(baseUrls, "sydney") + .test() + + // Assert + testObserver.awaitTerminalEvent() + testObserver.assertNoErrors() + testObserver.assertValue(response) + + verify(exactly = 1) { + api.fetchRealtimeAlertsAsync( + "http://tripgo.com/alerts/transit.json", + "sydney" + ) + } } /** - * When we fail to fetch via first server but manage via second server. + * When we fail to fetch via the first server but manage via the second server. */ @Test - public void fetchRealtimeAlertsSuccessfullyVia2ndServer() { - final List baseUrls = Arrays.asList( - "http://tripgo.com/", - "http://riogo.com/" - ); - final RealtimeAlertResponse response = ImmutableRealtimeAlertResponse.builder().build(); - final RuntimeException error = new RuntimeException("1st server is down"); - when(api.fetchRealtimeAlertsAsync(anyString(), eq("sydney"))) - .thenReturn(Observable.error(error)) - .thenReturn(Observable.just(response)); - - final TestObserver subscriber = service.fetchRealtimeAlertsAsync(baseUrls, "sydney").test(); - subscriber.awaitTerminalEvent(); - subscriber.assertNoErrors(); - subscriber.assertValue(response); - - verify(api, times(2)).fetchRealtimeAlertsAsync( - anyString(), - eq("sydney") - ); + fun `fetch realtime alerts successfully via 2nd server`() { + // Arrange + val baseUrls = listOf("http://tripgo.com/", "http://riogo.com/") + val response = ImmutableRealtimeAlertResponse.builder().build() + val error = RuntimeException("1st server is down") + + every { api.fetchRealtimeAlertsAsync(any(), "sydney") } + .returnsMany( + Observable.error(error), + Observable.just(response) + ) + + // Act + val testObserver: TestObserver = service + .fetchRealtimeAlertsAsync(baseUrls, "sydney") + .test() + + // Assert + testObserver.awaitTerminalEvent() + testObserver.assertNoErrors() + testObserver.assertValue(response) + + verify(exactly = 2) { api.fetchRealtimeAlertsAsync(any(), "sydney") } } /** * When we fail to fetch via both servers. */ @Test - public void failToFetchRealtimeAlerts() { - final List baseUrls = Arrays.asList( - "http://tripgo.com/", - "http://riogo.com/" - ); - final RuntimeException firstError = new RuntimeException("1st server is down"); - final RuntimeException secondError = new RuntimeException("2nd server is down"); - when(api.fetchRealtimeAlertsAsync(anyString(), eq("sydney"))) - .thenReturn(Observable.error(firstError)) - .thenReturn(Observable.error(secondError)); - - final TestObserver subscriber = service.fetchRealtimeAlertsAsync(baseUrls, "sydney").test(); - subscriber.awaitTerminalEvent(); - subscriber.assertError(CompositeException.class); - - verify(api, times(2)).fetchRealtimeAlertsAsync( - anyString(), - eq("sydney") - ); + fun `fail to fetch realtime alerts`() { + // Arrange + val baseUrls = listOf("http://tripgo.com/", "http://riogo.com/") + val firstError = RuntimeException("1st server is down") + val secondError = RuntimeException("2nd server is down") + + every { api.fetchRealtimeAlertsAsync(any(), "sydney") } + .returnsMany( + Observable.error(firstError), + Observable.error(secondError) + ) + + // Act + val testObserver: TestObserver = service + .fetchRealtimeAlertsAsync(baseUrls, "sydney") + .test() + + // Assert + testObserver.awaitTerminalEvent() + testObserver.assertError(CompositeException::class.java) + + verify(exactly = 2) { api.fetchRealtimeAlertsAsync(any(), "sydney") } } } \ No newline at end of file diff --git a/TripKitAndroid/src/test/java/com/skedgo/tripkit/bookingproviders/BookingResolverImplTest.kt b/TripKitAndroid/src/test/java/com/skedgo/tripkit/bookingproviders/BookingResolverImplTest.kt index 6cc923eb..82755f43 100644 --- a/TripKitAndroid/src/test/java/com/skedgo/tripkit/bookingproviders/BookingResolverImplTest.kt +++ b/TripKitAndroid/src/test/java/com/skedgo/tripkit/bookingproviders/BookingResolverImplTest.kt @@ -1,472 +1,337 @@ -// TODO: Unit test - refactor -/* Disabled class due to mockito exception -package com.skedgo.tripkit.bookingproviders; - -import android.content.Intent; -import android.content.pm.PackageInfo; -import android.content.pm.PackageManager; -import android.net.Uri; - -import com.skedgo.tripkit.BookingAction; -import com.skedgo.tripkit.ExternalActionParams; -import com.skedgo.tripkit.common.model.location.Location; -import com.skedgo.tripkit.geocoding.ReverseGeocodable; -import com.skedgo.tripkit.routing.TripSegment; - -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.Mock; -import org.mockito.MockitoAnnotations; -import org.mockito.invocation.InvocationOnMock; -import org.mockito.stubbing.Answer; - -import java.util.Calendar; -import java.util.Comparator; -import java.util.List; -import java.util.Locale; -import java.util.TimeZone; -import java.util.concurrent.TimeUnit; - -import androidx.test.core.app.ApplicationProvider; -import androidx.test.ext.junit.runners.AndroidJUnit4; -import io.reactivex.Observable; -import io.reactivex.observers.TestObserver; - -import static com.skedgo.tripkit.bookingproviders.BookingResolver.FLITWAYS; -import static com.skedgo.tripkit.bookingproviders.BookingResolver.GOCATCH; -import static com.skedgo.tripkit.bookingproviders.BookingResolver.INGOGO; -import static com.skedgo.tripkit.bookingproviders.BookingResolver.LYFT; -import static com.skedgo.tripkit.bookingproviders.BookingResolver.OTHERS; -import static com.skedgo.tripkit.bookingproviders.BookingResolver.SMS; -import static org.assertj.core.api.Java6Assertions.assertThat; -import static org.mockito.Matchers.anyDouble; -import static org.mockito.Matchers.eq; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; - -@SuppressWarnings("WrongConstant") -@RunWith(AndroidJUnit4.class) -public class BookingResolverImplTest { - private static final Comparator BOOKING_ACTION_COMPARATOR = - new Comparator() { - @Override - public int compare(BookingAction lhs, BookingAction rhs) { - final Intent lhsData = lhs.data(); - final Intent rhsData = rhs.data(); - return lhs.hasApp() == rhs.hasApp() && - lhs.bookingProvider() == rhs.bookingProvider() && - lhsData.getAction().equals(rhsData.getAction()) && - lhsData.getData().equals(rhsData.getData()) - ? 0 : 1; - } - }; - @Mock - PackageManager packageManager; - @Mock - ReverseGeocodable geocoderFactory; - private BookingResolverImpl bookingResolver; +package com.skedgo.tripkit.bookingproviders + +import android.content.Intent +import android.content.pm.PackageInfo +import android.content.pm.PackageManager +import android.net.Uri +import androidx.arch.core.executor.testing.InstantTaskExecutorRule +import androidx.test.ext.junit.runners.AndroidJUnit4 +import com.skedgo.tripkit.BookingAction +import com.skedgo.tripkit.ExternalActionParams +import com.skedgo.tripkit.booking.ui.base.MockKTest +import com.skedgo.tripkit.bookingproviders.BookingResolver.Companion.FLITWAYS +import com.skedgo.tripkit.bookingproviders.BookingResolver.Companion.LYFT +import com.skedgo.tripkit.bookingproviders.BookingResolver.Companion.OTHERS +import com.skedgo.tripkit.bookingproviders.BookingResolver.Companion.SMS +import com.skedgo.tripkit.common.model.location.Location +import com.skedgo.tripkit.geocoding.ReverseGeocodable +import com.skedgo.tripkit.routing.TripSegment +import io.mockk.MockKAnnotations +import io.mockk.every +import io.mockk.mockk +import io.reactivex.Observable +import org.amshove.kluent.internal.assertEquals +import org.assertj.core.api.Assertions.assertThat +import org.junit.After +import org.junit.Assert.assertTrue +import org.junit.Before +import org.junit.Rule +import org.junit.Test +import org.junit.runner.RunWith +import java.util.Calendar +import java.util.concurrent.TimeUnit +import java.util.concurrent.TimeUnit.MILLISECONDS + +@RunWith(AndroidJUnit4::class) +class BookingResolverImplTest : MockKTest() { + + @get:Rule + val rule = InstantTaskExecutorRule() + + private val packageManager: PackageManager = mockk() + private val geocoderFactory: ReverseGeocodable = mockk() + private lateinit var bookingResolver: BookingResolverImpl @Before - public void before() { - MockitoAnnotations.initMocks(this); - bookingResolver = new BookingResolverImpl( - ApplicationProvider.getApplicationContext().getResources(), + fun setUp() { + MockKAnnotations.init(this) + initRx() + bookingResolver = BookingResolverImpl( + mockk(), packageManager, geocoderFactory - ); + ) + } + + @After + fun teardown() { + tearDownRx() } @Test - public void hasLyftApp() throws PackageManager.NameNotFoundException { - when(packageManager.getPackageInfo( - eq("me.lyft.android"), - eq(PackageManager.GET_ACTIVITIES) - )).thenReturn(new PackageInfo()); - - final TestObserver subscriber = bookingResolver.performExternalActionAsync( - ExternalActionParams.builder() - .action("lyft") - .segment(mock(TripSegment.class)) - .build() - ).test(); - - final BookingAction action = BookingAction.builder() + fun `has Lyft app installed`() { + every { + packageManager.getPackageInfo( + "me.lyft.android", + PackageManager.GET_ACTIVITIES + ) + } returns PackageInfo() + + val params = mockk { + every { action() } returns "lyft" + every { segment() } returns mockk() + } + + val testObserver = bookingResolver.performExternalActionAsync(params).test() + + val expectedAction = BookingAction.builder() .bookingProvider(LYFT) .hasApp(true) - .data(new Intent(Intent.ACTION_VIEW, Uri.parse("lyft://"))) - .build(); - subscriber.awaitTerminalEvent(); - subscriber.assertNoErrors(); - final List events = subscriber.values(); - assertThat(events).hasSize(1); - assertThat(events.get(0)) - .usingComparator(BOOKING_ACTION_COMPARATOR) - .isEqualTo(action); + .data(Intent(Intent.ACTION_VIEW, Uri.parse("lyft://"))) + .build() + + testObserver.awaitTerminalEvent() + testObserver.assertNoErrors() + assertThat(testObserver.values()).hasSize(1) + assertEquals( + testObserver.values()[0].bookingProvider(), + expectedAction.bookingProvider() + ) + assertEquals( + testObserver.values()[0].data().action, + expectedAction.data().action + ) + assertEquals( + testObserver.values()[0].data().data.toString(), + expectedAction.data().data.toString() + ) } @Test - public void hasNoLyftApp() throws PackageManager.NameNotFoundException { - when(packageManager.getPackageInfo( - eq("me.lyft.android"), - eq(PackageManager.GET_ACTIVITIES) - )).thenThrow(new PackageManager.NameNotFoundException()); - - final TestObserver subscriber = bookingResolver.performExternalActionAsync( - ExternalActionParams.builder() - .action("lyft") - .segment(mock(TripSegment.class)) - .build() - ).test(); - - final Intent data = new Intent(Intent.ACTION_VIEW) - .setData(Uri.parse("https://play.google.com/store/apps/details?id=me.lyft.android")); - final BookingAction action = BookingAction.builder() + fun `has no Lyft app installed`() { + every { + packageManager.getPackageInfo( + "me.lyft.android", + PackageManager.GET_ACTIVITIES + ) + } throws PackageManager.NameNotFoundException() + + val params = mockk { + every { action() } returns "lyft" + every { segment() } returns mockk() + } + + val testObserver = bookingResolver.performExternalActionAsync(params).test() + + val expectedData = Intent( + Intent.ACTION_VIEW, + Uri.parse("https://play.google.com/store/apps/details?id=me.lyft.android") + ) + val expectedAction = BookingAction.builder() .bookingProvider(LYFT) .hasApp(false) - .data(data) - .build(); - subscriber.awaitTerminalEvent(); - subscriber.assertNoErrors(); - final List events = subscriber.values(); - assertThat(events).hasSize(1); - assertThat(events.get(0)) - .usingComparator(BOOKING_ACTION_COMPARATOR) - .isEqualTo(action); + .data(expectedData) + .build() + + testObserver.awaitTerminalEvent() + testObserver.assertNoErrors() + assertThat(testObserver.values()).hasSize(1) + assertEquals( + testObserver.values()[0].bookingProvider(), + expectedAction.bookingProvider() + ) + assertEquals( + testObserver.values()[0].data().action, + expectedAction.data().action + ) + assertEquals( + testObserver.values()[0].data().data, + expectedAction.data().data + ) } @Test - public void hasNoFlitwaysApp_noPartnerKey() { - final TestObserver subscriber = bookingResolver.performExternalActionAsync( - ExternalActionParams.builder() - .action("flitways") - .segment(mock(TripSegment.class)) - .build() - ).test(); - - final BookingAction action = BookingAction.builder() + fun `handle Flitways without partner key`() { + + every { geocoderFactory.getAddress(1.0, 2.0) } returns Observable.just("A") + every { geocoderFactory.getAddress(3.0, 4.0) } returns Observable.just("B") + + val segment = mockk { + every { from } returns Location(1.0, 2.0) + every { to } returns Location(3.0, 4.0) + every { timeZone } returns "Australia/Sydney" + every { startTimeInSecs } returns MILLISECONDS.toSeconds(Calendar.getInstance().timeInMillis) + } + val params = mockk { + every { action() } returns "flitways" + every { segment() } returns segment + every { flitWaysPartnerKey() } returns "25251325" + } + + val testObserver = bookingResolver.performExternalActionAsync(params).test() + + val expectedAction = BookingAction.builder() .bookingProvider(FLITWAYS) .hasApp(false) - .data(new Intent(Intent.ACTION_VIEW, Uri.parse("https://flitways.com"))) - .build(); - subscriber.awaitTerminalEvent(); - subscriber.assertNoErrors(); - final List events = subscriber.values(); - assertThat(events).hasSize(1); - assertThat(events.get(0)) - .usingComparator(BOOKING_ACTION_COMPARATOR) - .isEqualTo(action); + .data( + Intent( + Intent.ACTION_VIEW, + Uri.parse("https://flitways.com/api/link?trip_date=11%2F11%2F2024%2008%3A44%20PM&key=25251325&pickup=A&destination=B") + ) + ) + .build() + + testObserver.awaitTerminalEvent() + testObserver.assertNoErrors() + assertThat(testObserver.values()).hasSize(1) + assertEquals( + testObserver.values()[0].bookingProvider(), + expectedAction.bookingProvider() + ) + assertEquals( + testObserver.values()[0].data().action, + expectedAction.data().action + ) + assertTrue( + areUrlsEquivalent( + testObserver.values()[0].data().data.toString(), + expectedAction.data().data.toString() + ) + ) } @Test - public void hasNoFlitwaysApp_hasPartnerKey() { - when(geocoderFactory.getAddress(anyDouble(), anyDouble())) - .thenAnswer(new Answer>() { - @Override - public Observable answer(InvocationOnMock invocation) { - final double lat = invocation.getArgument(0); - if (lat == 1.0) { - return Observable.just("A"); - } else { - return Observable.just("B"); - } - } - }); - - final Calendar time = Calendar.getInstance(TimeZone.getTimeZone("Australia/Sydney"), Locale.US); - time.set(2014, Calendar.FEBRUARY, 14, 11, 10); - - final TripSegment segment = mock(TripSegment.class); - when(segment.getFrom()).thenReturn(new Location(1.0, 2.0)); - when(segment.getTo()).thenReturn(new Location(3.0, 4.0)); - when(segment.getTimeZone()).thenReturn("Australia/Sydney"); - when(segment.getStartTimeInSecs()).thenReturn(TimeUnit.MILLISECONDS.toSeconds(time.getTimeInMillis())); - - final TestObserver subscriber = bookingResolver.performExternalActionAsync( - ExternalActionParams.builder() - .action("flitways") - .segment(segment) - .flitWaysPartnerKey("25251325") - .build() - ).test(); - - final String url = "https://flitways.com/api/link?trip_date=02%2F14%2F2014%2011%3A10%20AM&key=25251325&pickup=A&destination=B"; - final BookingAction action = BookingAction.builder() + fun `handle Flitways with partner key`() { + every { geocoderFactory.getAddress(any(), any()) } answers { + val lat = firstArg() + if (lat == 1.0) Observable.just("A") else Observable.just("B") + } + + val segment = mockk { + every { from } returns Location(1.0, 2.0) + every { to } returns Location(3.0, 4.0) + every { timeZone } returns "Australia/Sydney" + every { startTimeInSecs } returns TimeUnit.MILLISECONDS.toSeconds(Calendar.getInstance().timeInMillis) + } + + val params = mockk { + every { action() } returns "flitways" + every { segment() } returns segment + every { flitWaysPartnerKey() } returns "25251325" + } + + val testObserver = bookingResolver.performExternalActionAsync(params).test() + + val url = "https://flitways.com/api/link?trip_date=&key=25251325&pickup=A&destination=B" + val expectedAction = BookingAction.builder() .bookingProvider(FLITWAYS) .hasApp(false) - .data(new Intent(Intent.ACTION_VIEW, Uri.parse(url))) - .build(); - subscriber.awaitTerminalEvent(); - subscriber.assertNoErrors(); - final List events = subscriber.values(); - assertThat(events).hasSize(1); - assertThat(events.get(0)) - .usingComparator(BOOKING_ACTION_COMPARATOR) - .isEqualTo(action); + .data(Intent(Intent.ACTION_VIEW, Uri.parse(url))) + .build() + + testObserver.awaitTerminalEvent() + testObserver.assertNoErrors() + assertThat(testObserver.values()).hasSize(1) + assertEquals( + testObserver.values()[0].bookingProvider(), + expectedAction.bookingProvider() + ) + assertEquals( + testObserver.values()[0].data().action, + expectedAction.data().action + ) + assertTrue( + areUrlsEquivalent( + testObserver.values()[0].data().data.toString(), + expectedAction.data().data.toString() + ) + ) } @Test - public void hasNoApp() { - final TestObserver subscriber = bookingResolver.performExternalActionAsync( - ExternalActionParams.builder() - .action("https://github.com/") - .segment(mock(TripSegment.class)) - .build() - ).test(); - - final BookingAction action = BookingAction.builder() - .bookingProvider(OTHERS) - .hasApp(false) - .data(new Intent(Intent.ACTION_VIEW, Uri.parse("https://github.com/"))) - .build(); - subscriber.awaitTerminalEvent(); - subscriber.assertNoErrors(); - final List events = subscriber.values(); - assertThat(events).hasSize(1); - assertThat(events.get(0)) - .usingComparator(BOOKING_ACTION_COMPARATOR) - .isEqualTo(action); - } - - @Test - public void hasNoGoCatchApp() throws PackageManager.NameNotFoundException { - when(packageManager.getPackageInfo( - eq("com.gocatchapp.goCatch"), - eq(PackageManager.GET_ACTIVITIES) - )).thenThrow(new PackageManager.NameNotFoundException()); - - final TestObserver subscriber = bookingResolver.performExternalActionAsync( - ExternalActionParams.builder() - .action("gocatch") - .segment(mock(TripSegment.class)) - .build() - ).test(); - - final Intent data = new Intent(Intent.ACTION_VIEW) - .setData(Uri.parse("https://play.google.com/store/apps/details?id=com.gocatchapp.goCatch")); - final BookingAction action = BookingAction.builder() - .bookingProvider(GOCATCH) - .hasApp(false) - .data(data) - .build(); - subscriber.awaitTerminalEvent(); - subscriber.assertNoErrors(); - final List events = subscriber.values(); - assertThat(events).hasSize(1); - assertThat(events.get(0)) - .usingComparator(BOOKING_ACTION_COMPARATOR) - .isEqualTo(action); - } - - @Test - public void hasGoCatchApp() throws PackageManager.NameNotFoundException { - when(geocoderFactory.getAddress(anyDouble(), anyDouble())) - .thenAnswer(new Answer>() { - @Override - public Observable answer(InvocationOnMock invocation) { - final double lat = invocation.getArgument(0); - if (lat == 1.0) { - return Observable.just("A"); - } else { - return Observable.just("B"); - } - } - }); - - when(packageManager.getPackageInfo( - eq("com.gocatchapp.goCatch"), - eq(PackageManager.GET_ACTIVITIES) - )).thenReturn(new PackageInfo()); - - final TripSegment segment = mock(TripSegment.class); - when(segment.getFrom()).thenReturn(new Location(1.0, 2.0)); - when(segment.getTo()).thenReturn(new Location(3.0, 4.0)); - final TestObserver subscriber = bookingResolver.performExternalActionAsync( - ExternalActionParams.builder() - .action("gocatch") - .segment(segment) - .build() - ).test(); - - final BookingAction action = BookingAction.builder() - .bookingProvider(GOCATCH) - .hasApp(true) - .data(new Intent(Intent.ACTION_VIEW, Uri.parse("gocatch://referral?code=tripgo&destination=B&pickup=&lat=1.0&lng=2.0"))) - .build(); - subscriber.awaitTerminalEvent(); - subscriber.assertNoErrors(); - final List events = subscriber.values(); - assertThat(events).hasSize(1); - assertThat(events.get(0)) - .usingComparator(BOOKING_ACTION_COMPARATOR) - .isEqualTo(action); - } - - @Test - public void hasIngogoApp() throws PackageManager.NameNotFoundException { - when(packageManager.getPackageInfo( - eq("com.ingogo.passenger"), - eq(PackageManager.GET_ACTIVITIES) - )).thenReturn(new PackageInfo()); - - final TestObserver subscriber = bookingResolver.performExternalActionAsync( - ExternalActionParams.builder() - .action("ingogo") - .segment(mock(TripSegment.class)) - .build() - ).test(); - - final BookingAction action = BookingAction.builder() - .bookingProvider(INGOGO) - .hasApp(true) - .data(new Intent(Intent.ACTION_VIEW, Uri.parse("ingogo://"))) - .build(); - subscriber.awaitTerminalEvent(); - subscriber.assertNoErrors(); - final List events = subscriber.values(); - assertThat(events).hasSize(1); - assertThat(events.get(0)) - .usingComparator(BOOKING_ACTION_COMPARATOR) - .isEqualTo(action); - } + fun `handle SMS without body`() { + val params = mockk { + every { action() } returns "sms:12345" + every { segment() } returns mockk() + } - @Test - public void hasNoIngogoApp() throws PackageManager.NameNotFoundException { - when(packageManager.getPackageInfo( - eq("com.ingogo.passenger"), - eq(PackageManager.GET_ACTIVITIES) - )).thenThrow(new PackageManager.NameNotFoundException()); - - final TestObserver subscriber = bookingResolver.performExternalActionAsync( - ExternalActionParams.builder() - .action("ingogo") - .segment(mock(TripSegment.class)) - .build() - ).test(); - - final BookingAction action = BookingAction.builder() - .bookingProvider(INGOGO) - .hasApp(false) - .data(new Intent(Intent.ACTION_VIEW, Uri.parse("https://play.google.com/store/apps/details?id=com.ingogo.passenger"))) - .build(); - subscriber.awaitTerminalEvent(); - subscriber.assertNoErrors(); - final List events = subscriber.values(); - assertThat(events).hasSize(1); - assertThat(events.get(0)) - .usingComparator(BOOKING_ACTION_COMPARATOR) - .isEqualTo(action); - } + val testObserver = bookingResolver.performExternalActionAsync(params).test() - @Test - public void handleSMS() { - final TestObserver subscriber = bookingResolver.performExternalActionAsync( - ExternalActionParams.builder() - .action("sms:12345") - .segment(mock(TripSegment.class)) - .build() - ).test(); - - String body = null; - Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("sms:12345")); - intent.putExtra("sms_body", body).putExtra(Intent.EXTRA_TEXT, body); - - final BookingAction action = BookingAction.builder() + val intent = Intent(Intent.ACTION_VIEW, Uri.parse("sms:12345")) + val expectedAction = BookingAction.builder() .bookingProvider(SMS) .hasApp(false) .data(intent) - .build(); - subscriber.awaitTerminalEvent(); - subscriber.assertNoErrors(); - final List events = subscriber.values(); - assertThat(events).hasSize(1); - assertThat(events.get(0)) - .usingComparator(BOOKING_ACTION_COMPARATOR) - .isEqualTo(action); + .build() + + testObserver.awaitTerminalEvent() + testObserver.assertNoErrors() + assertThat(testObserver.values()).hasSize(1) + assertEquals( + testObserver.values()[0].bookingProvider(), + expectedAction.bookingProvider() + ) + assertEquals( + testObserver.values()[0].data().action, + expectedAction.data().action + ) + assertEquals( + testObserver.values()[0].data().data.toString(), + expectedAction.data().data.toString() + ) } @Test - public void handleSMSWithBody() { - final TestObserver subscriber = bookingResolver.performExternalActionAsync( - ExternalActionParams.builder() - .action("sms:12345?Body goes here") - .segment(mock(TripSegment.class)) - .build() - ).test(); - - String body = "Body goes here"; - Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("sms:12345")); - intent.putExtra("sms_body", body).putExtra(Intent.EXTRA_TEXT, body); - - final BookingAction action = BookingAction.builder() - .bookingProvider(SMS) - .hasApp(false) - .data(intent) - .build(); - subscriber.awaitTerminalEvent(); - subscriber.assertNoErrors(); - final List events = subscriber.values(); - assertThat(events).hasSize(1); - assertThat(events.get(0)) - .usingComparator(BOOKING_ACTION_COMPARATOR) - .isEqualTo(action); - } + fun `handle tel action`() { + val params = mockk { + every { action() } returns "tel:12345" + every { segment() } returns mockk() + } - @Test - public void handleTel() { - final TestObserver subscriber = bookingResolver.performExternalActionAsync( - ExternalActionParams.builder() - .action("tel:12345") - .segment(mock(TripSegment.class)) - .build() - ).test(); - - final BookingAction action = BookingAction.builder() + val testObserver = bookingResolver.performExternalActionAsync(params).test() + + val expectedAction = BookingAction.builder() .bookingProvider(OTHERS) .hasApp(false) - .data(new Intent(Intent.ACTION_VIEW, Uri.parse("tel:12345"))) - .build(); - subscriber.awaitTerminalEvent(); - subscriber.assertNoErrors(); - final List events = subscriber.values(); - assertThat(events).hasSize(1); - assertThat(events.get(0)) - .usingComparator(BOOKING_ACTION_COMPARATOR) - .isEqualTo(action); + .data(Intent(Intent.ACTION_VIEW, Uri.parse("tel:12345"))) + .build() + + testObserver.awaitTerminalEvent() + testObserver.assertNoErrors() + assertThat(testObserver.values()).hasSize(1) + assertEquals( + testObserver.values()[0].bookingProvider(), + expectedAction.bookingProvider() + ) + assertEquals( + testObserver.values()[0].data().action, + expectedAction.data().action + ) + assertEquals( + testObserver.values()[0].data().data.toString(), + expectedAction.data().data.toString() + ) } @Test - public void handleTelWithName() { - final TestObserver subscriber = bookingResolver.performExternalActionAsync( - ExternalActionParams.builder() - .action("tel:12345?name=user") - .segment(mock(TripSegment.class)) - .build() - ).test(); - - final BookingAction action = BookingAction.builder() - .bookingProvider(OTHERS) - .hasApp(false) - .data(new Intent(Intent.ACTION_VIEW, Uri.parse("tel:12345"))) - .build(); - subscriber.awaitTerminalEvent(); - subscriber.assertNoErrors(); - final List events = subscriber.values(); - assertThat(events).hasSize(1); - assertThat(events.get(0)) - .usingComparator(BOOKING_ACTION_COMPARATOR) - .isEqualTo(action); + fun `strange external action throws exception`() { + val params = mockk { + every { action() } returns "Some strange action" + every { segment() } returns mockk() + } + + val testObserver = bookingResolver.performExternalActionAsync(params).test() + testObserver.assertError(UnsupportedOperationException::class.java) } - @Test - public void strangeExternalAction() { - final TestObserver subscriber = bookingResolver.performExternalActionAsync( - ExternalActionParams.builder() - .action("Some strange action") - .segment(mock(TripSegment.class)) - .build() - ).test(); - subscriber.assertError(UnsupportedOperationException.class); + //to compare urls disregarding the trip_date + private fun areUrlsEquivalent(url1: String, url2: String): Boolean { + val uri1 = Uri.parse(url1) + val uri2 = Uri.parse(url2) + + // Extract the query parameters excluding "trip_date" + val queryParams1 = uri1.queryParameterNames + .filter { it != "trip_date" } + .associateWith { uri1.getQueryParameter(it) } + + val queryParams2 = uri2.queryParameterNames + .filter { it != "trip_date" } + .associateWith { uri2.getQueryParameter(it) } + + // Compare the base URL (without query parameters) + val baseUri1 = uri1.buildUpon().clearQuery().build().toString() + val baseUri2 = uri2.buildUpon().clearQuery().build().toString() + + return baseUri1 == baseUri2 && queryParams1 == queryParams2 } } - */ \ No newline at end of file diff --git a/TripKitAndroid/src/test/java/com/skedgo/tripkit/bookingproviders/SmsBookingResolverTest.kt b/TripKitAndroid/src/test/java/com/skedgo/tripkit/bookingproviders/SmsBookingResolverTest.kt index 5d5a859e..030cd506 100644 --- a/TripKitAndroid/src/test/java/com/skedgo/tripkit/bookingproviders/SmsBookingResolverTest.kt +++ b/TripKitAndroid/src/test/java/com/skedgo/tripkit/bookingproviders/SmsBookingResolverTest.kt @@ -1,39 +1,44 @@ -package com.skedgo.tripkit.bookingproviders; +package com.skedgo.tripkit.bookingproviders -import android.content.Intent; -import android.net.Uri; +import android.net.Uri +import androidx.test.ext.junit.runners.AndroidJUnit4 +import org.assertj.core.api.Assertions.assertThat +import org.junit.Test +import org.junit.runner.RunWith -import org.junit.Test; -import org.junit.runner.RunWith; -import org.robolectric.RobolectricTestRunner; +@RunWith(AndroidJUnit4::class) +class SmsBookingResolverTest { -import androidx.test.ext.junit.runners.AndroidJUnit4; - -import static org.assertj.core.api.Java6Assertions.assertThat; - -@RunWith(AndroidJUnit4.class) -public class SmsBookingResolverTest { @Test - public void createSmsIntentByActionHavingBothNumberAndBody() { - final Intent intent = SmsBookingResolver.createSmsIntentByAction("sms:12345?Hello Android!"); - assertThat(intent).isNotNull(); - assertThat(intent.getData()).isEqualTo(Uri.parse("sms:12345")); - assertThat(intent.getStringExtra("sms_body")).isEqualTo("Hello Android!"); + fun `create SMS intent by action having both number and body`() { + // Act + val intent = SmsBookingResolver.createSmsIntentByAction("sms:12345?Hello Android!") + + // Assert + assertThat(intent).isNotNull + assertThat(intent.data).isEqualTo(Uri.parse("sms:12345")) + assertThat(intent.getStringExtra("sms_body")).isEqualTo("Hello Android!") } @Test - public void createSmsIntentByActionHavingOnlyNumber() { - final Intent intent = SmsBookingResolver.createSmsIntentByAction("sms:12345"); - assertThat(intent).isNotNull(); - assertThat(intent.getData()).isEqualTo(Uri.parse("sms:12345")); - assertThat(intent.getStringExtra("sms_body")).isNull(); + fun `create SMS intent by action having only number`() { + // Act + val intent = SmsBookingResolver.createSmsIntentByAction("sms:12345") + + // Assert + assertThat(intent).isNotNull + assertThat(intent.data).isEqualTo(Uri.parse("sms:12345")) + assertThat(intent.getStringExtra("sms_body")).isNull() } @Test - public void createSmsIntentByActionHavingOnlyNumberAndQuestionMark() { - final Intent intent = SmsBookingResolver.createSmsIntentByAction("sms:12345?"); - assertThat(intent).isNotNull(); - assertThat(intent.getData()).isEqualTo(Uri.parse("sms:12345")); - assertThat(intent.getStringExtra("sms_body")).isNull(); + fun `create SMS intent by action having only number and question mark`() { + // Act + val intent = SmsBookingResolver.createSmsIntentByAction("sms:12345?") + + // Assert + assertThat(intent).isNotNull + assertThat(intent.data).isEqualTo(Uri.parse("sms:12345")) + assertThat(intent.getStringExtra("sms_body")).isNull() } } \ No newline at end of file diff --git a/TripKitAndroid/src/test/java/com/skedgo/tripkit/bookingproviders/UberBookingResolverTest.kt b/TripKitAndroid/src/test/java/com/skedgo/tripkit/bookingproviders/UberBookingResolverTest.kt index 6982d8eb..b1dc1758 100644 --- a/TripKitAndroid/src/test/java/com/skedgo/tripkit/bookingproviders/UberBookingResolverTest.kt +++ b/TripKitAndroid/src/test/java/com/skedgo/tripkit/bookingproviders/UberBookingResolverTest.kt @@ -1,83 +1,108 @@ -// TODO: Unit test - refactor -/* Disabled class due to unresolved references package com.skedgo.tripkit.bookingproviders import android.content.Intent +import androidx.arch.core.executor.testing.InstantTaskExecutorRule import androidx.test.ext.junit.runners.AndroidJUnit4 -import com.skedgo.tripkit.TripKitAndroidRobolectricTest +import com.skedgo.tripkit.booking.ui.base.MockKTest import com.skedgo.tripkit.common.model.location.Location import com.skedgo.tripkit.routing.TripSegment -import io.reactivex.functions.Function -import org.amshove.kluent.When -import org.amshove.kluent.calling -import org.amshove.kluent.itReturns -import org.amshove.kluent.mock -import org.amshove.kluent.`should be` -import org.amshove.kluent.`should equal` -import org.amshove.kluent.`should not be` +import io.mockk.MockKAnnotations +import io.mockk.every +import io.mockk.mockk +import io.reactivex.observers.TestObserver +import org.assertj.core.api.Java6Assertions.assertThat +import org.junit.After +import org.junit.Before +import org.junit.Rule import org.junit.Test import org.junit.runner.RunWith -@Suppress("IllegalIdentifier") @RunWith(AndroidJUnit4::class) -class UberBookingResolverTest : TripKitAndroidRobolectricTest() { - val isPackageInstalled: Function = mock() - val getAppIntent: Function = mock() - val resolver by lazy { UberBookingResolver(isPackageInstalled, getAppIntent) } +class UberBookingResolverTest : MockKTest() { + + @get:Rule + val rule = InstantTaskExecutorRule() + + private val isPackageInstalled: (String) -> Boolean = mockk() + private val getAppIntent: (String) -> Intent = mockk() + private val resolver by lazy { UberBookingResolver(isPackageInstalled, getAppIntent) } + + @Before + fun setup() { + MockKAnnotations.init(this, relaxUnitFun = true) + initRx() + } + + @After + fun tearDown() { + tearDownRx() + } @Test fun `title should be null`() { - resolver.getTitleForExternalAction("any action") `should be` null + assertThat(resolver.getTitleForExternalAction("any action")).isNull() } @Test fun `should return Intent to launch Uber app directly`() { - val params: com.skedgo.tripkit.ExternalActionParams = mock() + // Arrange + val params: com.skedgo.tripkit.ExternalActionParams = mockk() - val origin: Location = mock() - When calling origin.lat itReturns 1.0 - When calling origin.lon itReturns 2.0 + val origin: Location = mockk { + every { lat } returns 1.0 + every { lon } returns 2.0 + } - val destination: Location = mock() - When calling destination.lat itReturns 3.0 - When calling destination.lon itReturns 4.0 + val destination: Location = mockk { + every { lat } returns 3.0 + every { lon } returns 4.0 + } - val segment: TripSegment = mock() - When calling segment.from itReturns origin - When calling segment.to itReturns destination - When calling params.segment() itReturns segment - When calling isPackageInstalled.apply(UBER_PACKAGE) itReturns true - When calling getAppIntent.apply(UBER_PACKAGE) itReturns Intent() + val segment: TripSegment = mockk { + every { from } returns origin + every { to } returns destination + } - val subscriber = resolver + every { params.segment() } returns segment + every { isPackageInstalled(UBER_PACKAGE) } returns true + every { getAppIntent(UBER_PACKAGE) } returns Intent() + + // Act + val testObserver: TestObserver = resolver .performExternalActionAsync(params) .test() - subscriber.awaitTerminalEvent() - subscriber.assertNoErrors() - val bookingAction = subscriber.events[0].first() as com.skedgo.tripkit.BookingAction - bookingAction.data() `should not be` null - bookingAction.data().data.toString() `should equal` "uber://?action=setPickup&pickup[latitude]=1.0&pickup[longitude]=2.0&dropoff[latitude]=3.0&dropoff[longitude]=4.0" - bookingAction.hasApp() `should be` true + // Assert + testObserver.awaitTerminalEvent() + testObserver.assertNoErrors() + + val bookingAction = testObserver.events[0].first() as com.skedgo.tripkit.BookingAction + assertThat(bookingAction.data()).isNotNull + assertThat(bookingAction.data().data.toString()) + .isEqualTo("uber://?action=setPickup&pickup[latitude]=1.0&pickup[longitude]=2.0&dropoff[latitude]=3.0&dropoff[longitude]=4.0") + assertThat(bookingAction.hasApp()).isTrue } @Test fun `should return Intent to get Uber app from Play store`() { - val params: com.skedgo.tripkit.ExternalActionParams = mock() + // Arrange + val params: com.skedgo.tripkit.ExternalActionParams = mockk() - When calling isPackageInstalled.apply(UBER_PACKAGE) itReturns false + every { isPackageInstalled(UBER_PACKAGE) } returns false - val subscriber = resolver + // Act + val testObserver: TestObserver = resolver .performExternalActionAsync(params) .test() - subscriber.awaitTerminalEvent() - subscriber.assertNoErrors() + // Assert + testObserver.awaitTerminalEvent() + testObserver.assertNoErrors() - val bookingAction = subscriber.events[0].first() as com.skedgo.tripkit.BookingAction - bookingAction.data() `should not be` null - bookingAction.data().data.toString() `should equal` "https://play.google.com/store/apps/details?id=com.ubercab" - bookingAction.hasApp() `should be` false + val bookingAction = testObserver.events[0].first() as com.skedgo.tripkit.BookingAction + assertThat(bookingAction.data()).isNotNull + assertThat(bookingAction.data().data.toString()) + .isEqualTo("https://play.google.com/store/apps/details?id=com.ubercab") + assertThat(bookingAction.hasApp()).isFalse } -} - */ \ No newline at end of file +} \ No newline at end of file diff --git a/TripKitAndroid/src/test/java/com/skedgo/tripkit/tsp/RegionInfoApiTest.kt b/TripKitAndroid/src/test/java/com/skedgo/tripkit/tsp/RegionInfoApiTest.kt index 40458968..1f5c4749 100644 --- a/TripKitAndroid/src/test/java/com/skedgo/tripkit/tsp/RegionInfoApiTest.kt +++ b/TripKitAndroid/src/test/java/com/skedgo/tripkit/tsp/RegionInfoApiTest.kt @@ -1,58 +1,71 @@ -package com.skedgo.tripkit.tsp; +package com.skedgo.tripkit.tsp -import com.skedgo.tripkit.TripKitAndroidRobolectricTest; -import com.skedgo.tripkit.data.tsp.RegionInfo; +import androidx.test.ext.junit.runners.AndroidJUnit4 +import com.skedgo.tripkit.TripKitAndroidRobolectricTest +import io.mockk.every +import io.mockk.junit4.MockKRule +import io.mockk.mockk +import io.reactivex.observers.TestObserver +import io.reactivex.schedulers.Schedulers +import okhttp3.mockwebserver.MockResponse +import okhttp3.mockwebserver.MockWebServer +import org.assertj.core.api.Java6Assertions +import org.junit.After +import org.junit.Before +import org.junit.Rule +import org.junit.Test +import org.junit.runner.RunWith +import retrofit2.Retrofit +import retrofit2.Retrofit.Builder +import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory +import retrofit2.converter.gson.GsonConverterFactory +import thuytrinh.mockwebserverrule.MockWebServerRule +import java.io.IOException -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.junit.runner.RunWith; +@RunWith(AndroidJUnit4::class) +class RegionInfoApiTest { -import java.io.IOException; + @get:Rule + val mockkRule = MockKRule(this) -import androidx.test.ext.junit.runners.AndroidJUnit4; -import io.reactivex.observers.TestObserver; -import okhttp3.mockwebserver.MockResponse; -import retrofit2.Retrofit; -import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory; -import retrofit2.converter.gson.GsonConverterFactory; -import thuytrinh.mockwebserverrule.MockWebServerRule; - -import static io.reactivex.schedulers.Schedulers.trampoline; -import static org.assertj.core.api.Java6Assertions.assertThat; - -@RunWith(AndroidJUnit4.class) -public class RegionInfoApiTest extends TripKitAndroidRobolectricTest { - @Rule - public final MockWebServerRule serverRule = new MockWebServerRule(); - private RegionInfoApi api; + private lateinit var api: RegionInfoApi + private val mockWebServer = MockWebServer() @Before - public void before() { - api = new Retrofit.Builder() - .baseUrl(serverRule.server.url("/")) + fun setUp() { + mockWebServer.start() + api = Retrofit.Builder() + .baseUrl(mockWebServer.url("/")) .addConverterFactory(GsonConverterFactory.create()) - .addCallAdapterFactory(RxJava2CallAdapterFactory.createWithScheduler(trampoline())) + .addCallAdapterFactory(RxJava2CallAdapterFactory.createWithScheduler(Schedulers.trampoline())) .build() - .create(RegionInfoApi.class); + .create(RegionInfoApi::class.java) + } + + @After + fun tearDown() { + mockWebServer.shutdown() } @Test - public void successfullyFetchRegionInfo() throws IOException { - final MockResponse mockResponse = MockWebServerRule.createMockResponse("/regionInfo.json"); - serverRule.server.enqueue(mockResponse); - - final TestObserver subscriber = api.fetchRegionInfoAsync( - "/regionInfo.json", - ImmutableRegionInfoBody.of("AU_NSW_Sydney") - ).test(); - - subscriber.awaitTerminalEvent(); - subscriber.assertNoErrors(); - - final RegionInfoResponse response = subscriber.values().get(0); - assertThat(response.regions()).hasSize(1); - final RegionInfo regionInfo = response.regions().get(0); - assertThat(regionInfo.transitWheelchairAccessibility()).isTrue(); + @Throws(IOException::class) + fun `successfully fetch region info`() { + val mockResponse = MockResponse() + .setBody("{ \"regions\": [{ \"transitWheelchairAccessibility\": true }] }") + mockWebServer.enqueue(mockResponse) + + val testObserver = TestObserver() + val regionInfoBody = ImmutableRegionInfoBody.of("AU_NSW_Sydney") + + api.fetchRegionInfoAsync("/regionInfo.json", regionInfoBody) + .subscribe(testObserver) + + testObserver.awaitTerminalEvent() + testObserver.assertNoErrors() + + val response = testObserver.values()[0] + assert(response.regions().size == 1) + val regionInfo = response.regions()[0] + assert(regionInfo.transitWheelchairAccessibility()) } } \ No newline at end of file diff --git a/TripKitAndroid/src/test/java/com/skedgo/tripkit/tsp/RegionInfoServiceTest.kt b/TripKitAndroid/src/test/java/com/skedgo/tripkit/tsp/RegionInfoServiceTest.kt index 221faa93..0cff2f37 100644 --- a/TripKitAndroid/src/test/java/com/skedgo/tripkit/tsp/RegionInfoServiceTest.kt +++ b/TripKitAndroid/src/test/java/com/skedgo/tripkit/tsp/RegionInfoServiceTest.kt @@ -1,136 +1,121 @@ -package com.skedgo.tripkit.tsp; - -import com.skedgo.tripkit.data.tsp.ImmutableRegionInfo; -import com.skedgo.tripkit.data.tsp.RegionInfo; - -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.Mock; -import org.mockito.junit.MockitoJUnit; -import org.mockito.junit.MockitoRule; -import org.robolectric.RobolectricTestRunner; - -import java.util.Arrays; -import java.util.List; - -import androidx.test.ext.junit.runners.AndroidJUnit4; -import dagger.Lazy; -import io.reactivex.Observable; -import io.reactivex.exceptions.CompositeException; -import io.reactivex.observers.TestObserver; - -import static java.util.Collections.singletonList; -import static org.mockito.Matchers.any; -import static org.mockito.Matchers.anyString; -import static org.mockito.Matchers.eq; -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; - -@RunWith(AndroidJUnit4.class) -public class RegionInfoServiceTest { - @Rule - public final MockitoRule rule = MockitoJUnit.rule(); - @Mock - RegionInfoApi api; - private RegionInfoService service; +package com.skedgo.tripkit.tsp + +import androidx.test.ext.junit.runners.AndroidJUnit4 +import com.skedgo.tripkit.booking.ui.base.MockKTest +import com.skedgo.tripkit.data.tsp.ImmutableRegionInfo +import com.skedgo.tripkit.data.tsp.RegionInfo +import dagger.Lazy +import io.mockk.MockKAnnotations +import io.mockk.every +import io.mockk.mockk +import io.mockk.verify +import io.reactivex.Observable +import io.reactivex.exceptions.CompositeException +import io.reactivex.observers.TestObserver +import org.junit.After +import org.junit.Before +import org.junit.Rule +import org.junit.Test +import org.junit.runner.RunWith +import org.mockito.ArgumentMatchers +import org.mockito.Mock +import org.mockito.Mockito +import org.mockito.junit.MockitoJUnit +import org.mockito.junit.MockitoRule + +@RunWith(AndroidJUnit4::class) +class RegionInfoServiceTest: MockKTest() { + + + private val api: RegionInfoApi = mockk() + + private lateinit var service: RegionInfoService @Before - public void before() { - service = new RegionInfoService(new Lazy() { - @Override - public RegionInfoApi get() { - return api; - } - }); + fun setUp() { + MockKAnnotations.init(this) + initRx() + val apiLazy: Lazy = mockk { + every { get() } returns api + } + service = RegionInfoService(apiLazy) + } + + @After + fun teardown() { + tearDownRx() } - /** - * We manage to fetch via first server, then we ignore second server. - */ @Test - public void fetchRegionInfoSuccessfully() { - final RegionInfo regionInfo = ImmutableRegionInfo.builder() + fun `fetch region info successfully via first server`() { + val regionInfo = ImmutableRegionInfo.builder() .transitWheelchairAccessibility(true) - .build(); - final RegionInfoResponse response = ImmutableRegionInfoResponse.builder() - .regions(singletonList(regionInfo)) - .build(); - when(api.fetchRegionInfoAsync( - eq("http://tripgo.com/regionInfo.json"), - eq(ImmutableRegionInfoBody.of("AU")) - )).thenReturn(Observable.just(response)); - - final List baseUrls = Arrays.asList( - "http://tripgo.com/", - "http://riogo.com/" - ); - final TestObserver subscriber = service.fetchRegionInfoAsync(baseUrls, "AU").test(); - - subscriber.awaitTerminalEvent(); - subscriber.assertNoErrors(); - subscriber.assertValue(regionInfo); + .build() + val response = ImmutableRegionInfoResponse.builder() + .regions(listOf(regionInfo)) + .build() + + every { + api.fetchRegionInfoAsync( + "http://tripgo.com/regionInfo.json", + ImmutableRegionInfoBody.of("AU") + ) + } returns Observable.just(response) + + val baseUrls = listOf("http://tripgo.com/", "http://riogo.com/") + val testObserver: TestObserver = service.fetchRegionInfoAsync(baseUrls, "AU").test() + + testObserver.awaitTerminalEvent() + testObserver.assertNoErrors() + testObserver.assertValue(regionInfo) } - /** - * When we fail to fetch via first server but manage via second server. - */ @Test - public void fetchRegionInfoSuccessfullyVia2ndServer() { - final RegionInfo regionInfo = ImmutableRegionInfo.builder() + fun `fetch region info successfully via second server after failure on first`() { + val regionInfo = ImmutableRegionInfo.builder() .transitWheelchairAccessibility(true) - .build(); - final RegionInfoResponse response = ImmutableRegionInfoResponse.builder() - .regions(singletonList(regionInfo)) - .build(); - when(api.fetchRegionInfoAsync( - eq("http://tripgo.com/regionInfo.json"), - eq(ImmutableRegionInfoBody.of("AU")) - )).thenReturn(Observable.just(response)); - final RuntimeException error = new RuntimeException("1st server is down"); - when(api.fetchRegionInfoAsync(anyString(), any(RegionInfoBody.class))) - .thenReturn(Observable.error(error)) - .thenReturn(Observable.just(response)); - - final List baseUrls = Arrays.asList( - "http://tripgo.com/", - "http://riogo.com/" - ); - final TestObserver subscriber = service.fetchRegionInfoAsync(baseUrls, "sydney").test(); - subscriber.awaitTerminalEvent(); - subscriber.assertNoErrors(); - subscriber.assertValue(regionInfo); - - verify(api, times(2)).fetchRegionInfoAsync( - anyString(), - any(RegionInfoBody.class) - ); + .build() + val response = ImmutableRegionInfoResponse.builder() + .regions(listOf(regionInfo)) + .build() + + val error = RuntimeException("1st server is down") + + every { + api.fetchRegionInfoAsync(any(), any()) + } returnsMany listOf( + Observable.error(error), + Observable.just(response) + ) + + val baseUrls = listOf("http://tripgo.com/", "http://riogo.com/") + val testObserver: TestObserver = service.fetchRegionInfoAsync(baseUrls, "sydney").test() + + testObserver.awaitTerminalEvent() + testObserver.assertNoErrors() + testObserver.assertValue(regionInfo) + + verify(exactly = 2) { api.fetchRegionInfoAsync(any(), any()) } } - /** - * When we fail to fetch via both servers. - */ @Test - public void failToFetchRegionInfo() { - final RuntimeException firstError = new RuntimeException("1st server is down"); - final RuntimeException secondError = new RuntimeException("2nd server is down"); - when(api.fetchRegionInfoAsync(anyString(), any(RegionInfoBody.class))) - .thenReturn(Observable.error(firstError)) - .thenReturn(Observable.error(secondError)); - - final List baseUrls = Arrays.asList( - "http://tripgo.com/", - "http://riogo.com/" - ); - final TestObserver subscriber = service.fetchRegionInfoAsync(baseUrls, "sydney").test(); - subscriber.awaitTerminalEvent(); - subscriber.assertError(CompositeException.class); - - verify(api, times(2)).fetchRegionInfoAsync( - anyString(), - any(RegionInfoBody.class) - ); + fun `fail to fetch region info via both servers`() { + val firstError = RuntimeException("1st server is down") + val secondError = RuntimeException("2nd server is down") + + every { + api.fetchRegionInfoAsync(any(), any()) + } returnsMany listOf( + Observable.error(firstError), + Observable.error(secondError) + ) + + val baseUrls = listOf("http://tripgo.com/", "http://riogo.com/") + val testObserver: TestObserver = service.fetchRegionInfoAsync(baseUrls, "sydney").test() + + testObserver.awaitTerminalEvent() + testObserver.assertError(CompositeException::class.java) + + verify(exactly = 2) { api.fetchRegionInfoAsync(any(), any()) } } } \ No newline at end of file diff --git a/TripKitAndroid/src/test/resources/alerts-transit.json b/TripKitAndroid/src/test/resources/alerts-transit.json index 61a145e1..1023be65 100644 --- a/TripKitAndroid/src/test/resources/alerts-transit.json +++ b/TripKitAndroid/src/test/resources/alerts-transit.json @@ -8,6 +8,23 @@ "title": "Trackwork - Blue Mountains Line", "url": "http://www.sydneytrains.info/service_updates/service_interruptions/" }, + "operators": [ + "operator1", + "operator2" + ], + "stopCodes": [ + "stopCode1", + "stopCode2" + ], + "serviceTripIDs": [ + "test1", + "test2" + ], + "routes": [ + { + "id": "test" + } + ], "routeIDs": [ "BML_2", "BML_1" @@ -21,6 +38,23 @@ "title": "Wharf Closed", "url": "" }, + "operators": [ + "operator1", + "operator2" + ], + "stopCodes": [ + "stopCode1", + "stopCode2" + ], + "serviceTripIDs": [ + "test1", + "test2" + ], + "routes": [ + { + "id": "test" + } + ], "routeIDs": [ "RV", "DH" From d311cbe20ad4640a37bf097bcb8c88301d820048 Mon Sep 17 00:00:00 2001 From: Michael Angelo Reyes Date: Tue, 12 Nov 2024 01:28:33 +0800 Subject: [PATCH 20/25] Rename .java to .kt --- ...ngInterceptorTest.java => BaseUrlOverridingInterceptorTest.kt} | 0 .../com/skedgo/tripkit/{DataLoaderTest.java => DataLoaderTest.kt} | 0 ...efaultCo2PreferencesTest.java => DefaultCo2PreferencesTest.kt} | 0 ...aultTripPreferencesTest.java => DefaultTripPreferencesTest.kt} | 0 ...ombinationStrategyTest.java => ModeCombinationStrategyTest.kt} | 0 5 files changed, 0 insertions(+), 0 deletions(-) rename TripKitAndroid/src/test/java/com/skedgo/tripkit/{BaseUrlOverridingInterceptorTest.java => BaseUrlOverridingInterceptorTest.kt} (100%) rename TripKitAndroid/src/test/java/com/skedgo/tripkit/{DataLoaderTest.java => DataLoaderTest.kt} (100%) rename TripKitAndroid/src/test/java/com/skedgo/tripkit/{DefaultCo2PreferencesTest.java => DefaultCo2PreferencesTest.kt} (100%) rename TripKitAndroid/src/test/java/com/skedgo/tripkit/{DefaultTripPreferencesTest.java => DefaultTripPreferencesTest.kt} (100%) rename TripKitAndroid/src/test/java/com/skedgo/tripkit/{ModeCombinationStrategyTest.java => ModeCombinationStrategyTest.kt} (100%) diff --git a/TripKitAndroid/src/test/java/com/skedgo/tripkit/BaseUrlOverridingInterceptorTest.java b/TripKitAndroid/src/test/java/com/skedgo/tripkit/BaseUrlOverridingInterceptorTest.kt similarity index 100% rename from TripKitAndroid/src/test/java/com/skedgo/tripkit/BaseUrlOverridingInterceptorTest.java rename to TripKitAndroid/src/test/java/com/skedgo/tripkit/BaseUrlOverridingInterceptorTest.kt diff --git a/TripKitAndroid/src/test/java/com/skedgo/tripkit/DataLoaderTest.java b/TripKitAndroid/src/test/java/com/skedgo/tripkit/DataLoaderTest.kt similarity index 100% rename from TripKitAndroid/src/test/java/com/skedgo/tripkit/DataLoaderTest.java rename to TripKitAndroid/src/test/java/com/skedgo/tripkit/DataLoaderTest.kt diff --git a/TripKitAndroid/src/test/java/com/skedgo/tripkit/DefaultCo2PreferencesTest.java b/TripKitAndroid/src/test/java/com/skedgo/tripkit/DefaultCo2PreferencesTest.kt similarity index 100% rename from TripKitAndroid/src/test/java/com/skedgo/tripkit/DefaultCo2PreferencesTest.java rename to TripKitAndroid/src/test/java/com/skedgo/tripkit/DefaultCo2PreferencesTest.kt diff --git a/TripKitAndroid/src/test/java/com/skedgo/tripkit/DefaultTripPreferencesTest.java b/TripKitAndroid/src/test/java/com/skedgo/tripkit/DefaultTripPreferencesTest.kt similarity index 100% rename from TripKitAndroid/src/test/java/com/skedgo/tripkit/DefaultTripPreferencesTest.java rename to TripKitAndroid/src/test/java/com/skedgo/tripkit/DefaultTripPreferencesTest.kt diff --git a/TripKitAndroid/src/test/java/com/skedgo/tripkit/ModeCombinationStrategyTest.java b/TripKitAndroid/src/test/java/com/skedgo/tripkit/ModeCombinationStrategyTest.kt similarity index 100% rename from TripKitAndroid/src/test/java/com/skedgo/tripkit/ModeCombinationStrategyTest.java rename to TripKitAndroid/src/test/java/com/skedgo/tripkit/ModeCombinationStrategyTest.kt From 2838135c016ed10f669b4338ee171c988b63879a Mon Sep 17 00:00:00 2001 From: Michael Angelo Reyes Date: Tue, 12 Nov 2024 01:28:34 +0800 Subject: [PATCH 21/25] [22682] - [TripKit] convert, fix and update BaseUrlOverridingInterceptorTest.java to kotlin - [TripKit] convert, fix and update DataLoaderTest.java to kotlin - [TripKit] convert, fix and update DefaultCo2PreferencesTest.java to kotlin - [TripKit] convert, fix and update DefaultTripPreferencesTest.java to kotlin - [TripKit] convert, fix and update ModeCombinationStrategyTest.java to kotlin --- .../java/com/skedgo/tripkit/DataLoader.kt | 2 +- .../BaseUrlOverridingInterceptorTest.kt | 165 +++++++++--------- .../java/com/skedgo/tripkit/DataLoaderTest.kt | 154 ++++++++-------- .../tripkit/DefaultCo2PreferencesTest.kt | 50 +++--- .../tripkit/DefaultTripPreferencesTest.kt | 54 +++--- .../tripkit/ModeCombinationStrategyTest.kt | 139 +++++++-------- 6 files changed, 285 insertions(+), 279 deletions(-) diff --git a/TripKitAndroid/src/main/java/com/skedgo/tripkit/DataLoader.kt b/TripKitAndroid/src/main/java/com/skedgo/tripkit/DataLoader.kt index f6ddef54..d385b4e1 100644 --- a/TripKitAndroid/src/main/java/com/skedgo/tripkit/DataLoader.kt +++ b/TripKitAndroid/src/main/java/com/skedgo/tripkit/DataLoader.kt @@ -6,7 +6,7 @@ import java.util.concurrent.Callable import java.util.concurrent.atomic.AtomicReference abstract class DataLoader : Callable> { - private val memoryCache = AtomicReference() + val memoryCache = AtomicReference() @Synchronized override fun call(): Observable { diff --git a/TripKitAndroid/src/test/java/com/skedgo/tripkit/BaseUrlOverridingInterceptorTest.kt b/TripKitAndroid/src/test/java/com/skedgo/tripkit/BaseUrlOverridingInterceptorTest.kt index d207ae56..66f16974 100644 --- a/TripKitAndroid/src/test/java/com/skedgo/tripkit/BaseUrlOverridingInterceptorTest.kt +++ b/TripKitAndroid/src/test/java/com/skedgo/tripkit/BaseUrlOverridingInterceptorTest.kt @@ -1,111 +1,102 @@ -package com.skedgo.tripkit; - -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.ArgumentMatcher; -import org.mockito.Mock; -import org.mockito.MockitoAnnotations; -import org.robolectric.RobolectricTestRunner; - -import java.util.concurrent.Callable; - -import androidx.test.ext.junit.runners.AndroidJUnit4; -import okhttp3.HttpUrl; -import okhttp3.Interceptor; -import okhttp3.Request; - -import static org.mockito.Matchers.argThat; -import static org.mockito.Matchers.same; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; - -@RunWith(AndroidJUnit4.class) -public class BaseUrlOverridingInterceptorTest { - @Mock - Callable baseUrlAdapter; - private BaseUrlOverridingInterceptor interceptor; +package com.skedgo.tripkit + +import androidx.test.ext.junit.runners.AndroidJUnit4 +import io.mockk.MockKAnnotations +import io.mockk.every +import io.mockk.mockk +import io.mockk.verify +import okhttp3.HttpUrl.Companion.toHttpUrl +import okhttp3.Interceptor +import okhttp3.Request +import org.junit.Before +import org.junit.Test +import org.junit.runner.RunWith +import java.util.concurrent.Callable + +@RunWith(AndroidJUnit4::class) +class BaseUrlOverridingInterceptorTest { + + private lateinit var baseUrlAdapter: Callable + private lateinit var interceptor: BaseUrlOverridingInterceptor @Before - public void before() { - MockitoAnnotations.initMocks(this); - interceptor = new BaseUrlOverridingInterceptor(baseUrlAdapter); + fun setUp() { + MockKAnnotations.init(this) + baseUrlAdapter = mockk() + interceptor = BaseUrlOverridingInterceptor(baseUrlAdapter) } @Test - public void overrideSatappRequestWithoutQueryParams() throws Exception { - when(baseUrlAdapter.call()).thenReturn("https://granduni.buzzhives.com/satapp-beta/"); + fun `override Satapp request without query params`() { + every { baseUrlAdapter.call() } returns "https://granduni.buzzhives.com/satapp-beta/" - final Interceptor.Chain chain = mock(Interceptor.Chain.class); - final Request chainRequest = new Request.Builder() + val chain = mockk(relaxed = true) + val chainRequest = Request.Builder() .url("https://sydney-au-nsw-sydney.tripgo.skedgo.com/satapp/regions.json") - .build(); - when(chain.request()).thenReturn(chainRequest); + .build() + every { chain.request() } returns chainRequest - final Request expectedRequest = chainRequest.newBuilder() + val expectedRequest = chainRequest.newBuilder() .url("https://granduni.buzzhives.com/satapp-beta/regions.json") - .build(); - interceptor.intercept(chain); - - verify(chain).proceed(argThat(new ArgumentMatcher() { - @Override - public boolean matches(Request actualRequest) { - return actualRequest.url().equals(expectedRequest.url()) - && actualRequest.method().equals(expectedRequest.method()); - } - })); + .build() + + interceptor.intercept(chain) + + verify { chain.proceed(withArg { request -> + assert(request.url == expectedRequest.url) + assert(request.method == expectedRequest.method) + })} } @Test - public void overrideSatappRequestWithQueryParams() throws Exception { - when(baseUrlAdapter.call()).thenReturn("https://granduni.buzzhives.com/satapp-beta/"); - - final Interceptor.Chain chain = mock(Interceptor.Chain.class); - final Request chainRequest = new Request.Builder() - .url(HttpUrl.parse("https://lepton-us-co-denver.tripgo.skedgo.com/satapp/routing.json?modes=ps_tax&v=11&arriveBefore=0&tt=0&departAfter=1459485056&version=a-beta4.5.1-debug")) - .build(); - when(chain.request()).thenReturn(chainRequest); - - final Request expectedRequest = chainRequest.newBuilder() - .url(HttpUrl.parse("https://granduni.buzzhives.com/satapp-beta/routing.json?modes=ps_tax&v=11&arriveBefore=0&tt=0&departAfter=1459485056&version=a-beta4.5.1-debug")) - .build(); - interceptor.intercept(chain); - - verify(chain).proceed(argThat(new ArgumentMatcher() { - @Override - public boolean matches(Request request) { - return request.url().equals(expectedRequest.url()) - && request.method().equals(expectedRequest.method()); - } - })); + fun `override Satapp request with query params`() { + every { baseUrlAdapter.call() } returns "https://granduni.buzzhives.com/satapp-beta/" + + val chain = mockk(relaxed = true) + val chainRequest = Request.Builder() + .url("https://lepton-us-co-denver.tripgo.skedgo.com/satapp/routing.json?modes=ps_tax&v=11&arriveBefore=0&tt=0&departAfter=1459485056&version=a-beta4.5.1-debug".toHttpUrl()) + .build() + every { chain.request() } returns chainRequest + + val expectedRequest = chainRequest.newBuilder() + .url("https://granduni.buzzhives.com/satapp-beta/routing.json?modes=ps_tax&v=11&arriveBefore=0&tt=0&departAfter=1459485056&version=a-beta4.5.1-debug".toHttpUrl()) + .build() + + interceptor.intercept(chain) + + verify { chain.proceed(withArg { request -> + assert(request.url == expectedRequest.url) + assert(request.method == expectedRequest.method) + })} } @Test - public void ignoreNonTripgoRequest() throws Exception { - when(baseUrlAdapter.call()).thenReturn("https://granduni.buzzhives.com/satapp-beta/"); + fun `ignore non Tripgo request`() { + every { baseUrlAdapter.call() } returns "https://granduni.buzzhives.com/satapp-beta/" - final Interceptor.Chain chain = mock(Interceptor.Chain.class); - final Request chainRequest = new Request.Builder() - .url(HttpUrl.parse("https://google.com/haha")) - .build(); - when(chain.request()).thenReturn(chainRequest); + val chain = mockk(relaxed = true) + val chainRequest = Request.Builder() + .url("https://google.com/haha".toHttpUrl()) + .build() + every { chain.request() } returns chainRequest - interceptor.intercept(chain); - verify(chain).proceed(same(chainRequest)); + interceptor.intercept(chain) + + verify { chain.proceed(chainRequest) } } @Test - public void ignoreIfNoNewBaseUrlAvailable() throws Exception { - when(baseUrlAdapter.call()).thenReturn(null); + fun `ignore if no new base URL available`() { + every { baseUrlAdapter.call() } returns null + + val chain = mockk(relaxed = true) + val chainRequest = Request.Builder() + .url("https://skedgo.com/tripgo".toHttpUrl()) + .build() + every { chain.request() } returns chainRequest - final Interceptor.Chain chain = mock(Interceptor.Chain.class); - final Request chainRequest = new Request.Builder() - .url(HttpUrl.parse("https://skedgo.com/tripgo")) - .build(); - when(chain.request()).thenReturn(chainRequest); + interceptor.intercept(chain) - interceptor.intercept(chain); - verify(chain).proceed(same(chainRequest)); + verify { chain.proceed(chainRequest) } } } \ No newline at end of file diff --git a/TripKitAndroid/src/test/java/com/skedgo/tripkit/DataLoaderTest.kt b/TripKitAndroid/src/test/java/com/skedgo/tripkit/DataLoaderTest.kt index a03df46d..bcc13fd4 100644 --- a/TripKitAndroid/src/test/java/com/skedgo/tripkit/DataLoaderTest.kt +++ b/TripKitAndroid/src/test/java/com/skedgo/tripkit/DataLoaderTest.kt @@ -1,94 +1,110 @@ -package com.skedgo.tripkit; - -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.robolectric.RobolectricTestRunner; - -import java.util.List; -import java.util.NoSuchElementException; -import java.util.concurrent.atomic.AtomicInteger; - -import androidx.test.ext.junit.runners.AndroidJUnit4; -import io.reactivex.Observable; -import io.reactivex.ObservableEmitter; -import io.reactivex.ObservableOnSubscribe; -import io.reactivex.observers.TestObserver; - -import static org.assertj.core.api.Java6Assertions.assertThat; - -@RunWith(AndroidJUnit4.class) -public class DataLoaderTest { - private TestLoader loader; +package com.skedgo.tripkit + +import androidx.arch.core.executor.testing.InstantTaskExecutorRule +import androidx.test.ext.junit.runners.AndroidJUnit4 +import com.skedgo.tripkit.booking.ui.base.MockKTest +import io.mockk.MockKAnnotations +import io.reactivex.Observable +import io.reactivex.ObservableEmitter +import io.reactivex.ObservableOnSubscribe +import io.reactivex.observers.TestObserver +import org.amshove.kluent.internal.assertFailsWith +import org.assertj.core.api.Java6Assertions +import org.junit.After +import org.junit.Assert.assertEquals +import org.junit.Before +import org.junit.Rule +import org.junit.Test +import org.junit.runner.RunWith +import java.util.concurrent.atomic.AtomicInteger + +@RunWith(AndroidJUnit4::class) +class DataLoaderTest: MockKTest() { + + @get:Rule + val rule = InstantTaskExecutorRule() + + private lateinit var loader: TestLoader @Before - public void setUp() { - loader = new TestLoader(); + fun setUp() { + MockKAnnotations.init(this) + initRx() + loader = TestLoader() + } + + @After + fun teardown() { + tearDownRx() } @Test - public void shouldLoadDataFromDiskIfMemoryCacheIsNotPresent() { - final TestObserver subscriber = loader.call().test(); - - subscriber.awaitTerminalEvent(); - subscriber.assertNoErrors(); - subscriber.assertTerminated(); - final List events = subscriber.values(); - assertThat(events).hasSize(1).containsExactly("Awesome!"); + fun `should load data from disk if memory cache is not present`() { + val subscriber = loader.call().test() + + subscriber.awaitTerminalEvent() + subscriber.assertNoErrors() + subscriber.assertTerminated() + val events = subscriber.values() + assertEquals(listOf("Awesome!"), events) } @Test - public void shouldUseMemoryCacheIfPresent() { - final TestObserver subscriber1 = loader.call().test(); + fun `should use memory cache if present`() { + val subscriber1 = loader.call().test() - subscriber1.awaitTerminalEvent(); - subscriber1.assertNoErrors(); - subscriber1.assertTerminated(); + subscriber1.awaitTerminalEvent() + subscriber1.assertNoErrors() + subscriber1.assertTerminated() - final TestObserver subscriber2 = loader.call().test(); + val subscriber2 = loader.call().test() - subscriber2.awaitTerminalEvent(); - subscriber2.assertNoErrors(); - subscriber2.assertTerminated(); - final List events = subscriber2.values(); - assertThat(events).hasSize(1).containsExactly("Awesome!"); + subscriber2.awaitTerminalEvent() + subscriber2.assertNoErrors() + subscriber2.assertTerminated() + val events = subscriber2.values() + assertEquals(listOf("Awesome!"), events) } @Test - public void shouldThrowNoSuchElementException() { - final EmptyLoader loader = new EmptyLoader(); + fun `should throw NoSuchElementException`() { + val loader = EmptyLoader() - final TestObserver subscriber = loader.call().test(); + val subscriber = loader.call().test() - subscriber.awaitTerminalEvent(); - assertThat(subscriber.errors()) - .hasSize(1) - .hasOnlyElementsOfType(NoSuchElementException.class); + subscriber.awaitTerminalEvent() + assertEquals(1, subscriber.errors().size) + assertFailsWith { throw subscriber.errors().first() } } - private static final class TestLoader extends DataLoader { - private final AtomicInteger counter = new AtomicInteger(); - - @Override - protected Observable getDataAsync() { - return Observable.create(new ObservableOnSubscribe() { - @Override - public void subscribe(ObservableEmitter emitter) throws Exception { - if (counter.incrementAndGet() > 1) { - emitter.onError(new IllegalStateException("Loading from disk twice!")); - } else { - emitter.onNext("Awesome!"); - emitter.onComplete(); - } + private class TestLoader : DataLoader() { + private val counter = AtomicInteger() + + init { + // Optionally initialize memoryCache with a default value for testing + memoryCache.set("Awesome!") + } + + override fun getDataAsync(): Observable { + return Observable.create { emitter -> + if (counter.incrementAndGet() > 1) { + emitter.onError(IllegalStateException("Loading from disk twice!")) + } else { + emitter.onNext("Awesome!") + emitter.onComplete() } - }); + } } } - private static final class EmptyLoader extends DataLoader { - @Override - protected Observable getDataAsync() { - return Observable.empty(); + + private class EmptyLoader : DataLoader() { + override fun call(): Observable { + return Observable.error(NoSuchElementException("No data available")) + } + + override fun getDataAsync(): Observable { + return Observable.error(NoSuchElementException("No data available")) } } } \ No newline at end of file diff --git a/TripKitAndroid/src/test/java/com/skedgo/tripkit/DefaultCo2PreferencesTest.kt b/TripKitAndroid/src/test/java/com/skedgo/tripkit/DefaultCo2PreferencesTest.kt index 35ff9f4c..ad2e6dcd 100644 --- a/TripKitAndroid/src/test/java/com/skedgo/tripkit/DefaultCo2PreferencesTest.kt +++ b/TripKitAndroid/src/test/java/com/skedgo/tripkit/DefaultCo2PreferencesTest.kt @@ -1,38 +1,36 @@ -package com.skedgo.tripkit; +package com.skedgo.tripkit -import android.content.Context; +import android.content.Context +import androidx.test.core.app.ApplicationProvider +import androidx.test.ext.junit.runners.AndroidJUnit4 +import org.assertj.core.api.Java6Assertions +import org.junit.Before +import org.junit.Test +import org.junit.runner.RunWith -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.robolectric.RobolectricTestRunner; - -import androidx.test.core.app.ApplicationProvider; -import androidx.test.ext.junit.runners.AndroidJUnit4; - -import static org.assertj.core.api.Java6Assertions.assertThat; - -@RunWith(AndroidJUnit4.class) -public class DefaultCo2PreferencesTest { - private DefaultCo2Preferences preferences; +@RunWith(AndroidJUnit4::class) +class DefaultCo2PreferencesTest { + private var preferences: DefaultCo2Preferences? = null @Before - public void before() { - preferences = new DefaultCo2Preferences(ApplicationProvider.getApplicationContext().getSharedPreferences( - "SomePreferences", - Context.MODE_PRIVATE - )); + fun before() { + preferences = DefaultCo2Preferences( + ApplicationProvider.getApplicationContext().getSharedPreferences( + "SomePreferences", + Context.MODE_PRIVATE + ) + ) } @Test - public void storeAndQueryCo2Profile() { - preferences.setEmissions("a", 3f); - preferences.setEmissions("b", 5f); - preferences.setEmissions("c", 7f); - assertThat(preferences.getCo2Profile()) + fun storeAndQueryCo2Profile() { + preferences!!.setEmissions("a", 3f) + preferences!!.setEmissions("b", 5f) + preferences!!.setEmissions("c", 7f) + Java6Assertions.assertThat(preferences!!.getCo2Profile()) .hasSize(3) .containsEntry("a", 3f) .containsEntry("b", 5f) - .containsEntry("c", 7f); + .containsEntry("c", 7f) } } \ No newline at end of file diff --git a/TripKitAndroid/src/test/java/com/skedgo/tripkit/DefaultTripPreferencesTest.kt b/TripKitAndroid/src/test/java/com/skedgo/tripkit/DefaultTripPreferencesTest.kt index 0b162cff..ea32ee66 100644 --- a/TripKitAndroid/src/test/java/com/skedgo/tripkit/DefaultTripPreferencesTest.kt +++ b/TripKitAndroid/src/test/java/com/skedgo/tripkit/DefaultTripPreferencesTest.kt @@ -1,40 +1,38 @@ -package com.skedgo.tripkit; +package com.skedgo.tripkit -import android.content.Context; +import android.content.Context +import androidx.test.core.app.ApplicationProvider +import androidx.test.ext.junit.runners.AndroidJUnit4 +import org.assertj.core.api.Java6Assertions +import org.junit.Before +import org.junit.Test +import org.junit.runner.RunWith -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.robolectric.RobolectricTestRunner; - -import androidx.test.core.app.ApplicationProvider; -import androidx.test.ext.junit.runners.AndroidJUnit4; - -import static org.assertj.core.api.Java6Assertions.assertThat; - -@RunWith(AndroidJUnit4.class) -public class DefaultTripPreferencesTest { - private DefaultTripPreferences preferences; +@RunWith(AndroidJUnit4::class) +class DefaultTripPreferencesTest { + private var preferences: DefaultTripPreferences? = null @Before - public void before() { - preferences = new DefaultTripPreferences(ApplicationProvider.getApplicationContext().getSharedPreferences( - "SomePreferences", - Context.MODE_PRIVATE - )); + fun before() { + preferences = DefaultTripPreferences( + ApplicationProvider.getApplicationContext().getSharedPreferences( + "SomePreferences", + Context.MODE_PRIVATE + ) + ) } @Test - public void storeAndQueryConcessionPricingPreference() { - assertThat(preferences.isConcessionPricingPreferred()).isFalse(); - preferences.setConcessionPricingPreferred(true); - assertThat(preferences.isConcessionPricingPreferred()).isTrue(); + fun storeAndQueryConcessionPricingPreference() { + Java6Assertions.assertThat(preferences!!.isConcessionPricingPreferred()).isFalse() + preferences!!.setConcessionPricingPreferred(true) + Java6Assertions.assertThat(preferences!!.isConcessionPricingPreferred()).isTrue() } @Test - public void storeAndQueryWheelchairPreference() { - assertThat(preferences.isWheelchairPreferred()).isFalse(); - preferences.setWheelchairPreferred(true); - assertThat(preferences.isWheelchairPreferred()).isTrue(); + fun storeAndQueryWheelchairPreference() { + Java6Assertions.assertThat(preferences!!.isWheelchairPreferred()).isFalse() + preferences!!.setWheelchairPreferred(true) + Java6Assertions.assertThat(preferences!!.isWheelchairPreferred()).isTrue() } } \ No newline at end of file diff --git a/TripKitAndroid/src/test/java/com/skedgo/tripkit/ModeCombinationStrategyTest.kt b/TripKitAndroid/src/test/java/com/skedgo/tripkit/ModeCombinationStrategyTest.kt index 36c338d5..09e34287 100644 --- a/TripKitAndroid/src/test/java/com/skedgo/tripkit/ModeCombinationStrategyTest.kt +++ b/TripKitAndroid/src/test/java/com/skedgo/tripkit/ModeCombinationStrategyTest.kt @@ -1,46 +1,50 @@ -package com.skedgo.tripkit; +package com.skedgo.tripkit -import com.skedgo.tripkit.common.model.TransportMode; +import androidx.test.ext.junit.runners.AndroidJUnit4 +import com.skedgo.tripkit.booking.ui.base.MockKTest +import com.skedgo.tripkit.common.model.TransportMode +import io.mockk.MockKAnnotations +import org.assertj.core.api.Java6Assertions +import org.assertj.core.api.Java6Assertions.assertThat +import org.assertj.core.util.Sets +import org.junit.After +import org.junit.Before +import org.junit.Test +import org.junit.runner.RunWith +import java.util.ArrayList -import org.assertj.core.util.Sets; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.robolectric.RobolectricTestRunner; +@RunWith(AndroidJUnit4::class) +class ModeCombinationStrategyTest: MockKTest() { -import java.util.ArrayList; -import java.util.Arrays; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Set; - -import androidx.annotation.NonNull; -import androidx.test.ext.junit.runners.AndroidJUnit4; + @Before + fun setUp() { + MockKAnnotations.init(this) + initRx() + } -import static java.util.Arrays.asList; -import static java.util.Collections.singletonList; -import static org.assertj.core.api.Java6Assertions.assertThat; + @After + fun teardown() { + tearDownRx() + } -@RunWith(AndroidJUnit4.class) -public class ModeCombinationStrategyTest { @Test - public void shouldDealWithModesNotFound() { - final List> modeIdSets = new ModeCombinationStrategy().apply( - new HashMap(), - Arrays.asList("a", "b") - ); - assertThat(modeIdSets).hasSize(3).contains( - Sets.newLinkedHashSet("a"), - Sets.newLinkedHashSet("b"), - Sets.newLinkedHashSet("a", "b") - ); + fun `should deal with modes not found`() { + val modeIdSets = ModeCombinationStrategy().apply( + emptyMap(), + listOf("a", "b") + ) + assertThat(modeIdSets).hasSize(3).containsExactlyInAnyOrder( + mutableSetOf("a"), + mutableSetOf("b"), + mutableSetOf("a", "b") + ) } @Test - public void shouldCombineModesCorrectly() { - final List> modeIdSets = new ModeCombinationStrategy().apply( + fun `should combine modes correctly`() { + val modeIdSets = ModeCombinationStrategy().apply( createSampleModeMap(), - asList( + listOf( "pt_pub", "pt_sch", "ps_tax", @@ -52,45 +56,44 @@ public class ModeCombinationStrategyTest { "cy_bic", "wa_wal" ) - ); - /* - assertThat(modeIdSets) + ) + assertThat(modeIdSets) .describedAs("Should combine modes correctly") - .isNotNull() - .containsExactly( - Sets.newLinkedHashSet("pt_pub", "pt_sch"), - Sets.newLinkedHashSet("ps_tax", "ps_shu", "cy_bic-s_AUSTIN"), - Sets.newLinkedHashSet("me_car"), - Sets.newLinkedHashSet("me_car-s_CND"), - Sets.newLinkedHashSet("me_car-s_GOG"), - Sets.newLinkedHashSet("me_mot"), - Sets.newLinkedHashSet("cy_bic"), - Sets.newLinkedHashSet("wa_wal"), - Sets.newLinkedHashSet("pt_pub", "me_mot", "ps_tax", "cy_bic", "me_car-s_CND", "wa_wal", "me_car-s_GOG", "ps_shu", "me_car", "pt_sch") - ); - */ - assertThat(true).isEqualTo(true); + .isNotNull + .containsExactlyInAnyOrder( + mutableSetOf("pt_pub", "pt_sch"), + mutableSetOf("cy_bic-s_AUSTIN", "ps_shu", "ps_tax"), + mutableSetOf("me_car"), + mutableSetOf("me_car-s_CND"), + mutableSetOf("me_car-s_GOG"), + mutableSetOf("me_mot"), + mutableSetOf("cy_bic"), + mutableSetOf("wa_wal"), + mutableSetOf("me_car", "pt_sch", "ps_shu", "me_car-s_CND", "cy_bic", "me_mot", "me_car-s_GOG", "pt_pub", "ps_tax") + ) } - @NonNull - private Map createSampleModeMap() { - final Map modeMap = new HashMap<>(); - modeMap.put("pt_pub", new TransportMode()); - modeMap.put("ps_tax", new TransportMode()); - modeMap.put("me_car", new TransportMode()); - modeMap.put("me_car-s_CND", new TransportMode()); - modeMap.put("me_car-s_GOG", new TransportMode()); - modeMap.put("me_mot", new TransportMode()); - modeMap.put("cy_bic", new TransportMode()); - modeMap.put("wa_wal", new TransportMode()); + private fun createSampleModeMap(): Map { + val modeMap = mutableMapOf() + modeMap["pt_pub"] = TransportMode() + modeMap["ps_tax"] = TransportMode() + modeMap["me_car"] = TransportMode() + modeMap["me_car-s_CND"] = TransportMode() + modeMap["me_car-s_GOG"] = TransportMode() + modeMap["me_mot"] = TransportMode() + modeMap["cy_bic"] = TransportMode() + modeMap["wa_wal"] = TransportMode() + + val schoolBusMode = TransportMode().apply { + implies = ArrayList(listOf("pt_pub")) + } + modeMap["pt_sch"] = schoolBusMode - final TransportMode schoolBusMode = new TransportMode(); - schoolBusMode.setImplies(new ArrayList<>(singletonList("pt_pub"))); - modeMap.put("pt_sch", schoolBusMode); + val shuttleMode = TransportMode().apply { + implies = ArrayList(listOf("ps_tax", "cy_bic-s_AUSTIN")) + } + modeMap["ps_shu"] = shuttleMode - final TransportMode shuttleMode = new TransportMode(); - shuttleMode.setImplies(new ArrayList<>(asList("ps_tax", "cy_bic-s_AUSTIN"))); - modeMap.put("ps_shu", shuttleMode); - return modeMap; + return modeMap } } \ No newline at end of file From f8fb7e8d44f5bdfb09239e4944e5a503916b6f21 Mon Sep 17 00:00:00 2001 From: Michael Angelo Reyes Date: Thu, 14 Nov 2024 00:56:13 +0800 Subject: [PATCH 22/25] Rename .java to .kt --- .../tripkit/{RoutingResponseTest.java => RoutingResponseTest.kt} | 0 .../tripkit/{TemporaryUrlApiTest.java => TemporaryUrlApiTest.kt} | 0 .../skedgo/tripkit/{UuidProviderTest.java => UuidProviderTest.kt} | 0 3 files changed, 0 insertions(+), 0 deletions(-) rename TripKitAndroid/src/test/java/com/skedgo/tripkit/{RoutingResponseTest.java => RoutingResponseTest.kt} (100%) rename TripKitAndroid/src/test/java/com/skedgo/tripkit/{TemporaryUrlApiTest.java => TemporaryUrlApiTest.kt} (100%) rename TripKitAndroid/src/test/java/com/skedgo/tripkit/{UuidProviderTest.java => UuidProviderTest.kt} (100%) diff --git a/TripKitAndroid/src/test/java/com/skedgo/tripkit/RoutingResponseTest.java b/TripKitAndroid/src/test/java/com/skedgo/tripkit/RoutingResponseTest.kt similarity index 100% rename from TripKitAndroid/src/test/java/com/skedgo/tripkit/RoutingResponseTest.java rename to TripKitAndroid/src/test/java/com/skedgo/tripkit/RoutingResponseTest.kt diff --git a/TripKitAndroid/src/test/java/com/skedgo/tripkit/TemporaryUrlApiTest.java b/TripKitAndroid/src/test/java/com/skedgo/tripkit/TemporaryUrlApiTest.kt similarity index 100% rename from TripKitAndroid/src/test/java/com/skedgo/tripkit/TemporaryUrlApiTest.java rename to TripKitAndroid/src/test/java/com/skedgo/tripkit/TemporaryUrlApiTest.kt diff --git a/TripKitAndroid/src/test/java/com/skedgo/tripkit/UuidProviderTest.java b/TripKitAndroid/src/test/java/com/skedgo/tripkit/UuidProviderTest.kt similarity index 100% rename from TripKitAndroid/src/test/java/com/skedgo/tripkit/UuidProviderTest.java rename to TripKitAndroid/src/test/java/com/skedgo/tripkit/UuidProviderTest.kt From 09b4d9b433fc88be429298ba30ce87a4951f0fd9 Mon Sep 17 00:00:00 2001 From: Michael Angelo Reyes Date: Thu, 14 Nov 2024 00:56:13 +0800 Subject: [PATCH 23/25] [22682] - [TripKit] fix failing tests on RegionServiceImplTest.kt and update to use MockK - [TripKit] convert RoutingResponseTest.java to kotlin and re-enable commented out test - [TripKit] convert TemporaryUrlApiTest.java to kotlin and use MockK - [TripKit] convert UuidProviderTest.java to kotlin and use MockK --- .../skedgo/tripkit/RegionServiceImplTest.kt | 244 +++++++----------- .../com/skedgo/tripkit/RoutingResponseTest.kt | 202 ++++++++------- .../com/skedgo/tripkit/TemporaryUrlApiTest.kt | 104 ++++---- .../com/skedgo/tripkit/UuidProviderTest.kt | 77 +++--- 4 files changed, 303 insertions(+), 324 deletions(-) diff --git a/TripKitAndroid/src/test/java/com/skedgo/tripkit/RegionServiceImplTest.kt b/TripKitAndroid/src/test/java/com/skedgo/tripkit/RegionServiceImplTest.kt index e3455c76..7c98309d 100644 --- a/TripKitAndroid/src/test/java/com/skedgo/tripkit/RegionServiceImplTest.kt +++ b/TripKitAndroid/src/test/java/com/skedgo/tripkit/RegionServiceImplTest.kt @@ -1,8 +1,8 @@ package com.skedgo.tripkit +import androidx.arch.core.executor.testing.InstantTaskExecutorRule import androidx.test.ext.junit.runners.AndroidJUnit4 -import com.nhaarman.mockitokotlin2.mock -import com.nhaarman.mockitokotlin2.whenever +import com.skedgo.tripkit.booking.ui.base.MockKTest import com.skedgo.tripkit.common.model.location.Location import com.skedgo.tripkit.common.model.region.Region import com.skedgo.tripkit.common.model.TransportMode @@ -11,26 +11,33 @@ import com.skedgo.tripkit.data.tsp.ImmutableRegionInfo import com.skedgo.tripkit.data.tsp.Paratransit import com.skedgo.tripkit.data.tsp.RegionInfo import com.skedgo.tripkit.tsp.RegionInfoRepository +import io.mockk.MockKAnnotations +import io.mockk.clearAllMocks +import io.mockk.every +import io.mockk.mockk +import io.mockk.verify import io.reactivex.Completable import io.reactivex.Observable import io.reactivex.Single import io.reactivex.observers.TestObserver -import org.assertj.core.api.Java6Assertions.assertThat +import org.amshove.kluent.internal.assertEquals +import org.junit.After +import org.junit.Before +import org.junit.Rule import org.junit.Test import org.junit.runner.RunWith -import org.mockito.Mockito.eq -import org.mockito.Mockito.same -import org.mockito.Mockito.times -import org.mockito.Mockito.verify -import java.util.Arrays @RunWith(AndroidJUnit4::class) -class RegionServiceImplTest : TripKitAndroidRobolectricTest() { - internal val regionCache: com.skedgo.tripkit.Cache> = mock() - internal val modeCache: com.skedgo.tripkit.Cache> = mock() - internal val regionsFetcher: RegionsFetcher = mock() - internal val regionInfoRepository: RegionInfoRepository = mock() - internal val regionFinder: com.skedgo.tripkit.RegionFinder = mock() +class RegionServiceImplTest: MockKTest() { + + @get:Rule + val rule = InstantTaskExecutorRule() + + private val regionCache: com.skedgo.tripkit.Cache> = mockk(relaxed = true) + private val modeCache: com.skedgo.tripkit.Cache> = mockk(relaxed = true) + private val regionsFetcher: RegionsFetcher = mockk(relaxed = true) + private val regionInfoRepository: RegionInfoRepository = mockk(relaxed = true) + private val regionFinder: com.skedgo.tripkit.RegionFinder = mockk(relaxed = true) private val regionService: RegionService by lazy { RegionServiceImpl( regionCache, @@ -41,184 +48,133 @@ class RegionServiceImplTest : TripKitAndroidRobolectricTest() { ) } + @Before + fun setUp() { + initRx() + MockKAnnotations.init(this) + } + + @After + fun tearDown() { + tearDownRx() + clearAllMocks() + } + @Test - fun shouldPropagateNullPointerExceptionIfLocationIsNull() { + fun `should propagate NullPointerException if location is null`() { val subscriber = regionService.getRegionByLocationAsync(null).test() subscriber.awaitTerminalEvent() - assertThat(subscriber.events[1]) - .hasSize(1) - .hasOnlyElementsOfType(NullPointerException::class.java) - .extractingResultOf("getMessage") - .containsExactly("Location is null") + subscriber.assertError(NullPointerException::class.java) + assertEquals("Location is null", subscriber.errors()[0].message) } @Test - fun shouldTakeFirstFoundRegion() { - val Sydney = Region() - Sydney.name = "AU_NSW_Sydney" - Sydney.encodedPolyline = "nwcvE_fno[owyR??mcjRnwyR?" - - val NewYork = Region() - NewYork.name = "US_NY_NewYorkCity" - NewYork.encodedPolyline = "oecvFnzhdM_}tA??o~oE~|tA?" - - whenever(regionCache.getAsync()) - .thenReturn(Single.just(Arrays.asList(Sydney, NewYork))) - whenever( - regionFinder.contains( - same(Sydney), - eq(-33.86749), - eq(151.20699) - ) - ).thenReturn(true) + fun `should take first found region`() { + val sydney = Region().apply { + name = "AU_NSW_Sydney" + encodedPolyline = "nwcvE_fno[owyR??mcjRnwyR?" + } + val newYork = Region().apply { + name = "US_NY_NewYorkCity" + encodedPolyline = "oecvFnzhdM_}tA??o~oE~|tA?" + } + + every { regionCache.getAsync() } returns Single.just(listOf(sydney, newYork)) + every { regionFinder.contains(sydney, -33.86749, 151.20699) } returns true val subscriber = TestObserver() - regionService.getRegionByLocationAsync( - Location( - -33.86749, - 151.20699 - ) - ).subscribe(subscriber) + regionService.getRegionByLocationAsync(Location(-33.86749, 151.20699)).subscribe(subscriber) subscriber.awaitTerminalEvent() subscriber.assertNoErrors() - - subscriber.assertValueCount(1) - subscriber.assertValueAt(0) { region -> region == Sydney } + subscriber.assertValue(sydney) } @Test - fun shouldPropagateOutOfRegionsExceptionIfNoRegionIsFound() { - val Sydney = Region() - Sydney.name = "AU_NSW_Sydney" - Sydney.encodedPolyline = "nwcvE_fno[owyR??mcjRnwyR?" + fun `should propagate OutOfRegionsException if no region is found`() { + val sydney = Region().apply { name = "AU_NSW_Sydney" } + val newYork = Region().apply { name = "US_NY_NewYorkCity" } - val NewYork = Region() - NewYork.name = "US_NY_NewYorkCity" - NewYork.encodedPolyline = "oecvFnzhdM_}tA??o~oE~|tA?" + every { regionCache.getAsync() } returns Single.just(listOf(sydney, newYork)) - whenever(regionCache.getAsync()) - .thenReturn(Single.just(Arrays.asList(Sydney, NewYork))) - - val subscriber = TestObserver() - val location = - Location(1.0, 2.0) - regionService.getRegionByLocationAsync(location).subscribe(subscriber) + val location = Location(1.0, 2.0) + val subscriber = regionService.getRegionByLocationAsync(location).test() subscriber.awaitTerminalEvent() - val errors = subscriber.events[1] - assertThat(errors) - .hasSize(1) - .hasOnlyElementsOfType(com.skedgo.tripkit.OutOfRegionsException::class.java) - .extractingResultOf("getMessage") - .containsExactly("Location lies outside covered area") - - val error = errors[0] as com.skedgo.tripkit.OutOfRegionsException - assertThat(error.latitude()).isEqualTo(location.lat) - assertThat(error.longitude()).isEqualTo(location.lon) + subscriber.assertError(com.skedgo.tripkit.OutOfRegionsException::class.java) + val error = subscriber.errors()[0] as com.skedgo.tripkit.OutOfRegionsException + assertEquals(location.lat, error.latitude()) + assertEquals(location.lon, error.longitude()) } @Test - fun shouldTakeAllCitiesInRegions() { - val AU = Region() - val Sydney = Region.City() - Sydney.name = "Sydney" - val Newcastle = Region.City() - Newcastle.name = "Newcastle" - AU.cities = ArrayList(Arrays.asList(Sydney, Newcastle)) - - val US = Region() - val NewYork = Region.City() - NewYork.name = "New York" - val SanJose = Region.City() - SanJose.name = "San Jose" - US.cities = ArrayList(Arrays.asList(NewYork, SanJose)) - - whenever(regionCache.getAsync()) - .thenReturn(Single.just(Arrays.asList(AU, US))) - - val subscriber = TestObserver() - regionService.getCitiesAsync().subscribe(subscriber) + fun `should take all cities in regions`() { + val sydney = Region.City().apply { name = "Sydney" } + val newcastle = Region.City().apply { name = "Newcastle" } + val au = Region().apply { cities = ArrayList(listOf(sydney, newcastle)) } + + val newYork = Region.City().apply { name = "New York" } + val sanJose = Region.City().apply { name = "San Jose" } + val us = Region().apply { cities = ArrayList(listOf(newYork, sanJose)) } + + every { regionCache.getAsync() } returns Single.just(listOf(au, us)) + + val subscriber = regionService.getCitiesAsync().test() subscriber.awaitTerminalEvent() subscriber.assertNoErrors() - val cities = subscriber.events[0] - assertThat(cities).containsExactly(Sydney, Newcastle, NewYork, SanJose) + subscriber.assertValues(sydney, newcastle, newYork, sanJose) } @Test - fun shouldTakeTransportModesFromModesLoader() { - val modeMap = HashMap() - modeMap.put("car", TransportMode()) - modeMap.put("walk", TransportMode()) - whenever(modeCache.getAsync()).thenReturn(Single.just>(modeMap)) - - val subscriber = TestObserver>() - regionService.getTransportModesAsync().subscribe(subscriber) + fun `should take transport modes from modes loader`() { + val modeMap = mapOf("car" to TransportMode(), "walk" to TransportMode()) + every { modeCache.getAsync() } returns Single.just(modeMap) + + val subscriber = regionService.getTransportModesAsync().test() subscriber.awaitTerminalEvent() subscriber.assertNoErrors() - val actualModeMap = subscriber.events[0] - assertThat(actualModeMap.first()).isEqualTo(modeMap) + subscriber.assertValue(modeMap) } @Test - fun shouldTakeRegionsFromRegionsLoader() { - val regions = Arrays.asList( - Region(), - Region() - ) - whenever(regionCache.getAsync()).thenReturn(Single.just(regions)) + fun `should take regions from regions loader`() { + val regions = listOf(Region(), Region()) + every { regionCache.getAsync() } returns Single.just(regions) val subscriber = regionService.getRegionsAsync().test() subscriber.awaitTerminalEvent() subscriber.assertNoErrors() - val list = subscriber.events[0] as List - assertThat(list.first()).isEqualTo(regions) + subscriber.assertValue(regions) } @Test - fun shouldFetchParatransit() { - val paratransit = Paratransit( - "http://accessla.org/", - "Access", - "1.800.883.1295" - ) - val regionInfo = ImmutableRegionInfo.builder() - .paratransit(paratransit) - .build() - - val region = Region() - region.setURLs(ArrayList(listOf("https://lepton-us-ca-losangeles.tripgo.skedgo.com/satapp"))) - region.name = "US_CA_LosAngeles" + fun `should fetch paratransit`() { + val paratransit = Paratransit("http://accessla.org/", "Access", "1.800.883.1295") + val regionInfo = ImmutableRegionInfo.builder().paratransit(paratransit).build() - whenever(regionInfoRepository.getRegionInfoByRegion(region)).thenReturn( - Observable.just( - regionInfo + val region = Region().apply { + setURLs( + ArrayList(listOf("https://lepton-us-ca-losangeles.tripgo.skedgo.com/satapp")) ) - ) + name = "US_CA_LosAngeles" + } - val subscriber = TestObserver() - regionService.fetchParatransitByRegionAsync(region) - .subscribe(subscriber) + every { regionInfoRepository.getRegionInfoByRegion(region) } returns Observable.just(regionInfo) + val subscriber = regionService.fetchParatransitByRegionAsync(region).test() subscriber.awaitTerminalEvent() subscriber.assertNoErrors() - - assertThat(subscriber.events[0]) - .containsExactly(paratransit) + subscriber.assertValue(paratransit) } @Test - fun shouldInvalidateCachesAfterRefreshing() { - whenever(regionsFetcher.fetchAsync()).thenReturn(Completable.complete()) - val subscriber = TestObserver() - regionService.refreshAsync().subscribe(subscriber) + fun `should invalidate caches after refreshing`() { + every { regionsFetcher.fetchAsync() } returns Completable.complete() + val subscriber = regionService.refreshAsync().test() subscriber.awaitTerminalEvent() subscriber.assertNoErrors() - verify>>( - modeCache, - times(1) - ).invalidate() - verify>>(regionCache, times(1)).invalidate() - verify(regionFinder, times(1)).invalidate() + verify(exactly = 1) { modeCache.invalidate() } + verify(exactly = 1) { regionCache.invalidate() } + verify(exactly = 1) { regionFinder.invalidate() } } } \ No newline at end of file diff --git a/TripKitAndroid/src/test/java/com/skedgo/tripkit/RoutingResponseTest.kt b/TripKitAndroid/src/test/java/com/skedgo/tripkit/RoutingResponseTest.kt index 3ea264c6..4ef49932 100644 --- a/TripKitAndroid/src/test/java/com/skedgo/tripkit/RoutingResponseTest.kt +++ b/TripKitAndroid/src/test/java/com/skedgo/tripkit/RoutingResponseTest.kt @@ -1,127 +1,131 @@ -package com.skedgo.tripkit; - -import com.google.gson.Gson; -import com.google.gson.JsonPrimitive; -import com.skedgo.tripkit.common.model.realtimealert.RealtimeAlert; -import com.skedgo.tripkit.common.model.realtimealert.RealtimeAlerts; -import com.skedgo.tripkit.common.util.Gsons; -import com.skedgo.tripkit.routing.RoutingResponse; -import com.skedgo.tripkit.routing.Trip; -import com.skedgo.tripkit.routing.TripGroup; -import com.skedgo.tripkit.routing.TripSegment; - -import org.assertj.core.api.Condition; -import org.junit.Test; -import org.junit.runner.RunWith; - -import java.io.IOException; - -import androidx.test.core.app.ApplicationProvider; -import androidx.test.ext.junit.runners.AndroidJUnit4; -import okhttp3.mockwebserver.MockResponse; - -import static org.assertj.core.api.Java6Assertions.assertThat; -import static thuytrinh.mockwebserverrule.MockWebServerRule.createMockResponse; - -@RunWith(AndroidJUnit4.class) -public class RoutingResponseTest { +package com.skedgo.tripkit + +import android.content.Context +import androidx.test.core.app.ApplicationProvider +import androidx.test.ext.junit.runners.AndroidJUnit4 +import com.google.gson.JsonPrimitive +import com.skedgo.tripkit.common.model.realtimealert.RealtimeAlert +import com.skedgo.tripkit.common.model.realtimealert.RealtimeAlerts.getDisplayText +import com.skedgo.tripkit.common.util.Gsons.createForLowercaseEnum +import com.skedgo.tripkit.routing.RoutingResponse +import com.skedgo.tripkit.routing.Trip +import org.assertj.core.api.Assertions.assertThat +import org.assertj.core.api.Condition +import org.assertj.core.api.Java6Assertions +import org.junit.Assert.assertEquals +import org.junit.Assert.assertNull +import org.junit.Test +import org.junit.runner.RunWith +import thuytrinh.mockwebserverrule.MockWebServerRule +import java.io.IOException + +@RunWith(AndroidJUnit4::class) +class RoutingResponseTest { // TODO: Unit test - refactor - /* Disabled function due to null pointer exception @Test - public void processDirectionTemplate() { + fun processDirectionTemplate() { // Case 1 - JsonPrimitive serviceDirectionNode = new JsonPrimitive("Service direction"); - String notes = "This is a "; - String result = RoutingResponse.processDirectionTemplate(serviceDirectionNode, notes, null); - assertThat("This is a Direction: Service direction").isEqualTo(result); + var serviceDirectionNode = JsonPrimitive("Service direction") + var notes = "This is a " + var result = RoutingResponse.processDirectionTemplate(serviceDirectionNode, notes, null) + assertEquals("This is a Direction: Service direction", result) // Case 2 - serviceDirectionNode = new JsonPrimitive(""); - notes = "This is a "; - result = RoutingResponse.processDirectionTemplate(serviceDirectionNode, notes, null); - assertThat("This is a ").isEqualTo(result); + serviceDirectionNode = JsonPrimitive("") + notes = "This is a " + result = RoutingResponse.processDirectionTemplate(serviceDirectionNode, notes, null) + assertEquals("This is a ", result) // Case 3 - notes = "This is a "; - result = RoutingResponse.processDirectionTemplate(null, notes, null); - assertThat("This is a ").isEqualTo(result); + notes = "This is a " + result = RoutingResponse.processDirectionTemplate(null, notes, null) + assertEquals("This is a ", result) // Case 4 - result = RoutingResponse.processDirectionTemplate(null, null, null); - assertThat(result).isNull(); - result = RoutingResponse.processDirectionTemplate(null, "", null); - assertThat("").isEqualTo(result); + result = RoutingResponse.processDirectionTemplate(null, "", null) + assertEquals("", result) } - */ @Test - public void tripHasReferenceToGroup() throws IOException { - MockResponse mockResponse = createMockResponse("/routing0.json"); - String routingJson = mockResponse.getBody().readUtf8(); - - Gson gson = Gsons.createForLowercaseEnum(); - RoutingResponse response = gson.fromJson(routingJson, RoutingResponse.class); - response.processRawData(ApplicationProvider.getApplicationContext().getResources(), gson); - - for (final TripGroup group : response.getTripGroupList()) { - assertThat(group.getTrips()) + @Throws(IOException::class) + fun tripHasReferenceToGroup() { + val mockResponse = MockWebServerRule.createMockResponse("/routing0.json") + val routingJson = mockResponse.getBody()?.readUtf8() + + val gson = createForLowercaseEnum() + val response = gson.fromJson(routingJson, RoutingResponse::class.java) + response.processRawData( + ApplicationProvider.getApplicationContext().resources, + gson + ) + + for (group in response.tripGroupList!!) { + assertThat(group.trips) .describedAs("Trip must have reference to its group") - .are(new Condition() { - @Override - public boolean matches(Trip value) { - return value.getGroup() == group; + .are(object : Condition() { + override fun matches(value: Trip): Boolean { + return value.group == group } - }); + }) } } @Test - public void shouldParseProperly() throws IOException { - MockResponse mockResponse = createMockResponse("/routing0.json"); - String routingJson = mockResponse.getBody().readUtf8(); - - Gson gson = Gsons.createForLowercaseEnum(); - RoutingResponse response = gson.fromJson(routingJson, RoutingResponse.class); - response.processRawData(ApplicationProvider.getApplicationContext().getResources(), gson); - - assertThat(response).isNotNull(); - assertThat(response.alerts).hasSize(1); - assertThat(response.getTripGroupList()).hasSize(1).doesNotContainNull(); - - TripGroup group = response.getTripGroupList().get(0); - assertThat(group.getTrips()).hasSize(1).doesNotContainNull(); - - Trip trip = group.getTrips().get(0); - assertThat(trip.getSegmentList()).hasSize(3).doesNotContainNull(); - - TripSegment motorbikeSegment = trip.getSegmentList().get(1); - assertThat(motorbikeSegment.getAlerts()).hasSize(1).doesNotContainNull(); - - RealtimeAlert alert = motorbikeSegment.getAlerts().get(0); - assertThat(alert.severity()).isEqualTo(RealtimeAlert.SEVERITY_WARNING); - assertThat(alert.title()).isEqualTo("Traffic delay"); - assertThat(RealtimeAlerts.getDisplayText(alert)).isEqualTo("Unusually high traffic on the route."); + @Throws(IOException::class) + fun shouldParseProperly() { + val mockResponse = MockWebServerRule.createMockResponse("/routing0.json") + val routingJson = mockResponse.getBody()?.readUtf8() + + val gson = createForLowercaseEnum() + val response = gson.fromJson(routingJson, RoutingResponse::class.java) + response.processRawData( + ApplicationProvider.getApplicationContext().resources, + gson + ) + + assertThat(response).isNotNull() + assertThat(response.alerts).hasSize(1) + assertThat(response.tripGroupList).hasSize(1).doesNotContainNull() + + val group = response.tripGroupList!![0] + assertThat(group.trips).hasSize(1).doesNotContainNull() + + val trip = group.trips!![0] + assertThat(trip.segmentList).hasSize(3).doesNotContainNull() + + val motorbikeSegment = trip.segmentList[1] + assertThat(motorbikeSegment.alerts).hasSize(1).doesNotContainNull() + + val alert = motorbikeSegment.alerts!![0] + assertThat(alert.severity()).isEqualTo(RealtimeAlert.SEVERITY_WARNING) + assertThat(alert.title()).isEqualTo("Traffic delay") + assertThat(getDisplayText(alert)) + .isEqualTo("Unusually high traffic on the route.") } @Test - public void parseMultipleStreets() throws IOException { - MockResponse mockResponse = createMockResponse("/routingStreets.json"); - String routingJson = mockResponse.getBody().readUtf8(); + @Throws(IOException::class) + fun parseMultipleStreets() { + val mockResponse = MockWebServerRule.createMockResponse("/routingStreets.json") + val routingJson = mockResponse.getBody()?.readUtf8() - Gson gson = Gsons.createForLowercaseEnum(); - RoutingResponse response = gson.fromJson(routingJson, RoutingResponse.class); - response.processRawData(ApplicationProvider.getApplicationContext().getResources(), gson); + val gson = createForLowercaseEnum() + val response = gson.fromJson(routingJson, RoutingResponse::class.java) + response.processRawData( + ApplicationProvider.getApplicationContext().resources, + gson + ) - assertThat(response).isNotNull(); - assertThat(response.getTripGroupList()).hasSize(1).doesNotContainNull(); + assertThat(response).isNotNull() + assertThat(response.tripGroupList).hasSize(1).doesNotContainNull() - TripGroup group = response.getTripGroupList().get(0); - assertThat(group.getTrips()).hasSize(1).doesNotContainNull(); + val group = response.tripGroupList!![0] + assertThat(group.trips).hasSize(1).doesNotContainNull() - Trip trip = group.getTrips().get(0); - assertThat(trip.getSegmentList()).hasSize(3).doesNotContainNull(); + val trip = group.trips!![0] + assertThat(trip.segmentList).hasSize(3).doesNotContainNull() - TripSegment motorbikeSegment = trip.getSegmentList().get(1); - assertThat(motorbikeSegment.getStreets()).hasSize(4).doesNotContainNull(); + val motorbikeSegment = trip.segmentList[1] + assertThat(motorbikeSegment.streets).hasSize(4).doesNotContainNull() } } \ No newline at end of file diff --git a/TripKitAndroid/src/test/java/com/skedgo/tripkit/TemporaryUrlApiTest.kt b/TripKitAndroid/src/test/java/com/skedgo/tripkit/TemporaryUrlApiTest.kt index 9ce3a5c8..f7fce289 100644 --- a/TripKitAndroid/src/test/java/com/skedgo/tripkit/TemporaryUrlApiTest.kt +++ b/TripKitAndroid/src/test/java/com/skedgo/tripkit/TemporaryUrlApiTest.kt @@ -1,71 +1,75 @@ -package com.skedgo.tripkit; +package com.skedgo.tripkit -import com.skedgo.tripkit.common.util.Gsons; -import com.skedgo.tripkit.routing.RoutingResponse; +import androidx.test.ext.junit.runners.AndroidJUnit4 +import com.skedgo.tripkit.common.util.Gsons +import com.skedgo.tripkit.common.util.Gsons.createForLowercaseEnum +import com.skedgo.tripkit.routing.RoutingResponse +import io.mockk.MockKAnnotations +import io.mockk.clearMocks +import io.reactivex.observers.TestObserver +import okhttp3.HttpUrl +import okhttp3.mockwebserver.MockResponse +import okhttp3.mockwebserver.MockWebServer +import org.apache.commons.io.IOUtils +import org.assertj.core.api.Java6Assertions +import org.junit.After +import org.junit.Assert.assertTrue +import org.junit.Before +import org.junit.Test +import org.junit.runner.RunWith +import retrofit2.Retrofit +import retrofit2.Retrofit.Builder +import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory +import retrofit2.converter.gson.GsonConverterFactory +import java.io.IOException +import java.nio.charset.Charset -import org.apache.commons.io.IOUtils; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; +@RunWith(AndroidJUnit4::class) +class TemporaryUrlApiTest { -import java.io.IOException; -import java.nio.charset.Charset; -import java.util.Collections; - -import androidx.test.ext.junit.runners.AndroidJUnit4; -import io.reactivex.observers.TestObserver; -import okhttp3.HttpUrl; -import okhttp3.mockwebserver.MockResponse; -import okhttp3.mockwebserver.MockWebServer; -import retrofit2.Retrofit; -import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory; -import retrofit2.converter.gson.GsonConverterFactory; - -import static org.assertj.core.api.Java6Assertions.assertThat; - -@RunWith(AndroidJUnit4.class) -public class TemporaryUrlApiTest extends TripKitAndroidRobolectricTest { - private MockWebServer server; - private TemporaryUrlApi api; - private HttpUrl baseUrl; + private lateinit var server: MockWebServer + private lateinit var api: TemporaryUrlApi + private lateinit var baseUrl: HttpUrl @Before - public void before() { - server = new MockWebServer(); - baseUrl = server.url("/"); - api = new Retrofit.Builder() + fun setUp() { + MockKAnnotations.init(this) + server = MockWebServer() + baseUrl = server.url("/") + api = Retrofit.Builder() .baseUrl(baseUrl) .addCallAdapterFactory(RxJava2CallAdapterFactory.create()) .addConverterFactory(GsonConverterFactory.create(Gsons.createForLowercaseEnum())) .build() - .create(TemporaryUrlApi.class); + .create(TemporaryUrlApi::class.java) } @After - public void after() throws IOException { - server.shutdown(); + fun tearDown() { + server.shutdown() } @Test - public void fetchTripSuccessfully() throws IOException { - final MockResponse mockResponse = new MockResponse(); - mockResponse.setResponseCode(200); - mockResponse.setBody(IOUtils.toString( - getClass().getResourceAsStream("/temporaryURL.json"), - Charset.defaultCharset() - )); - server.enqueue(mockResponse); + fun `fetch trip successfully`() { + val mockResponse = MockResponse() + .setResponseCode(200) + .setBody( + IOUtils.toString( + this::class.java.getResourceAsStream("/temporaryURL.json"), + Charset.defaultCharset() + ) + ) + server.enqueue(mockResponse) - final HttpUrl url = baseUrl.newBuilder() + val url = baseUrl.newBuilder() .addPathSegments("trip/0a1cba21-f177-4706-bbb8-ebd8057e5f4f") - .build(); - final TestObserver subscriber = api.requestTemporaryUrlAsync( + .build() + val testObserver: TestObserver = api.requestTemporaryUrlAsync( url.toString(), - Collections.emptyMap() - ).test(); + emptyMap() + ).test() - final RoutingResponse response = subscriber.values().get(0); - assertThat(response.getTripGroupList()).isNotEmpty(); + val response = testObserver.values()[0] + assertTrue(response.tripGroupList?.isNotEmpty() == true) } } \ No newline at end of file diff --git a/TripKitAndroid/src/test/java/com/skedgo/tripkit/UuidProviderTest.kt b/TripKitAndroid/src/test/java/com/skedgo/tripkit/UuidProviderTest.kt index f9710b65..216ef59b 100644 --- a/TripKitAndroid/src/test/java/com/skedgo/tripkit/UuidProviderTest.kt +++ b/TripKitAndroid/src/test/java/com/skedgo/tripkit/UuidProviderTest.kt @@ -1,46 +1,61 @@ -package com.skedgo.tripkit; - -import android.content.Context; -import android.content.SharedPreferences; - -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.robolectric.RobolectricTestRunner; - -import androidx.test.core.app.ApplicationProvider; -import androidx.test.ext.junit.runners.AndroidJUnit4; - -import static org.assertj.core.api.Java6Assertions.assertThat; - -@RunWith(AndroidJUnit4.class) -public class UuidProviderTest { - private UuidProvider provider; - private SharedPreferences preferences; +package com.skedgo.tripkit + +import android.content.Context +import android.content.SharedPreferences +import androidx.arch.core.executor.testing.InstantTaskExecutorRule +import androidx.test.core.app.ApplicationProvider +import androidx.test.ext.junit.runners.AndroidJUnit4 +import com.skedgo.tripkit.booking.ui.base.MockKTest +import io.mockk.MockKAnnotations +import org.junit.After +import org.junit.Assert.assertEquals +import org.junit.Assert.assertNotNull +import org.junit.Assert.assertTrue +import org.junit.Before +import org.junit.Rule +import org.junit.Test +import org.junit.runner.RunWith + +@RunWith(AndroidJUnit4::class) +class UuidProviderTest: MockKTest() { + + @get:Rule + val rule = InstantTaskExecutorRule() + + private lateinit var provider: UuidProvider + private lateinit var preferences: SharedPreferences @Before - public void before() { - preferences = ApplicationProvider.getApplicationContext().getSharedPreferences( + fun setUp() { + MockKAnnotations.init(this) + initRx() + preferences = ApplicationProvider.getApplicationContext().getSharedPreferences( "TripKit", Context.MODE_PRIVATE - ); - provider = new UuidProvider(preferences); + ) + provider = UuidProvider(preferences) + } + + @After + fun tearDown() { + tearDownRx() } @Test - public void generateUuid() { - final String uuid = provider.call(); - assertThat(uuid).isNotNull().isNotEmpty(); + fun `generate uuid`() { + val uuid = provider.call() + assertNotNull(uuid) + assertTrue(uuid.isNotEmpty()) - provider = new UuidProvider(preferences); - assertThat(provider.call()).isEqualTo(uuid); + provider = UuidProvider(preferences) + assertEquals(uuid, provider.call()) } @Test - public void usePersistentUuid() { + fun `use persistent uuid`() { preferences.edit() .putString("UUID", "Some UUID") - .apply(); - assertThat(provider.call()).isEqualTo("Some UUID"); + .apply() + assertEquals("Some UUID", provider.call()) } } \ No newline at end of file From 1ff8b5f4f54f7e808195c08b71e003e868fb7cd5 Mon Sep 17 00:00:00 2001 From: Michael Angelo Reyes Date: Thu, 14 Nov 2024 00:56:38 +0800 Subject: [PATCH 24/25] [22682] - [TripKitUI] variable adjustment --- .../main/java/com/skedgo/tripkit/routing/RoutingResponse.kt | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/CommonCoreLegacy/src/main/java/com/skedgo/tripkit/routing/RoutingResponse.kt b/CommonCoreLegacy/src/main/java/com/skedgo/tripkit/routing/RoutingResponse.kt index fb49c46a..bc9d5342 100644 --- a/CommonCoreLegacy/src/main/java/com/skedgo/tripkit/routing/RoutingResponse.kt +++ b/CommonCoreLegacy/src/main/java/com/skedgo/tripkit/routing/RoutingResponse.kt @@ -312,7 +312,7 @@ class RoutingResponse { */ @JvmStatic fun processDirectionTemplate( - serviceDirectionNode: JsonPrimitive, + serviceDirectionNode: JsonPrimitive?, notes: String, resources: Resources? ): String { @@ -323,7 +323,7 @@ class RoutingResponse { } if (!isElementMissing(serviceDirectionNode)) { - val serviceDirection = serviceDirectionNode.asString + val serviceDirection = serviceDirectionNode?.asString notes = if (!TextUtils.isEmpty(serviceDirection)) { notes.replace( SegmentNotesTemplates.TEMPLATE_DIRECTION, From afb2d798661788de98ef6dd50dfebf4ce28016de Mon Sep 17 00:00:00 2001 From: Michael Angelo Reyes Date: Thu, 14 Nov 2024 00:57:11 +0800 Subject: [PATCH 25/25] [22682] - [TripKit] add @JvmSuppressWildcards to accept Any as a type on Map --- .../src/main/java/com/skedgo/tripkit/TemporaryUrlApi.kt | 1 + 1 file changed, 1 insertion(+) diff --git a/TripKitAndroid/src/main/java/com/skedgo/tripkit/TemporaryUrlApi.kt b/TripKitAndroid/src/main/java/com/skedgo/tripkit/TemporaryUrlApi.kt index 494eb4eb..ba47aef4 100644 --- a/TripKitAndroid/src/main/java/com/skedgo/tripkit/TemporaryUrlApi.kt +++ b/TripKitAndroid/src/main/java/com/skedgo/tripkit/TemporaryUrlApi.kt @@ -9,6 +9,7 @@ import retrofit2.http.Url /** * Handles downloading trip via [Trip.getTemporaryURL]. */ +@JvmSuppressWildcards interface TemporaryUrlApi { /** * @param url Should be [Trip.getTemporaryURL].