Skip to content

Commit

Permalink
Merge pull request #369 from skedgo/feature/17415
Browse files Browse the repository at this point in the history
  • Loading branch information
MichaelReyes authored Oct 24, 2022
2 parents 504c1a9 + b4f476d commit d6870ff
Show file tree
Hide file tree
Showing 24 changed files with 417 additions and 236 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@
import com.google.gson.annotations.SerializedName;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;

public class Region implements Parcelable {
public static final Creator<Region> CREATOR = new Creator<Region>() {
Expand Down Expand Up @@ -51,8 +53,11 @@ public void setName(final String name) {
}

@Nullable
public ArrayList<String> getURLs() {
return urls;
public ArrayList<String> getURLs(@Nullable String customUrl) {
if(customUrl != null)
return new ArrayList<String>(Collections.singletonList(customUrl));
else
return urls;
}

public void setURLs(final ArrayList<String> urls) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,7 @@ static final class InterRegion extends Region {
setTransportModeIds(new ArrayList<>(unionModeIds));
}

final ArrayList<String> departureUrls = departureRegion.getURLs();
final ArrayList<String> departureUrls = departureRegion.getURLs(null);
if (departureUrls != null) {
setURLs(new ArrayList<>(departureUrls));
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,7 @@ public class InterRegionTest {
)));

final Regions.InterRegion interRegion = new Regions.InterRegion(departureRegion, arrivalRegion);
assertThat(interRegion.getURLs())
assertThat(interRegion.getURLs(null))
.containsExactlyElementsOf(departureServerUrls);
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ public class QueryTest {

assertThat(actual.getRegion()).isNotNull();
assertThat(actual.getRegion().getName()).isEqualTo(expectedRegionName);
assertThat(actual.getRegion().getURLs()).containsExactlyElementsOf(expectedRegion.getURLs());
assertThat(actual.getRegion().getURLs(null)).containsExactlyElementsOf(expectedRegion.getURLs(null));

assertThat(actual.getTransportModeIds())
.isNotNull()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -56,9 +56,9 @@ public class RegionTest {
assertThat(actual.getEncodedPolyline()).isEqualTo(expected.getEncodedPolyline());
assertEquals(expected.getName(), actual.getName());
assertEquals(expected.getTimezone(), actual.getTimezone());
assertThat(actual.getURLs())
assertThat(actual.getURLs(null))
.describedAs("Parcel urls properly yet?")
.containsExactlyElementsOf(expected.getURLs());
.containsExactlyElementsOf(expected.getURLs(null));
assertThat(actual.getTransportModeIds())
.describedAs("Parcel modes properly yet?")
.containsExactlyElementsOf(expected.getTransportModeIds());
Expand Down
7 changes: 6 additions & 1 deletion TripKitAndroid/src/main/java/com/skedgo/TripKit.java
Original file line number Diff line number Diff line change
Expand Up @@ -79,7 +79,12 @@ public static void initialize(Configs configs) {
if (instance == null) {
instance = DaggerTripKit.builder()
.mainModule(new MainModule(configs))
.httpClientModule(new HttpClientModule(null, null, configs, null))
.httpClientModule(new HttpClientModule(
null,
null,
configs,
null
))
.build();
JodaTimeAndroid.init(configs.context());
}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,21 +1,24 @@
package com.skedgo.tripkit

import android.content.SharedPreferences
import com.google.gson.Gson
import okhttp3.Interceptor
import okhttp3.Response
import com.skedgo.tripkit.configuration.GetAppVersion
import com.skedgo.tripkit.configuration.Key
import com.skedgo.tripkit.data.HttpClientCustomDataStore
import com.skedgo.tripkit.extensions.fromJson
import java.io.IOException
import java.util.*
import java.util.concurrent.Callable

class AddCustomHeaders constructor(
private val getAppVersion: GetAppVersion,
private val getLocale: () -> Locale,
private val getUuid: Callable<String>?,
private val getUserToken: Callable<String>?,
private val getKey: () -> Key,
private val preferences: SharedPreferences?
private val getAppVersion: GetAppVersion,
private val getLocale: () -> Locale,
private val getUuid: Callable<String>?,
private val getUserToken: Callable<String>?,
private val getKey: () -> Key,
private val preferences: SharedPreferences?
) : Interceptor {
private val appVersionHeader = "X-TripGo-Version"
private val uuidHeader = "X-TripGo-UUID"
Expand All @@ -29,8 +32,8 @@ class AddCustomHeaders constructor(
@Throws(IOException::class)
override fun intercept(chain: Interceptor.Chain): Response {
val builder = chain.request().newBuilder()
.addHeader(acceptLanguageHeader, getLocale().language)
.addHeader(appVersionHeader, getAppVersion.execute().blockingFirst())
.addHeader(acceptLanguageHeader, getLocale().language)
.addHeader(appVersionHeader, getAppVersion.execute().blockingFirst())
builder.addHeader(acceptHeader, appJsonValue)

val key = getKey()
Expand All @@ -50,6 +53,17 @@ class AddCustomHeaders constructor(
builder.addHeader(uuidHeader, uuid)
}
}

if (HttpClientCustomDataStore.getCustomHeadersString().isNullOrBlank().not()) {
val headersMap: Map<String, String> = Gson().fromJson(HttpClientCustomDataStore.getCustomHeadersString()
?: "")
headersMap.forEach {
builder.addHeader(it.key, it.value)
}
}

return chain.proceed(builder.build())
}
}


54 changes: 32 additions & 22 deletions TripKitAndroid/src/main/java/com/skedgo/tripkit/HttpClientModule.kt
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,13 @@ package com.skedgo.tripkit

import android.content.Context
import android.content.SharedPreferences
import android.content.res.Resources
import android.webkit.URLUtil
import com.google.gson.Gson
import com.haroldadmin.cnradapter.NetworkResponseAdapterFactory
import com.skedgo.tripkit.configuration.AppVersionNameRepository
import com.skedgo.tripkit.configuration.GetAppVersion
import com.skedgo.tripkit.configuration.Server
import com.skedgo.tripkit.data.HttpClientCustomDataStore
import dagger.Lazy
import dagger.Module
import dagger.Provides
Expand All @@ -27,17 +28,17 @@ import javax.inject.Singleton
*/
@Module
open class HttpClientModule(
private val buildFlavor: String?,
private val version: String?,
private val configs: Configs,
private val sharedPreferences: SharedPreferences? = null
private val buildFlavor: String?,
private val version: String?,
private val configs: Configs,
private val sharedPreferences: SharedPreferences? = null
) {

@Singleton
@Provides
open fun httpClient(addCustomHeaders: AddCustomHeaders): OkHttpClient {
val builder = httpClientBuilder()
.addInterceptor(addCustomHeaders)
.addInterceptor(addCustomHeaders)
if (configs.debuggable()) {
val interceptor = HttpLoggingInterceptor()
interceptor.level = HttpLoggingInterceptor.Level.BODY
Expand Down Expand Up @@ -83,32 +84,41 @@ open class HttpClientModule(

@Provides
internal fun addCustomHeaders(
getAppVersion: GetAppVersion,
uuidProviderLazy: Lazy<com.skedgo.tripkit.UuidProvider>
getAppVersion: GetAppVersion,
uuidProviderLazy: Lazy<com.skedgo.tripkit.UuidProvider>
): AddCustomHeaders {
return AddCustomHeaders(
getAppVersion,
{ Locale.getDefault() },
uuidProviderLazy.get(),
configs.userTokenProvider(),
{ configs.key().call() },
sharedPreferences
getAppVersion,
{ Locale.getDefault() },
uuidProviderLazy.get(),
configs.userTokenProvider(),
{ configs.key().call() },
sharedPreferences
)
}

@Provides
open fun retrofitBuilder(gson: Gson): Retrofit.Builder = Retrofit.Builder()
.baseUrl(Server.ApiTripGo.value)
.addCallAdapterFactory(NetworkResponseAdapterFactory())
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.addConverterFactory(GsonConverterFactory.create(gson))
open fun retrofitBuilder(gson: Gson): Retrofit.Builder {
val customUrl = HttpClientCustomDataStore.getCustomBaseUrl()
val baseUrl = if (customUrl != null && URLUtil.isValidUrl(customUrl)) {
customUrl
} else {
Server.ApiTripGo.value
}

return Retrofit.Builder()
.baseUrl(baseUrl)
.addCallAdapterFactory(NetworkResponseAdapterFactory())
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.addConverterFactory(GsonConverterFactory.create(gson))
}

@Provides
open fun getTripUpdateApi(builder: Retrofit.Builder, httpClient: OkHttpClient): TripUpdateApi {
return builder
.client(httpClient)
.build()
.create(TripUpdateApi::class.java)
.client(httpClient)
.build()
.create(TripUpdateApi::class.java)
}

@Singleton
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,47 +5,39 @@
import com.skedgo.tripkit.common.model.Location;
import com.skedgo.tripkit.common.model.Region;

import com.skedgo.tripkit.data.HttpClientCustomDataStore;
import com.skedgo.tripkit.data.regions.RegionService;

import io.reactivex.functions.Function;
import io.reactivex.functions.Predicate;
import okhttp3.HttpUrl;
import io.reactivex.Observable;

final class LocationInfoServiceImpl implements LocationInfoService {
private final LocationInfoApi api;
private final RegionService regionService;
private final LocationInfoApi api;
private final RegionService regionService;

LocationInfoServiceImpl(
@NonNull LocationInfoApi api,
@NonNull RegionService regionService) {
this.api = api;
this.regionService = regionService;
}
LocationInfoServiceImpl(
@NonNull LocationInfoApi api,
@NonNull RegionService regionService) {
this.api = api;
this.regionService = regionService;
}

@Override public Observable<LocationInfo> getLocationInfoAsync(final Location location) {
return regionService.getRegionByLocationAsync(location)
.flatMap(new Function<Region, Observable<String>>() {
@Override public Observable<String> apply(Region region) {
return Observable.fromIterable(region.getURLs());
}
})
.concatMap(new Function<String, Observable<LocationInfo>>() {
@Override public Observable<LocationInfo> apply(final String baseUrl) {
final String url = HttpUrl.parse(baseUrl).newBuilder()
.addPathSegment("locationInfo.json")
.build()
.toString();
return api.fetchLocationInfoAsync(
url,
location.getLat(),
location.getLon()
);
}
})
.filter(new Predicate<LocationInfo>() {
@Override public boolean test(LocationInfo response) {
return response != null;
}
}).firstElement().toObservable();
}
@Override
public Observable<LocationInfo> getLocationInfoAsync(final Location location) {
return regionService.getRegionByLocationAsync(location)
.flatMap((Function<Region, Observable<String>>) region -> Observable.fromIterable(region.getURLs(HttpClientCustomDataStore.INSTANCE.getCustomBaseUrl())))
.concatMap((Function<String, Observable<LocationInfo>>) baseUrl -> {
final String url = HttpUrl.parse(baseUrl).newBuilder()
.addPathSegment("locationInfo.json")
.build()
.toString();
return api.fetchLocationInfoAsync(
url,
location.getLat(),
location.getLon()
);
})
.filter(response -> response != null).firstElement().toObservable();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ import io.reactivex.Observable
import com.skedgo.tripkit.a2brouting.FailoverA2bRoutingApi
import com.skedgo.tripkit.a2brouting.RouteService
import com.skedgo.tripkit.a2brouting.ToWeightingProfileString
import com.skedgo.tripkit.data.HttpClientCustomDataStore
import com.skedgo.tripkit.routing.TripGroup

internal class RouteServiceImpl(
Expand All @@ -40,9 +41,8 @@ internal class RouteServiceImpl(
return flatSubQueries(query, transportModeFilter)
.flatMap { subQuery ->


val region = subQuery.region
val baseUrls = region!!.urLs
val baseUrls = region!!.getURLs(HttpClientCustomDataStore.getCustomBaseUrl())
val modes = subQuery.transportModeIds
val excludeStops = subQuery.excludedStopCodes
val avoidModes = region.transportModeIds.orEmpty().map { it }.filter { transportModeFilter.avoidTransportMode(it) }
Expand All @@ -61,6 +61,7 @@ internal class RouteServiceImpl(
}
}


if (co2Preferences != null) {
val co2Profile = co2Preferences.co2Profile
for ((key, value) in co2Profile) {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
package com.skedgo.tripkit.data

import android.annotation.SuppressLint
import android.content.Context
import android.content.SharedPreferences
import com.google.gson.Gson

@SuppressLint("StaticFieldLeak")
object HttpClientCustomDataStore {

private val gson = Gson()
private var context: Context? = null
private var sharedPreferences: SharedPreferences? = null
private const val KEY_CUSTOM_HEADERS = "_custom_headers"
private const val KEY_CUSTOM_BASE_URL = "_custom_base_url"

fun init(context: Context) {
this.context = context
sharedPreferences = context.getSharedPreferences("HttpClientSharedPref", 0)
}

fun setCustomHeaders(headers: Map<String, String>) {
sharedPreferences?.apply {
edit().putString(KEY_CUSTOM_HEADERS, gson.toJson(headers)).apply()
}
}

fun getCustomHeadersString(): String? = sharedPreferences?.getString(KEY_CUSTOM_HEADERS, null)

fun setCustomBaseUrl(url: String) {
sharedPreferences?.apply {
edit().putString(KEY_CUSTOM_BASE_URL, url).apply()
}
}

fun getCustomBaseUrl(): String? = sharedPreferences?.getString(KEY_CUSTOM_BASE_URL, null)
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
package com.skedgo.tripkit.extensions

import com.google.gson.Gson
import com.google.gson.reflect.TypeToken

inline fun <reified T> Gson.fromJson(json: String) = fromJson<T>(json, object: TypeToken<T>() {}.type)
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package com.skedgo.tripkit.tsp

import com.skedgo.tripkit.common.model.Region
import com.skedgo.tripkit.data.HttpClientCustomDataStore
import com.skedgo.tripkit.data.tsp.RegionInfo
import io.reactivex.Observable
import javax.inject.Inject
Expand All @@ -15,7 +16,7 @@ open class RegionInfoRepository @Inject constructor(
if (regionInfoMap.containsKey(region.name)) {
Observable.just(regionInfoMap[region.name])
} else {
regionInfoService.fetchRegionInfoAsync(region.urLs!!, region.name)
regionInfoService.fetchRegionInfoAsync(region.getURLs(HttpClientCustomDataStore.getCustomBaseUrl())!!, region.name)
.doOnNext { regionInfoMap[region.name!!] = it }
}
}
Loading

0 comments on commit d6870ff

Please sign in to comment.