From fe5cc504fecce37e7c9d99e3449469ca2c996be7 Mon Sep 17 00:00:00 2001 From: Luciano Balmaceda Date: Wed, 13 Jan 2021 23:16:48 +0100 Subject: [PATCH 1/5] Rename .java to .kt --- .../request/internal/{GsonProvider.java => GsonProvider.kt} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename auth0/src/main/java/com/auth0/android/request/internal/{GsonProvider.java => GsonProvider.kt} (100%) diff --git a/auth0/src/main/java/com/auth0/android/request/internal/GsonProvider.java b/auth0/src/main/java/com/auth0/android/request/internal/GsonProvider.kt similarity index 100% rename from auth0/src/main/java/com/auth0/android/request/internal/GsonProvider.java rename to auth0/src/main/java/com/auth0/android/request/internal/GsonProvider.kt From ea612cd75c29e820f76eae3e3838960ad0aae204 Mon Sep 17 00:00:00 2001 From: Luciano Balmaceda Date: Wed, 13 Jan 2021 23:16:50 +0100 Subject: [PATCH 2/5] Make GsonProvider expose a singleton --- .../android/request/internal/GsonProvider.kt | 75 +++++++++---------- 1 file changed, 36 insertions(+), 39 deletions(-) diff --git a/auth0/src/main/java/com/auth0/android/request/internal/GsonProvider.kt b/auth0/src/main/java/com/auth0/android/request/internal/GsonProvider.kt index 653fba6c5..821e92c6b 100755 --- a/auth0/src/main/java/com/auth0/android/request/internal/GsonProvider.kt +++ b/auth0/src/main/java/com/auth0/android/request/internal/GsonProvider.kt @@ -1,43 +1,40 @@ -package com.auth0.android.request.internal; - -import androidx.annotation.NonNull; -import androidx.annotation.VisibleForTesting; - -import com.auth0.android.result.Credentials; -import com.auth0.android.result.UserProfile; -import com.auth0.android.util.JsonRequiredTypeAdapterFactory; -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; -import com.google.gson.reflect.TypeToken; - -import java.lang.reflect.Type; -import java.security.PublicKey; -import java.text.SimpleDateFormat; -import java.util.Date; -import java.util.Locale; -import java.util.Map; - -public abstract class GsonProvider { - - static final String DATE_FORMAT = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"; - - @NonNull - public static Gson buildGson() { - Type jwksType = new TypeToken>() { - }.getType(); - - return new GsonBuilder() - .registerTypeAdapterFactory(new JsonRequiredTypeAdapterFactory()) - .registerTypeAdapter(UserProfile.class, new UserProfileDeserializer()) - .registerTypeAdapter(Credentials.class, new CredentialsDeserializer()) - .registerTypeAdapter(jwksType, new JwksDeserializer()) - .setDateFormat(DATE_FORMAT) - .create(); +package com.auth0.android.request.internal + +import androidx.annotation.VisibleForTesting +import com.auth0.android.result.Credentials +import com.auth0.android.result.UserProfile +import com.auth0.android.util.JsonRequiredTypeAdapterFactory +import com.google.gson.Gson +import com.google.gson.GsonBuilder +import com.google.gson.reflect.TypeToken +import java.security.PublicKey +import java.text.SimpleDateFormat +import java.util.* + +internal object GsonProvider { + internal val gson: Gson + private var sdf: SimpleDateFormat + private const val DATE_FORMAT = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'" + + init { + val jwksType = TypeToken.getParameterized( + Map::class.java, + String::class.java, + PublicKey::class.java + ).type + gson = GsonBuilder() + .registerTypeAdapterFactory(JsonRequiredTypeAdapterFactory()) + .registerTypeAdapter(UserProfile::class.java, UserProfileDeserializer()) + .registerTypeAdapter(Credentials::class.java, CredentialsDeserializer()) + .registerTypeAdapter(jwksType, JwksDeserializer()) + .setDateFormat(DATE_FORMAT) + .create() + sdf = SimpleDateFormat(DATE_FORMAT, Locale.US) } + @JvmStatic @VisibleForTesting - static String formatDate(Date date) { - SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT, Locale.US); - return sdf.format(date); + fun formatDate(date: Date): String { + return sdf.format(date) } -} +} \ No newline at end of file From a093bcf98a1eec35921917ab82830bb8ca656324 Mon Sep 17 00:00:00 2001 From: Luciano Balmaceda Date: Wed, 13 Jan 2021 23:17:23 +0100 Subject: [PATCH 3/5] Rename .java to .kt --- ...sDeserializer.java => JwksDeserializer.kt} | 0 .../internal/BaseAuthenticationRequestTest.kt | 26 ++-- .../request/internal/BaseRequestTest.kt | 134 +++++++++--------- ...st.java => CredentialsDeserializerTest.kt} | 0 ...lsGsonTest.java => CredentialsGsonTest.kt} | 0 .../{GsonBaseTest.java => GsonBaseTest.kt} | 0 .../{JwksGsonTest.java => JwksGsonTest.kt} | 0 ...yGsonTest.java => UserIdentityGsonTest.kt} | 0 ...leGsonTest.java => UserProfileGsonTest.kt} | 0 9 files changed, 80 insertions(+), 80 deletions(-) rename auth0/src/main/java/com/auth0/android/request/internal/{JwksDeserializer.java => JwksDeserializer.kt} (100%) rename auth0/src/test/java/com/auth0/android/request/internal/{CredentialsDeserializerTest.java => CredentialsDeserializerTest.kt} (100%) rename auth0/src/test/java/com/auth0/android/request/internal/{CredentialsGsonTest.java => CredentialsGsonTest.kt} (100%) rename auth0/src/test/java/com/auth0/android/request/internal/{GsonBaseTest.java => GsonBaseTest.kt} (100%) rename auth0/src/test/java/com/auth0/android/request/internal/{JwksGsonTest.java => JwksGsonTest.kt} (100%) rename auth0/src/test/java/com/auth0/android/request/internal/{UserIdentityGsonTest.java => UserIdentityGsonTest.kt} (100%) rename auth0/src/test/java/com/auth0/android/request/internal/{UserProfileGsonTest.java => UserProfileGsonTest.kt} (100%) diff --git a/auth0/src/main/java/com/auth0/android/request/internal/JwksDeserializer.java b/auth0/src/main/java/com/auth0/android/request/internal/JwksDeserializer.kt similarity index 100% rename from auth0/src/main/java/com/auth0/android/request/internal/JwksDeserializer.java rename to auth0/src/main/java/com/auth0/android/request/internal/JwksDeserializer.kt diff --git a/auth0/src/test/java/com/auth0/android/request/internal/BaseAuthenticationRequestTest.kt b/auth0/src/test/java/com/auth0/android/request/internal/BaseAuthenticationRequestTest.kt index cb6ed2f5c..d171be786 100644 --- a/auth0/src/test/java/com/auth0/android/request/internal/BaseAuthenticationRequestTest.kt +++ b/auth0/src/test/java/com/auth0/android/request/internal/BaseAuthenticationRequestTest.kt @@ -38,7 +38,7 @@ public class BaseAuthenticationRequestTest { private fun createRequest(url: String): AuthenticationRequest { val baseRequest: Request = - BaseRequest(HttpMethod.POST, url, client, resultAdapter, errorAdapter) + BaseRequest(HttpMethod.POST, url, client, resultAdapter, errorAdapter) val request: AuthenticationRequest = BaseAuthenticationRequest(baseRequest) return Mockito.spy(request) } @@ -48,8 +48,8 @@ public class BaseAuthenticationRequestTest { public fun shouldSetGrantType() { mockSuccessfulServerResponse() createRequest(BASE_URL) - .setGrantType("grantType") - .execute() + .setGrantType("grantType") + .execute() verify(client).load(eq(BASE_URL), optionsCaptor.capture()) val values: Map = optionsCaptor.firstValue.parameters MatcherAssert.assertThat(values, IsMapWithSize.aMapWithSize(1)) @@ -61,8 +61,8 @@ public class BaseAuthenticationRequestTest { public fun shouldSetConnection() { mockSuccessfulServerResponse() createRequest(BASE_URL) - .setConnection("my-connection") - .execute() + .setConnection("my-connection") + .execute() verify(client).load(eq(BASE_URL), optionsCaptor.capture()) val values: Map = optionsCaptor.firstValue.parameters MatcherAssert.assertThat(values, IsMapWithSize.aMapWithSize(1)) @@ -74,8 +74,8 @@ public class BaseAuthenticationRequestTest { public fun shouldSetRealm() { mockSuccessfulServerResponse() createRequest(BASE_URL) - .setRealm("my-realm") - .execute() + .setRealm("my-realm") + .execute() verify(client).load(eq(BASE_URL), optionsCaptor.capture()) val values: Map = optionsCaptor.firstValue.parameters MatcherAssert.assertThat(values, IsMapWithSize.aMapWithSize(1)) @@ -87,8 +87,8 @@ public class BaseAuthenticationRequestTest { public fun shouldSetScope() { mockSuccessfulServerResponse() createRequest(BASE_URL) - .setScope("email profile") - .execute() + .setScope("email profile") + .execute() verify(client).load(eq(BASE_URL), optionsCaptor.capture()) val values: Map = optionsCaptor.firstValue.parameters MatcherAssert.assertThat(values, IsMapWithSize.aMapWithSize(1)) @@ -100,8 +100,8 @@ public class BaseAuthenticationRequestTest { public fun shouldSetAudience() { mockSuccessfulServerResponse() createRequest(BASE_URL) - .setAudience("my-api") - .execute() + .setAudience("my-api") + .execute() verify(client).load(eq(BASE_URL), optionsCaptor.capture()) val values: Map = optionsCaptor.firstValue.parameters MatcherAssert.assertThat(values, IsMapWithSize.aMapWithSize(1)) @@ -116,8 +116,8 @@ public class BaseAuthenticationRequestTest { parameters["extra"] = "value" parameters["123"] = "890" createRequest(BASE_URL) - .addParameters(parameters) - .execute() + .addParameters(parameters) + .execute() verify(client).load(eq(BASE_URL), optionsCaptor.capture()) val values: Map = optionsCaptor.firstValue.parameters MatcherAssert.assertThat(values, IsMapWithSize.aMapWithSize(2)) diff --git a/auth0/src/test/java/com/auth0/android/request/internal/BaseRequestTest.kt b/auth0/src/test/java/com/auth0/android/request/internal/BaseRequestTest.kt index e4f963ff9..2fb673c74 100755 --- a/auth0/src/test/java/com/auth0/android/request/internal/BaseRequestTest.kt +++ b/auth0/src/test/java/com/auth0/android/request/internal/BaseRequestTest.kt @@ -70,11 +70,11 @@ public class BaseRequestTest { MockitoAnnotations.openMocks(this) resultAdapter = Mockito.spy(GsonAdapter(SimplePojo::class.java, Gson())) baseRequest = BaseRequest( - HttpMethod.POST, - BASE_URL, - client, - resultAdapter, - errorAdapter + HttpMethod.POST, + BASE_URL, + client, + resultAdapter, + errorAdapter ) } @@ -123,14 +123,14 @@ public class BaseRequestTest { public fun shouldBuildErrorFromException() { val networkError = mock() Mockito.`when`( - client.load( - eq(BASE_URL), any() - ) + client.load( + eq(BASE_URL), any() + ) ).thenThrow(networkError) Mockito.`when`( - errorAdapter.fromException( - any() - ) + errorAdapter.fromException( + any() + ) ).thenReturn(auth0Exception) var exception: Exception? = null var result: SimplePojo? = null @@ -160,14 +160,14 @@ public class BaseRequestTest { MatcherAssert.assertThat(exception, Matchers.`is`(Matchers.notNullValue())) MatcherAssert.assertThat(exception, Matchers.`is`(auth0Exception)) verify(errorAdapter).fromJsonResponse( - eq(422), any() + eq(422), any() ) val reader = readerCaptor.firstValue MatcherAssert.assertThat(reader, Matchers.`is`(Matchers.notNullValue())) MatcherAssert.assertThat( - reader, Matchers.`is`( + reader, Matchers.`is`( Matchers.instanceOf( - AwareInputStreamReader::class.java + AwareInputStreamReader::class.java ) ) ) @@ -192,17 +192,17 @@ public class BaseRequestTest { MatcherAssert.assertThat(exception, Matchers.`is`(auth0Exception)) val headersMapCaptor: KArgumentCaptor>> = argumentCaptor() verify(errorAdapter).fromRawResponse( - eq(500), - eq("Failure"), - headersMapCaptor.capture() + eq(500), + eq("Failure"), + headersMapCaptor.capture() ) val headersMap = headersMapCaptor.firstValue MatcherAssert.assertThat(headersMap, Matchers.`is`(Matchers.notNullValue())) MatcherAssert.assertThat(headersMap, IsMapWithSize.aMapWithSize(1)) MatcherAssert.assertThat( - headersMap, - IsMapContaining.hasEntry( - Matchers.`is`("Content-Type"), + headersMap, + IsMapContaining.hasEntry( + Matchers.`is`("Content-Type"), IsCollectionContaining.hasItem("text/plain") ) ) @@ -224,14 +224,14 @@ public class BaseRequestTest { MatcherAssert.assertThat(result, Matchers.`is`(Matchers.notNullValue())) MatcherAssert.assertThat(result!!.prop, Matchers.`is`("test-value")) verify(resultAdapter).fromJson( - readerCaptor.capture() + readerCaptor.capture() ) val reader = readerCaptor.firstValue MatcherAssert.assertThat(reader, Matchers.`is`(Matchers.notNullValue())) MatcherAssert.assertThat( - reader, Matchers.`is`( + reader, Matchers.`is`( Matchers.instanceOf( - AwareInputStreamReader::class.java + AwareInputStreamReader::class.java ) ) ) @@ -245,14 +245,14 @@ public class BaseRequestTest { public fun shouldExecuteRequestOnBackgroundThreadAndPostSuccessToMainThread() { val pausedExecutorService = PausedExecutorService() val threadSwitcher = - Mockito.spy(ThreadSwitcher(Looper.getMainLooper(), pausedExecutorService)) + Mockito.spy(ThreadSwitcher(Looper.getMainLooper(), pausedExecutorService)) val baseRequest = BaseRequest( - HttpMethod.POST, - BASE_URL, - client, - resultAdapter, - errorAdapter, - threadSwitcher + HttpMethod.POST, + BASE_URL, + client, + resultAdapter, + errorAdapter, + threadSwitcher ) mockSuccessfulServerResponse() val callback: Callback = mock() @@ -260,31 +260,31 @@ public class BaseRequestTest { // verify background thread is queued baseRequest.start(callback) verify(threadSwitcher).backgroundThread( - any() + any() ) verify(threadSwitcher, Mockito.never()).mainThread( - any() + any() ) // let the background thread run MatcherAssert.assertThat(pausedExecutorService.runNext(), Matchers.`is`(true)) verify(threadSwitcher).mainThread( - any() + any() ) verify(callback, Mockito.never()).onSuccess( - any() + any() ) // Release the main thread queue ShadowLooper.shadowMainLooper().idle() val pojoCaptor = ArgumentCaptor.forClass( - SimplePojo::class.java + SimplePojo::class.java ) verify(callback).onSuccess(pojoCaptor.capture()) MatcherAssert.assertThat(pojoCaptor.value, Matchers.`is`(Matchers.notNullValue())) MatcherAssert.assertThat(pojoCaptor.value.prop, Matchers.`is`("test-value")) verify(callback, Mockito.never()).onFailure( - any() + any() ) } @@ -293,14 +293,14 @@ public class BaseRequestTest { public fun shouldExecuteRequestOnBackgroundThreadAndPostFailureToMainThread() { val pausedExecutorService = PausedExecutorService() val threadSwitcher = - Mockito.spy(ThreadSwitcher(Looper.getMainLooper(), pausedExecutorService)) + Mockito.spy(ThreadSwitcher(Looper.getMainLooper(), pausedExecutorService)) val baseRequest = BaseRequest( - HttpMethod.POST, - BASE_URL, - client, - resultAdapter, - errorAdapter, - threadSwitcher + HttpMethod.POST, + BASE_URL, + client, + resultAdapter, + errorAdapter, + threadSwitcher ) mockFailedRawServerResponse() val callback: Callback = mock() @@ -308,28 +308,28 @@ public class BaseRequestTest { // verify background thread is queued baseRequest.start(callback) verify(threadSwitcher).backgroundThread( - any() + any() ) verify(threadSwitcher, Mockito.never()).mainThread( - any() + any() ) // let the background thread run MatcherAssert.assertThat(pausedExecutorService.runNext(), Matchers.`is`(true)) verify(threadSwitcher).mainThread( - any() + any() ) verify(callback, Mockito.never()).onFailure( - any() + any() ) // Release the main thread queue ShadowLooper.shadowMainLooper().idle() verify(callback).onFailure( - any() + any() ) verify(callback, Mockito.never()).onSuccess( - any() + any() ) } @@ -340,9 +340,9 @@ public class BaseRequestTest { val inputStream: InputStream = ByteArrayInputStream(jsonResponse.toByteArray()) val response = ServerResponse(200, inputStream, headers) Mockito.`when`( - client.load( - eq(BASE_URL), any() - ) + client.load( + eq(BASE_URL), any() + ) ).thenReturn(response) } @@ -352,17 +352,17 @@ public class BaseRequestTest { val textResponse = "Failure" val inputStream: InputStream = ByteArrayInputStream(textResponse.toByteArray()) Mockito.`when`( - errorAdapter.fromRawResponse( - eq(500), - ArgumentMatchers.anyString(), - ArgumentMatchers.anyMap() - ) + errorAdapter.fromRawResponse( + eq(500), + ArgumentMatchers.anyString(), + ArgumentMatchers.anyMap() + ) ).thenReturn(auth0Exception) val response = ServerResponse(500, inputStream, headers) Mockito.`when`( - client.load( - eq(BASE_URL), any() - ) + client.load( + eq(BASE_URL), any() + ) ).thenReturn(response) } @@ -372,16 +372,16 @@ public class BaseRequestTest { val jsonResponse = "{\"error_code\":\"invalid_token\"}" val inputStream: InputStream = ByteArrayInputStream(jsonResponse.toByteArray()) Mockito.`when`( - errorAdapter.fromJsonResponse( - eq(422), - readerCaptor.capture() - ) + errorAdapter.fromJsonResponse( + eq(422), + readerCaptor.capture() + ) ).thenReturn(auth0Exception) val response = ServerResponse(422, inputStream, headers) Mockito.`when`( - client.load( - eq(BASE_URL), any() - ) + client.load( + eq(BASE_URL), any() + ) ).thenReturn(response) } diff --git a/auth0/src/test/java/com/auth0/android/request/internal/CredentialsDeserializerTest.java b/auth0/src/test/java/com/auth0/android/request/internal/CredentialsDeserializerTest.kt similarity index 100% rename from auth0/src/test/java/com/auth0/android/request/internal/CredentialsDeserializerTest.java rename to auth0/src/test/java/com/auth0/android/request/internal/CredentialsDeserializerTest.kt diff --git a/auth0/src/test/java/com/auth0/android/request/internal/CredentialsGsonTest.java b/auth0/src/test/java/com/auth0/android/request/internal/CredentialsGsonTest.kt similarity index 100% rename from auth0/src/test/java/com/auth0/android/request/internal/CredentialsGsonTest.java rename to auth0/src/test/java/com/auth0/android/request/internal/CredentialsGsonTest.kt diff --git a/auth0/src/test/java/com/auth0/android/request/internal/GsonBaseTest.java b/auth0/src/test/java/com/auth0/android/request/internal/GsonBaseTest.kt similarity index 100% rename from auth0/src/test/java/com/auth0/android/request/internal/GsonBaseTest.java rename to auth0/src/test/java/com/auth0/android/request/internal/GsonBaseTest.kt diff --git a/auth0/src/test/java/com/auth0/android/request/internal/JwksGsonTest.java b/auth0/src/test/java/com/auth0/android/request/internal/JwksGsonTest.kt similarity index 100% rename from auth0/src/test/java/com/auth0/android/request/internal/JwksGsonTest.java rename to auth0/src/test/java/com/auth0/android/request/internal/JwksGsonTest.kt diff --git a/auth0/src/test/java/com/auth0/android/request/internal/UserIdentityGsonTest.java b/auth0/src/test/java/com/auth0/android/request/internal/UserIdentityGsonTest.kt similarity index 100% rename from auth0/src/test/java/com/auth0/android/request/internal/UserIdentityGsonTest.java rename to auth0/src/test/java/com/auth0/android/request/internal/UserIdentityGsonTest.kt diff --git a/auth0/src/test/java/com/auth0/android/request/internal/UserProfileGsonTest.java b/auth0/src/test/java/com/auth0/android/request/internal/UserProfileGsonTest.kt similarity index 100% rename from auth0/src/test/java/com/auth0/android/request/internal/UserProfileGsonTest.java rename to auth0/src/test/java/com/auth0/android/request/internal/UserProfileGsonTest.kt From e059e5fb0d4beb5057f1ad5783bef8e84090b595 Mon Sep 17 00:00:00 2001 From: Luciano Balmaceda Date: Wed, 13 Jan 2021 23:17:24 +0100 Subject: [PATCH 4/5] Update tests and references to GsonProvider --- .../authentication/AuthenticationAPIClient.kt | 2 +- .../storage/SecureCredentialsManager.kt | 2 +- .../android/management/UsersAPIClient.kt | 2 +- .../auth0/android/request/DefaultClient.kt | 10 +- .../android/request/internal/GsonAdapter.kt | 2 +- .../request/internal/JwksDeserializer.kt | 125 +++-- .../AuthenticationExceptionTest.kt | 3 +- .../storage/SecureCredentialsManagerTest.kt | 7 +- .../internal/CredentialsDeserializerTest.kt | 118 ++--- .../request/internal/CredentialsGsonTest.kt | 310 +++++++----- .../android/request/internal/GsonBaseTest.kt | 43 +- .../android/request/internal/JwksGsonTest.kt | 182 ++++--- .../request/internal/UserIdentityGsonTest.kt | 111 ++-- .../request/internal/UserProfileGsonTest.kt | 472 +++++++++++------- 14 files changed, 808 insertions(+), 581 deletions(-) diff --git a/auth0/src/main/java/com/auth0/android/authentication/AuthenticationAPIClient.kt b/auth0/src/main/java/com/auth0/android/authentication/AuthenticationAPIClient.kt index 70e2af3e5..72db84907 100755 --- a/auth0/src/main/java/com/auth0/android/authentication/AuthenticationAPIClient.kt +++ b/auth0/src/main/java/com/auth0/android/authentication/AuthenticationAPIClient.kt @@ -79,7 +79,7 @@ public class AuthenticationAPIClient @VisibleForTesting(otherwise = VisibleForTe ) : this( auth0, RequestFactory(networkingClient, createErrorAdapter()), - GsonProvider.buildGson() + GsonProvider.gson ) public val clientId: String diff --git a/auth0/src/main/java/com/auth0/android/authentication/storage/SecureCredentialsManager.kt b/auth0/src/main/java/com/auth0/android/authentication/storage/SecureCredentialsManager.kt index d525e209a..b15b291f8 100644 --- a/auth0/src/main/java/com/auth0/android/authentication/storage/SecureCredentialsManager.kt +++ b/auth0/src/main/java/com/auth0/android/authentication/storage/SecureCredentialsManager.kt @@ -30,7 +30,7 @@ public class SecureCredentialsManager @VisibleForTesting(otherwise = VisibleForT private val crypto: CryptoUtil, jwtDecoder: JWTDecoder ) : BaseCredentialsManager(apiClient, storage, jwtDecoder) { - private val gson: Gson = GsonProvider.buildGson() + private val gson: Gson = GsonProvider.gson //Changeable by the user private var authenticateBeforeDecrypt: Boolean diff --git a/auth0/src/main/java/com/auth0/android/management/UsersAPIClient.kt b/auth0/src/main/java/com/auth0/android/management/UsersAPIClient.kt index 08436c54d..922d31d41 100755 --- a/auth0/src/main/java/com/auth0/android/management/UsersAPIClient.kt +++ b/auth0/src/main/java/com/auth0/android/management/UsersAPIClient.kt @@ -75,7 +75,7 @@ public class UsersAPIClient @VisibleForTesting(otherwise = VisibleForTesting.PRI ) : this( auth0, factoryForToken(token, networkingClient), - GsonProvider.buildGson() + GsonProvider.gson ) public val clientId: String diff --git a/auth0/src/main/java/com/auth0/android/request/DefaultClient.kt b/auth0/src/main/java/com/auth0/android/request/DefaultClient.kt index f7f705cac..cf446f7ee 100644 --- a/auth0/src/main/java/com/auth0/android/request/DefaultClient.kt +++ b/auth0/src/main/java/com/auth0/android/request/DefaultClient.kt @@ -22,14 +22,14 @@ import java.util.concurrent.TimeUnit * @param enableLogging whether HTTP request and response info should be logged. This should only be set to `true` for debugging purposes in non-production environments, as sensitive information is included in the logs. Defaults to `false`. */ public class DefaultClient( - private val connectTimeout: Int = DEFAULT_TIMEOUT_SECONDS, - private val readTimeout: Int = DEFAULT_TIMEOUT_SECONDS, - private val defaultHeaders: Map = mapOf(), - private val enableLogging: Boolean = false + private val connectTimeout: Int = DEFAULT_TIMEOUT_SECONDS, + private val readTimeout: Int = DEFAULT_TIMEOUT_SECONDS, + private val defaultHeaders: Map = mapOf(), + private val enableLogging: Boolean = false ) : NetworkingClient { //TODO: receive this via internal constructor parameters - private val gson: Gson = GsonProvider.buildGson() + private val gson: Gson = GsonProvider.gson @get:VisibleForTesting(otherwise = VisibleForTesting.PRIVATE) internal val okHttpClient: OkHttpClient diff --git a/auth0/src/main/java/com/auth0/android/request/internal/GsonAdapter.kt b/auth0/src/main/java/com/auth0/android/request/internal/GsonAdapter.kt index ff968d957..7ed9eac0a 100644 --- a/auth0/src/main/java/com/auth0/android/request/internal/GsonAdapter.kt +++ b/auth0/src/main/java/com/auth0/android/request/internal/GsonAdapter.kt @@ -41,7 +41,7 @@ internal class GsonAdapter private constructor(private val adapter: TypeAdapt return GsonAdapter(typeToken, gson) } - private fun supplyDefaultGson() = GsonProvider.buildGson() + private fun supplyDefaultGson() = GsonProvider.gson } internal constructor( diff --git a/auth0/src/main/java/com/auth0/android/request/internal/JwksDeserializer.kt b/auth0/src/main/java/com/auth0/android/request/internal/JwksDeserializer.kt index a7ecef52f..1d63c0fd4 100644 --- a/auth0/src/main/java/com/auth0/android/request/internal/JwksDeserializer.kt +++ b/auth0/src/main/java/com/auth0/android/request/internal/JwksDeserializer.kt @@ -1,66 +1,81 @@ -package com.auth0.android.request.internal; +package com.auth0.android.request.internal -import android.util.Base64; -import android.util.Log; +import android.util.Base64 +import android.util.Log +import com.google.gson.JsonDeserializationContext +import com.google.gson.JsonDeserializer +import com.google.gson.JsonElement +import com.google.gson.JsonParseException +import java.lang.reflect.Type +import java.math.BigInteger +import java.security.KeyFactory +import java.security.NoSuchAlgorithmException +import java.security.PublicKey +import java.security.spec.InvalidKeySpecException +import java.security.spec.RSAPublicKeySpec -import com.google.gson.JsonArray; -import com.google.gson.JsonDeserializationContext; -import com.google.gson.JsonDeserializer; -import com.google.gson.JsonElement; -import com.google.gson.JsonObject; -import com.google.gson.JsonParseException; - -import java.lang.reflect.Type; -import java.math.BigInteger; -import java.security.KeyFactory; -import java.security.NoSuchAlgorithmException; -import java.security.PublicKey; -import java.security.spec.InvalidKeySpecException; -import java.security.spec.RSAPublicKeySpec; -import java.util.Collections; -import java.util.HashMap; -import java.util.Map; - -class JwksDeserializer implements JsonDeserializer> { - - private static final String RSA_ALGORITHM = "RS256"; - private static final String USE_SIGNING = "sig"; - - @Override - public Map deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { - if (!json.isJsonObject() || json.isJsonNull() || json.getAsJsonObject().entrySet().isEmpty()) { - throw new JsonParseException("jwks json must be a valid and non-empty json object"); +internal class JwksDeserializer : JsonDeserializer> { + @Throws(JsonParseException::class) + override fun deserialize( + json: JsonElement, + typeOfT: Type, + context: JsonDeserializationContext + ): Map { + if (!json.isJsonObject || json.isJsonNull || json.asJsonObject.entrySet().isEmpty()) { + throw JsonParseException("jwks json must be a valid and non-empty json object") } - - HashMap jwks = new HashMap<>(); - - JsonObject object = json.getAsJsonObject(); - JsonArray keys = object.getAsJsonArray("keys"); - for (JsonElement k : keys) { - JsonObject currentKey = k.getAsJsonObject(); - String keyAlg = context.deserialize(currentKey.get("alg"), String.class); - String keyUse = context.deserialize(currentKey.get("use"), String.class); - if (!RSA_ALGORITHM.equals(keyAlg) || !USE_SIGNING.equals(keyUse)) { + val jwks = mutableMapOf() + val keys = json.asJsonObject.getAsJsonArray("keys") + for (k in keys) { + val currentKey = k.asJsonObject + val keyAlg = context.deserialize(currentKey["alg"], String::class.java) + val keyUse = context.deserialize(currentKey["use"], String::class.java) + if (RSA_ALGORITHM != keyAlg || USE_SIGNING != keyUse) { //Key not supported at this time - continue; + continue } - String keyType = context.deserialize(currentKey.get("kty"), String.class); - String keyId = context.deserialize(currentKey.get("kid"), String.class); - String keyModulus = context.deserialize(currentKey.get("n"), String.class); - String keyPublicExponent = context.deserialize(currentKey.get("e"), String.class); - + val keyType = context.deserialize(currentKey["kty"], String::class.java) + val keyId = context.deserialize(currentKey["kid"], String::class.java) + val keyModulus = context.deserialize(currentKey["n"], String::class.java) + val keyPublicExponent = context.deserialize(currentKey["e"], String::class.java) try { - KeyFactory kf = KeyFactory.getInstance(keyType); - BigInteger modulus = new BigInteger(1, Base64.decode(keyModulus, Base64.URL_SAFE | Base64.NO_PADDING | Base64.NO_WRAP)); - BigInteger exponent = new BigInteger(1, Base64.decode(keyPublicExponent, Base64.URL_SAFE | Base64.NO_PADDING | Base64.NO_WRAP)); - PublicKey pub = kf.generatePublic(new RSAPublicKeySpec(modulus, exponent)); - jwks.put(keyId, pub); - } catch (NoSuchAlgorithmException | InvalidKeySpecException e) { - Log.e(JwksDeserializer.class.getSimpleName(), "Could not parse the JWK with ID " + keyId, e); + val kf = KeyFactory.getInstance(keyType) + val modulus = BigInteger( + 1, + Base64.decode( + keyModulus, + Base64.URL_SAFE or Base64.NO_PADDING or Base64.NO_WRAP + ) + ) + val exponent = BigInteger( + 1, + Base64.decode( + keyPublicExponent, + Base64.URL_SAFE or Base64.NO_PADDING or Base64.NO_WRAP + ) + ) + val pub = kf.generatePublic(RSAPublicKeySpec(modulus, exponent)) + jwks[keyId] = pub + } catch (e: NoSuchAlgorithmException) { + Log.e( + JwksDeserializer::class.java.simpleName, + "Could not parse the JWK with ID $keyId", + e + ) //Would result in an empty key set + } catch (e: InvalidKeySpecException) { + Log.e( + JwksDeserializer::class.java.simpleName, + "Could not parse the JWK with ID $keyId", + e + ) } } - return Collections.unmodifiableMap(jwks); + return jwks.toMap() } -} + companion object { + private const val RSA_ALGORITHM = "RS256" + private const val USE_SIGNING = "sig" + } +} \ No newline at end of file diff --git a/auth0/src/test/java/com/auth0/android/authentication/AuthenticationExceptionTest.kt b/auth0/src/test/java/com/auth0/android/authentication/AuthenticationExceptionTest.kt index 7110e9c4f..b6e149419 100644 --- a/auth0/src/test/java/com/auth0/android/authentication/AuthenticationExceptionTest.kt +++ b/auth0/src/test/java/com/auth0/android/authentication/AuthenticationExceptionTest.kt @@ -303,10 +303,9 @@ public class AuthenticationExceptionTest { @Test @Throws(Exception::class) public fun shouldHaveNotStrongPasswordWithDetailedDescription() { - val gson = GsonProvider.buildGson() val fr = FileReader(PASSWORD_STRENGTH_ERROR_RESPONSE) val mapType = object : TypeToken?>() {}.type - val mapPayload = gson.fromJson>(fr, mapType) + val mapPayload = GsonProvider.gson.fromJson>(fr, mapType) val ex = AuthenticationException(mapPayload) MatcherAssert.assertThat(ex.isPasswordNotStrongEnough, CoreMatchers.`is`(true)) val expectedDescription = diff --git a/auth0/src/test/java/com/auth0/android/authentication/storage/SecureCredentialsManagerTest.kt b/auth0/src/test/java/com/auth0/android/authentication/storage/SecureCredentialsManagerTest.kt index 86b410814..d404a6f49 100644 --- a/auth0/src/test/java/com/auth0/android/authentication/storage/SecureCredentialsManagerTest.kt +++ b/auth0/src/test/java/com/auth0/android/authentication/storage/SecureCredentialsManagerTest.kt @@ -30,8 +30,11 @@ import org.junit.Rule import org.junit.Test import org.junit.rules.ExpectedException import org.junit.runner.RunWith -import org.mockito.* +import org.mockito.ArgumentCaptor import org.mockito.ArgumentMatchers.* +import org.mockito.Mock +import org.mockito.Mockito +import org.mockito.MockitoAnnotations import org.robolectric.Robolectric import org.robolectric.RobolectricTestRunner import org.robolectric.annotation.Config @@ -84,7 +87,7 @@ public class SecureCredentialsManagerTest { SecureCredentialsManager(client, storage, crypto, jwtDecoder) manager = Mockito.spy(secureCredentialsManager) Mockito.doReturn(CredentialsMock.CURRENT_TIME_MS).`when`(manager).currentTimeInMillis - gson = GsonProvider.buildGson() + gson = GsonProvider.gson } @Test diff --git a/auth0/src/test/java/com/auth0/android/request/internal/CredentialsDeserializerTest.kt b/auth0/src/test/java/com/auth0/android/request/internal/CredentialsDeserializerTest.kt index 91c864927..5589eead3 100644 --- a/auth0/src/test/java/com/auth0/android/request/internal/CredentialsDeserializerTest.kt +++ b/auth0/src/test/java/com/auth0/android/request/internal/CredentialsDeserializerTest.kt @@ -1,73 +1,79 @@ -package com.auth0.android.request.internal; +package com.auth0.android.request.internal -import androidx.annotation.NonNull; - -import com.auth0.android.result.Credentials; -import com.auth0.android.result.CredentialsMock; -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; - -import org.junit.Before; -import org.junit.Test; - -import java.io.FileReader; -import java.util.Calendar; -import java.util.Date; - -import static org.hamcrest.CoreMatchers.notNullValue; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.closeTo; -import static org.hamcrest.core.Is.is; +import com.auth0.android.request.internal.GsonProvider.formatDate +import com.auth0.android.result.Credentials +import com.auth0.android.result.CredentialsMock +import com.google.gson.Gson +import org.hamcrest.CoreMatchers +import org.hamcrest.MatcherAssert +import org.hamcrest.Matchers +import org.hamcrest.core.Is +import org.junit.Before +import org.junit.Test +import java.io.FileReader +import java.util.* public class CredentialsDeserializerTest { - - private static final String BASIC_CREDENTIALS = "src/test/resources/credentials.json"; - - private Gson gson; + private lateinit var gson: Gson @Before - public void setUp() { - final CredentialsDeserializerMock deserializer = new CredentialsDeserializerMock(); - gson = new GsonBuilder() - .setDateFormat(GsonProvider.DATE_FORMAT) - .registerTypeAdapter(Credentials.class, deserializer) - .create(); + public fun setUp() { + val deserializer = CredentialsDeserializerMock() + gson = GsonProvider.gson.newBuilder() + .registerTypeAdapter(Credentials::class.java, deserializer) + .create() } @Test - public void shouldSetExpiresAtFromExpiresIn() throws Exception { - final Credentials credentials = gson.getAdapter(Credentials.class).fromJson(new FileReader(BASIC_CREDENTIALS)); - assertThat(credentials.getExpiresIn().doubleValue(), is(closeTo(86000, 1))); - assertThat(credentials.getExpiresAt(), is(notNullValue())); - double expiresAt = credentials.getExpiresAt().getTime(); - double expectedExpiresAt = CredentialsMock.CURRENT_TIME_MS + 86000 * 1000; - assertThat(expiresAt, is(closeTo(expectedExpiresAt, 1))); + @Throws(Exception::class) + public fun shouldSetExpiresAtFromExpiresIn() { + val credentials = gson.getAdapter( + Credentials::class.java + ).fromJson(FileReader(BASIC_CREDENTIALS)) + MatcherAssert.assertThat( + credentials.expiresIn!!.toDouble(), + Is.`is`(Matchers.closeTo(86000.0, 1.0)) + ) + MatcherAssert.assertThat(credentials.expiresAt, Is.`is`(CoreMatchers.notNullValue())) + val expiresAt = credentials.expiresAt!!.time.toDouble() + val expectedExpiresAt = (CredentialsMock.CURRENT_TIME_MS + 86000 * 1000).toDouble() + MatcherAssert.assertThat(expiresAt, Is.`is`(Matchers.closeTo(expectedExpiresAt, 1.0))) } @Test - public void shouldSetExpiresInFromExpiresAt() throws Exception { - Calendar cal = Calendar.getInstance(); - cal.add(Calendar.DAY_OF_YEAR, 7); - Date exp = cal.getTime(); - final Credentials credentials = gson.getAdapter(Credentials.class).fromJson(generateExpiresAtCredentialsJSON(exp)); + @Throws(Exception::class) + public fun shouldSetExpiresInFromExpiresAt() { + val cal = Calendar.getInstance() + cal.add(Calendar.DAY_OF_YEAR, 7) + val exp = cal.time + val credentials = gson.getAdapter( + Credentials::class.java + ).fromJson(generateExpiresAtCredentialsJSON(exp)) //The hardcoded value comes from the JSON file - assertThat(credentials.getExpiresAt(), is(notNullValue())); - double expiresAt = credentials.getExpiresAt().getTime(); - double expectedExpiresAt = exp.getTime(); - assertThat(expiresAt, is(closeTo(expectedExpiresAt, 1))); - assertThat(credentials.getExpiresIn(), is(notNullValue())); - double expectedExpiresIn = (exp.getTime() - CredentialsMock.CURRENT_TIME_MS) / 1000f; - assertThat(credentials.getExpiresIn().doubleValue(), is(closeTo(expectedExpiresIn, 1))); + MatcherAssert.assertThat(credentials.expiresAt, Is.`is`(CoreMatchers.notNullValue())) + val expiresAt = credentials.expiresAt!!.time.toDouble() + val expectedExpiresAt = exp.time.toDouble() + MatcherAssert.assertThat(expiresAt, Is.`is`(Matchers.closeTo(expectedExpiresAt, 1.0))) + MatcherAssert.assertThat(credentials.expiresIn, Is.`is`(CoreMatchers.notNullValue())) + val expectedExpiresIn = ((exp.time - CredentialsMock.CURRENT_TIME_MS) / 1000f).toDouble() + MatcherAssert.assertThat( + credentials.expiresIn!!.toDouble(), + Is.`is`(Matchers.closeTo(expectedExpiresIn, 1.0)) + ) } - - private String generateExpiresAtCredentialsJSON(@NonNull Date expiresAt) { - return "{\n" + - "\"access_token\": \"s6GS5FGJN2jfd4l6\",\n" + - "\"token_type\": \"bearer\",\n" + - "\"expires_in\": 86000,\n" + - "\"expires_at\": \"" + GsonProvider.formatDate(expiresAt) + "\"\n" + - "}"; + private fun generateExpiresAtCredentialsJSON(expiresAt: Date): String { + return """ + { + "access_token": "s6GS5FGJN2jfd4l6", + "token_type": "bearer", + "expires_in": 86000, + "expires_at": "${formatDate(expiresAt)}" + } + """.trimIndent() } + private companion object { + private const val BASIC_CREDENTIALS = "src/test/resources/credentials.json" + } } \ No newline at end of file diff --git a/auth0/src/test/java/com/auth0/android/request/internal/CredentialsGsonTest.kt b/auth0/src/test/java/com/auth0/android/request/internal/CredentialsGsonTest.kt index 9b8edc690..4ed34fc80 100755 --- a/auth0/src/test/java/com/auth0/android/request/internal/CredentialsGsonTest.kt +++ b/auth0/src/test/java/com/auth0/android/request/internal/CredentialsGsonTest.kt @@ -1,164 +1,216 @@ -package com.auth0.android.request.internal; - -import androidx.annotation.NonNull; - -import com.auth0.android.result.Credentials; -import com.auth0.android.result.CredentialsMock; -import com.google.gson.JsonParseException; - -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; - -import java.io.IOException; -import java.io.Reader; -import java.io.StringReader; -import java.util.Calendar; -import java.util.Date; - -import static org.hamcrest.CoreMatchers.containsString; -import static org.hamcrest.CoreMatchers.not; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.closeTo; -import static org.hamcrest.Matchers.equalTo; -import static org.hamcrest.Matchers.is; -import static org.hamcrest.Matchers.notNullValue; -import static org.hamcrest.Matchers.nullValue; - -public class CredentialsGsonTest extends GsonBaseTest { - private static final String OPEN_ID_OFFLINE_ACCESS_CREDENTIALS = "src/test/resources/credentials_openid_refresh_token.json"; - private static final String OPEN_ID_CREDENTIALS = "src/test/resources/credentials_openid.json"; - private static final String BASIC_CREDENTIALS = "src/test/resources/credentials.json"; - - @Rule - public ExpectedException expectedException = ExpectedException.none(); - +package com.auth0.android.request.internal + +import com.auth0.android.request.internal.GsonProvider.formatDate +import com.auth0.android.result.Credentials +import com.auth0.android.result.CredentialsMock +import com.google.gson.JsonParseException +import org.hamcrest.CoreMatchers +import org.hamcrest.MatcherAssert +import org.hamcrest.Matchers +import org.junit.Assert +import org.junit.Before +import org.junit.Test +import java.io.IOException +import java.io.Reader +import java.io.StringReader +import java.util.* + +public class CredentialsGsonTest : GsonBaseTest() { @Before - public void setUp() { - gson = GsonProvider.buildGson(); + public fun setUp() { + gson = GsonProvider.gson } @Test - public void shouldFailWithInvalidJson() throws Exception { - expectedException.expect(JsonParseException.class); - buildCredentialsFrom(json(INVALID)); + @Throws(Exception::class) + public fun shouldFailWithInvalidJson() { + Assert.assertThrows(JsonParseException::class.java) { + buildCredentialsFrom(json(INVALID)) + } } @Test - public void shouldFailWithEmptyJson() throws Exception { - expectedException.expect(JsonParseException.class); - buildCredentialsFrom(json(EMPTY_OBJECT)); + @Throws(Exception::class) + public fun shouldFailWithEmptyJson() { + Assert.assertThrows(JsonParseException::class.java) { + buildCredentialsFrom(json(EMPTY_OBJECT)) + } } @Test - public void shouldNotRequireAccessToken() throws Exception { - buildCredentialsFrom(new StringReader("{\"token_type\": \"bearer\"}")); + @Throws(Exception::class) + public fun shouldNotRequireAccessToken() { + buildCredentialsFrom(StringReader("{\"token_type\": \"bearer\"}")) } @Test - public void shouldNotRequireTokenType() throws Exception { - buildCredentialsFrom(new StringReader("{\"access_token\": \"some token\"}")); + @Throws(Exception::class) + public fun shouldNotRequireTokenType() { + buildCredentialsFrom(StringReader("{\"access_token\": \"some token\"}")) } @Test - public void shouldReturnBasic() throws Exception { - final Credentials credentials = buildCredentialsFrom(json(BASIC_CREDENTIALS)); - assertThat(credentials, is(notNullValue())); - assertThat(credentials.getAccessToken(), is(notNullValue())); - assertThat(credentials.getIdToken(), is(nullValue())); - assertThat(credentials.getType(), equalTo("bearer")); - assertThat(credentials.getRefreshToken(), is(nullValue())); - assertThat(credentials.getExpiresIn(), is(notNullValue())); - assertThat(credentials.getExpiresIn().doubleValue(), is(closeTo(86000, 1))); - assertThat(credentials.getExpiresAt(), is(notNullValue())); - assertThat(credentials.getScope(), is(nullValue())); + @Throws(Exception::class) + public fun shouldReturnBasic() { + val credentials = buildCredentialsFrom(json(BASIC_CREDENTIALS)) + MatcherAssert.assertThat(credentials, Matchers.`is`(Matchers.notNullValue())) + MatcherAssert.assertThat(credentials.accessToken, Matchers.`is`(Matchers.notNullValue())) + MatcherAssert.assertThat(credentials.idToken, Matchers.`is`(Matchers.nullValue())) + MatcherAssert.assertThat(credentials.type, Matchers.equalTo("bearer")) + MatcherAssert.assertThat(credentials.refreshToken, Matchers.`is`(Matchers.nullValue())) + MatcherAssert.assertThat(credentials.expiresIn, Matchers.`is`(Matchers.notNullValue())) + MatcherAssert.assertThat( + credentials.expiresIn!!.toDouble(), + Matchers.`is`(Matchers.closeTo(86000.0, 1.0)) + ) + MatcherAssert.assertThat(credentials.expiresAt, Matchers.`is`(Matchers.notNullValue())) + MatcherAssert.assertThat(credentials.scope, Matchers.`is`(Matchers.nullValue())) } @Test - public void shouldReturnWithExpiresAt() throws Exception { - Calendar cal = Calendar.getInstance(); - cal.add(Calendar.DAY_OF_YEAR, 1); - Date exp = cal.getTime(); - String credentialsJSON = generateJSONWithExpiresAt(exp); - final Credentials credentials = buildCredentialsFrom(new StringReader(credentialsJSON)); - assertThat(credentials, is(notNullValue())); - assertThat(credentials.getAccessToken(), is(notNullValue())); - assertThat(credentials.getType(), equalTo("bearer")); + @Throws(Exception::class) + public fun shouldReturnWithExpiresAt() { + val cal = Calendar.getInstance() + cal.add(Calendar.DAY_OF_YEAR, 1) + val exp = cal.time + val credentialsJSON = generateJSONWithExpiresAt(exp) + val credentials = buildCredentialsFrom(StringReader(credentialsJSON)) + MatcherAssert.assertThat(credentials, Matchers.`is`(Matchers.notNullValue())) + MatcherAssert.assertThat(credentials.accessToken, Matchers.`is`(Matchers.notNullValue())) + MatcherAssert.assertThat(credentials.type, Matchers.equalTo("bearer")) //The hardcoded value comes from the JSON file - assertThat(credentials.getExpiresIn(), is(notNullValue())); - double expectedCalculatedExpiresIn = (exp.getTime() - System.currentTimeMillis()) / 1000f; - assertThat(credentials.getExpiresIn().doubleValue(), is(closeTo(expectedCalculatedExpiresIn, 1))); - assertThat(credentials.getExpiresAt(), is(notNullValue())); - double expiresAt = credentials.getExpiresAt().getTime(); - assertThat(expiresAt, is(closeTo(exp.getTime(), 1))); + MatcherAssert.assertThat(credentials.expiresIn, Matchers.`is`(Matchers.notNullValue())) + val expectedCalculatedExpiresIn = + ((exp.time - System.currentTimeMillis()) / 1000f).toDouble() + MatcherAssert.assertThat( + credentials.expiresIn!!.toDouble(), + Matchers.`is`(Matchers.closeTo(expectedCalculatedExpiresIn, 1.0)) + ) + MatcherAssert.assertThat(credentials.expiresAt, Matchers.`is`(Matchers.notNullValue())) + val expiresAt = credentials.expiresAt!!.time.toDouble() + MatcherAssert.assertThat( + expiresAt, + Matchers.`is`(Matchers.closeTo(exp.time.toDouble(), 1.0)) + ) } @Test - public void shouldReturnWithIdToken() throws Exception { - final Credentials credentials = buildCredentialsFrom(json(OPEN_ID_CREDENTIALS)); - assertThat(credentials, is(notNullValue())); - assertThat(credentials.getAccessToken(), is(notNullValue())); - assertThat(credentials.getIdToken(), is(notNullValue())); - assertThat(credentials.getType(), equalTo("bearer")); - assertThat(credentials.getRefreshToken(), is(nullValue())); - assertThat(credentials.getExpiresIn(), is(notNullValue())); - assertThat(credentials.getExpiresIn().doubleValue(), is(closeTo(86000, 1))); - assertThat(credentials.getExpiresAt(), is(notNullValue())); - assertThat(credentials.getScope(), is("openid profile")); + @Throws(Exception::class) + public fun shouldReturnWithIdToken() { + val credentials = buildCredentialsFrom(json(OPEN_ID_CREDENTIALS)) + MatcherAssert.assertThat(credentials, Matchers.`is`(Matchers.notNullValue())) + MatcherAssert.assertThat(credentials.accessToken, Matchers.`is`(Matchers.notNullValue())) + MatcherAssert.assertThat(credentials.idToken, Matchers.`is`(Matchers.notNullValue())) + MatcherAssert.assertThat(credentials.type, Matchers.equalTo("bearer")) + MatcherAssert.assertThat(credentials.refreshToken, Matchers.`is`(Matchers.nullValue())) + MatcherAssert.assertThat(credentials.expiresIn, Matchers.`is`(Matchers.notNullValue())) + MatcherAssert.assertThat( + credentials.expiresIn!!.toDouble(), + Matchers.`is`(Matchers.closeTo(86000.0, 1.0)) + ) + MatcherAssert.assertThat(credentials.expiresAt, Matchers.`is`(Matchers.notNullValue())) + MatcherAssert.assertThat(credentials.scope, Matchers.`is`("openid profile")) } @Test - public void shouldReturnWithRefreshToken() throws Exception { - final Credentials credentials = buildCredentialsFrom(json(OPEN_ID_OFFLINE_ACCESS_CREDENTIALS)); - assertThat(credentials, is(notNullValue())); - assertThat(credentials.getAccessToken(), is(notNullValue())); - assertThat(credentials.getIdToken(), is(notNullValue())); - assertThat(credentials.getType(), equalTo("bearer")); - assertThat(credentials.getRefreshToken(), is(notNullValue())); - assertThat(credentials.getExpiresIn(), is(notNullValue())); - assertThat(credentials.getExpiresIn().doubleValue(), is(closeTo(86000, 1))); - assertThat(credentials.getExpiresAt(), is(notNullValue())); - assertThat(credentials.getScope(), is("openid profile")); + @Throws(Exception::class) + public fun shouldReturnWithRefreshToken() { + val credentials = buildCredentialsFrom(json(OPEN_ID_OFFLINE_ACCESS_CREDENTIALS)) + MatcherAssert.assertThat(credentials, Matchers.`is`(Matchers.notNullValue())) + MatcherAssert.assertThat(credentials.accessToken, Matchers.`is`(Matchers.notNullValue())) + MatcherAssert.assertThat(credentials.idToken, Matchers.`is`(Matchers.notNullValue())) + MatcherAssert.assertThat(credentials.type, Matchers.equalTo("bearer")) + MatcherAssert.assertThat(credentials.refreshToken, Matchers.`is`(Matchers.notNullValue())) + MatcherAssert.assertThat(credentials.expiresIn, Matchers.`is`(Matchers.notNullValue())) + MatcherAssert.assertThat( + credentials.expiresIn!!.toDouble(), + Matchers.`is`(Matchers.closeTo(86000.0, 1.0)) + ) + MatcherAssert.assertThat(credentials.expiresAt, Matchers.`is`(Matchers.notNullValue())) + MatcherAssert.assertThat(credentials.scope, Matchers.`is`("openid profile")) } @Test - public void shouldSerializeCredentials() { - Date expiresAt = new Date(CredentialsMock.CURRENT_TIME_MS + 123456 * 1000); - final String expectedExpiresAt = GsonProvider.formatDate(expiresAt); - - final Credentials expiresInCredentials = new CredentialsMock("id", "access", "ty", "refresh", 123456L); - final String expiresInJson = gson.toJson(expiresInCredentials); - assertThat(expiresInJson, containsString("\"id_token\":\"id\"")); - assertThat(expiresInJson, containsString("\"access_token\":\"access\"")); - assertThat(expiresInJson, containsString("\"token_type\":\"ty\"")); - assertThat(expiresInJson, containsString("\"refresh_token\":\"refresh\"")); - assertThat(expiresInJson, containsString("\"expires_in\":123456")); - assertThat(expiresInJson, containsString("\"expires_at\":\"" + expectedExpiresAt + "\"")); - assertThat(expiresInJson, not(containsString("\"scope\""))); - + public fun shouldSerializeCredentials() { + val expiresAt = Date(CredentialsMock.CURRENT_TIME_MS + 123456 * 1000) + val expectedExpiresAt = formatDate(expiresAt) + val expiresInCredentials: Credentials = + CredentialsMock("id", "access", "ty", "refresh", 123456L) + val expiresInJson = gson.toJson(expiresInCredentials) + MatcherAssert.assertThat(expiresInJson, CoreMatchers.containsString("\"id_token\":\"id\"")) + MatcherAssert.assertThat( + expiresInJson, + CoreMatchers.containsString("\"access_token\":\"access\"") + ) + MatcherAssert.assertThat( + expiresInJson, + CoreMatchers.containsString("\"token_type\":\"ty\"") + ) + MatcherAssert.assertThat( + expiresInJson, + CoreMatchers.containsString("\"refresh_token\":\"refresh\"") + ) + MatcherAssert.assertThat( + expiresInJson, + CoreMatchers.containsString("\"expires_in\":123456") + ) + MatcherAssert.assertThat( + expiresInJson, CoreMatchers.containsString( + "\"expires_at\":\"$expectedExpiresAt\"" + ) + ) + MatcherAssert.assertThat( + expiresInJson, + CoreMatchers.not(CoreMatchers.containsString("\"scope\"")) + ) + val expiresAtCredentials: Credentials = + CredentialsMock("id", "access", "ty", "refresh", expiresAt, "openid") + val expiresAtJson = gson.toJson(expiresAtCredentials) + MatcherAssert.assertThat(expiresAtJson, CoreMatchers.containsString("\"id_token\":\"id\"")) + MatcherAssert.assertThat( + expiresAtJson, + CoreMatchers.containsString("\"access_token\":\"access\"") + ) + MatcherAssert.assertThat( + expiresAtJson, + CoreMatchers.containsString("\"token_type\":\"ty\"") + ) + MatcherAssert.assertThat( + expiresAtJson, + CoreMatchers.containsString("\"refresh_token\":\"refresh\"") + ) + MatcherAssert.assertThat( + expiresAtJson, + CoreMatchers.containsString("\"expires_in\":123456") + ) + MatcherAssert.assertThat( + expiresInJson, CoreMatchers.containsString( + "\"expires_at\":\"$expectedExpiresAt\"" + ) + ) + MatcherAssert.assertThat(expiresAtJson, CoreMatchers.containsString("\"scope\":\"openid\"")) + } - final Credentials expiresAtCredentials = new CredentialsMock("id", "access", "ty", "refresh", expiresAt, "openid"); - final String expiresAtJson = gson.toJson(expiresAtCredentials); - assertThat(expiresAtJson, containsString("\"id_token\":\"id\"")); - assertThat(expiresAtJson, containsString("\"access_token\":\"access\"")); - assertThat(expiresAtJson, containsString("\"token_type\":\"ty\"")); - assertThat(expiresAtJson, containsString("\"refresh_token\":\"refresh\"")); - assertThat(expiresAtJson, containsString("\"expires_in\":123456")); - assertThat(expiresInJson, containsString("\"expires_at\":\"" + expectedExpiresAt + "\"")); - assertThat(expiresAtJson, containsString("\"scope\":\"openid\"")); + @Throws(IOException::class) + private fun buildCredentialsFrom(json: Reader): Credentials { + return pojoFrom(json, Credentials::class.java) } - private Credentials buildCredentialsFrom(Reader json) throws IOException { - return pojoFrom(json, Credentials.class); + private fun generateJSONWithExpiresAt(expiresAt: Date): String { + return """ + { + "access_token": "s6GS5FGJN2jfd4l6", + "token_type": "bearer", + "expires_in": 86000, + "expires_at": "${formatDate(expiresAt)}" + } + """.trimIndent() } - private String generateJSONWithExpiresAt(@NonNull Date expiresAt) { - return "{\n" + - "\"access_token\": \"s6GS5FGJN2jfd4l6\",\n" + - "\"token_type\": \"bearer\",\n" + - "\"expires_in\": 86000,\n" + - "\"expires_at\": \"" + GsonProvider.formatDate(expiresAt) + "\"\n" + - "}"; + private companion object { + private const val OPEN_ID_OFFLINE_ACCESS_CREDENTIALS = + "src/test/resources/credentials_openid_refresh_token.json" + private const val OPEN_ID_CREDENTIALS = "src/test/resources/credentials_openid.json" + private const val BASIC_CREDENTIALS = "src/test/resources/credentials.json" } -} +} \ No newline at end of file diff --git a/auth0/src/test/java/com/auth0/android/request/internal/GsonBaseTest.kt b/auth0/src/test/java/com/auth0/android/request/internal/GsonBaseTest.kt index 3061b6a55..fcfc6b3f1 100755 --- a/auth0/src/test/java/com/auth0/android/request/internal/GsonBaseTest.kt +++ b/auth0/src/test/java/com/auth0/android/request/internal/GsonBaseTest.kt @@ -1,31 +1,32 @@ -package com.auth0.android.request.internal; +package com.auth0.android.request.internal -import com.google.gson.Gson; -import com.google.gson.reflect.TypeToken; +import com.google.gson.Gson +import com.google.gson.reflect.TypeToken +import java.io.FileNotFoundException +import java.io.FileReader +import java.io.IOException +import java.io.Reader -import java.io.FileNotFoundException; -import java.io.FileReader; -import java.io.IOException; -import java.io.Reader; +public abstract class GsonBaseTest { + internal lateinit var gson: Gson -abstract class GsonBaseTest { - - static final String EMPTY_OBJECT = "src/test/resources/empty_object.json"; - static final String INVALID = "src/test/resources/invalid.json"; - - - Gson gson; - - T pojoFrom(Reader json, TypeToken typeToken) throws IOException { - return gson.getAdapter(typeToken).fromJson(json); + @Throws(IOException::class) + internal fun pojoFrom(json: Reader, typeToken: TypeToken): T { + return gson.getAdapter(typeToken).fromJson(json) } - T pojoFrom(Reader json, Class clazz) throws IOException { - return gson.getAdapter(clazz).fromJson(json); + @Throws(IOException::class) + internal fun pojoFrom(json: Reader, clazz: Class): T { + return gson.getAdapter(clazz).fromJson(json) } - FileReader json(String name) throws FileNotFoundException { - return new FileReader(name); + @Throws(FileNotFoundException::class) + internal fun json(name: String): FileReader { + return FileReader(name) } + internal companion object { + internal const val EMPTY_OBJECT = "src/test/resources/empty_object.json" + internal const val INVALID = "src/test/resources/invalid.json" + } } \ No newline at end of file diff --git a/auth0/src/test/java/com/auth0/android/request/internal/JwksGsonTest.kt b/auth0/src/test/java/com/auth0/android/request/internal/JwksGsonTest.kt index 7344c2889..d9715c742 100755 --- a/auth0/src/test/java/com/auth0/android/request/internal/JwksGsonTest.kt +++ b/auth0/src/test/java/com/auth0/android/request/internal/JwksGsonTest.kt @@ -1,109 +1,125 @@ -package com.auth0.android.request.internal; - -import com.google.gson.JsonParseException; -import com.google.gson.reflect.TypeToken; - -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; -import org.junit.runner.RunWith; -import org.robolectric.RobolectricTestRunner; - -import java.io.IOException; -import java.io.Reader; -import java.io.StringReader; -import java.math.BigInteger; -import java.security.PublicKey; -import java.security.interfaces.RSAPublicKey; -import java.util.Map; - -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.instanceOf; -import static org.hamcrest.Matchers.is; -import static org.hamcrest.Matchers.notNullValue; -import static org.junit.Assert.assertTrue; - -@RunWith(RobolectricTestRunner.class) -public class JwksGsonTest extends GsonBaseTest { - private static final String VALID_RSA_JWKS = "src/test/resources/rsa_jwks.json"; - private static final String EXPECTED_KEY_ID = "key123"; - private static final String EXPECTED_RSA_EXPONENT = "65537"; - private static final String EXPECTED_RSA_MODULUS = "2327856100899355911632462598898247024131242" + - "69568893466584055046785206443536944170967694954399904576260402148130300731927741648861" + - "77036082957412916823253078715836599659671998742580694113788009114660385412566349874736" + - "27869308481943996880794168096537223920950531497564162778062893250580915368070350845084" + - "20860279004024750131874921675175697075713453754160892451823567877023128161490580261931" + - "58312146038158019813447205810433184619008248223295213470806341823186239417071266118809" + - "63334488448657815599232564013868981211014327205461460864291477265210472076542261630382" + - "8138891725285516030216809064067106806135514473091101324387"; - - @Rule - public ExpectedException expectedException = ExpectedException.none(); - +package com.auth0.android.request.internal + +import com.google.gson.JsonParseException +import com.google.gson.reflect.TypeToken +import org.hamcrest.MatcherAssert +import org.hamcrest.Matchers +import org.junit.Assert +import org.junit.Before +import org.junit.Test +import org.junit.runner.RunWith +import org.robolectric.RobolectricTestRunner +import java.io.IOException +import java.io.Reader +import java.io.StringReader +import java.math.BigInteger +import java.security.PublicKey +import java.security.interfaces.RSAPublicKey + +@RunWith(RobolectricTestRunner::class) +public class JwksGsonTest : GsonBaseTest() { @Before - public void setUp() { - gson = GsonProvider.buildGson(); + public fun setUp() { + gson = GsonProvider.gson } @Test - public void shouldFailWithInvalidJson() throws Exception { - expectedException.expect(JsonParseException.class); - buildJwksFrom(json(INVALID)); + @Throws(Exception::class) + public fun shouldFailWithInvalidJson() { + Assert.assertThrows(JsonParseException::class.java) { + buildJwksFrom(json(INVALID)) + } } @Test - public void shouldFailWithEmptyJson() throws Exception { - expectedException.expect(JsonParseException.class); - buildJwksFrom(json(EMPTY_OBJECT)); + @Throws(Exception::class) + public fun shouldFailWithEmptyJson() { + Assert.assertThrows(JsonParseException::class.java) { + buildJwksFrom(json(EMPTY_OBJECT)) + } } @Test - public void shouldReturnValid() throws Exception { - Map jwks = buildJwksFrom(json(VALID_RSA_JWKS)); - assertThat(jwks, is(notNullValue())); - assertThat(jwks.size(), is(1)); - assertTrue(jwks.containsKey(EXPECTED_KEY_ID)); - PublicKey pub = jwks.get(EXPECTED_KEY_ID); - assertThat(pub, instanceOf(RSAPublicKey.class)); - - RSAPublicKey rsaPub = (RSAPublicKey) pub; - assertThat(rsaPub.getPublicExponent(), is(new BigInteger(EXPECTED_RSA_EXPONENT))); - assertThat(rsaPub.getModulus(), is(new BigInteger(EXPECTED_RSA_MODULUS))); + @Throws(Exception::class) + public fun shouldReturnValid() { + val jwks = buildJwksFrom(json(VALID_RSA_JWKS)) + MatcherAssert.assertThat(jwks, Matchers.`is`(Matchers.notNullValue())) + MatcherAssert.assertThat(jwks.size, Matchers.`is`(1)) + Assert.assertTrue(jwks.containsKey(EXPECTED_KEY_ID)) + val pub = jwks[EXPECTED_KEY_ID] + MatcherAssert.assertThat( + pub, Matchers.instanceOf( + RSAPublicKey::class.java + ) + ) + val rsaPub = pub as RSAPublicKey? + MatcherAssert.assertThat( + rsaPub!!.publicExponent, Matchers.`is`( + BigInteger( + EXPECTED_RSA_EXPONENT + ) + ) + ) + MatcherAssert.assertThat(rsaPub.modulus, Matchers.`is`(BigInteger(EXPECTED_RSA_MODULUS))) } @Test - public void shouldReturnEmptyWhenKeysAreEmpty() throws Exception { - Map jwks = buildJwksFrom(new StringReader("{\"keys\": []}")); - assertThat(jwks, is(notNullValue())); - assertTrue(jwks.isEmpty()); + @Throws(Exception::class) + public fun shouldReturnEmptyWhenKeysAreEmpty() { + val jwks = buildJwksFrom(StringReader("{\"keys\": []}")) + MatcherAssert.assertThat(jwks, Matchers.`is`(Matchers.notNullValue())) + Assert.assertTrue(jwks.isEmpty()) } @Test - public void shouldReturnEmptyWhenKeysAreFromDifferentAlgorithm() throws Exception { - Map jwks = buildJwksFrom(new StringReader("{\"keys\": [{\"alg\": \"RS512\", \"use\": \"sig\"}]}")); - assertThat(jwks, is(notNullValue())); - assertTrue(jwks.isEmpty()); + @Throws(Exception::class) + public fun shouldReturnEmptyWhenKeysAreFromDifferentAlgorithm() { + val jwks = + buildJwksFrom(StringReader("{\"keys\": [{\"alg\": \"RS512\", \"use\": \"sig\"}]}")) + MatcherAssert.assertThat(jwks, Matchers.`is`(Matchers.notNullValue())) + Assert.assertTrue(jwks.isEmpty()) } @Test - public void shouldReturnEmptyWhenKeysAreNotForSignatureChecking() throws Exception { - Map jwks = buildJwksFrom(new StringReader("{\"keys\": [{\"alg\": \"RS256\", \"use\": \"enc\"}]}")); - assertThat(jwks, is(notNullValue())); - assertTrue(jwks.isEmpty()); + @Throws(Exception::class) + public fun shouldReturnEmptyWhenKeysAreNotForSignatureChecking() { + val jwks = + buildJwksFrom(StringReader("{\"keys\": [{\"alg\": \"RS256\", \"use\": \"enc\"}]}")) + MatcherAssert.assertThat(jwks, Matchers.`is`(Matchers.notNullValue())) + Assert.assertTrue(jwks.isEmpty()) } @Test - public void shouldReturnEmptyWhenKeysCannotBeCreatedBecauseOfNotSupportedKeyType() throws Exception { - Map jwks = buildJwksFrom(new StringReader("{\"keys\": [{\"alg\": \"RS256\", \"use\": \"sig\", \"kty\": \"INVALID_VALUE\"}]}")); - assertThat(jwks, is(notNullValue())); - assertTrue(jwks.isEmpty()); + @Throws(Exception::class) + public fun shouldReturnEmptyWhenKeysCannotBeCreatedBecauseOfNotSupportedKeyType() { + val jwks = + buildJwksFrom(StringReader("{\"keys\": [{\"alg\": \"RS256\", \"use\": \"sig\", \"kty\": \"INVALID_VALUE\"}]}")) + MatcherAssert.assertThat(jwks, Matchers.`is`(Matchers.notNullValue())) + Assert.assertTrue(jwks.isEmpty()) } - private Map buildJwksFrom(Reader json) throws IOException { - TypeToken> jwksType = new TypeToken>() { - }; - return pojoFrom(json, jwksType); + @Throws(IOException::class) + private fun buildJwksFrom(json: Reader): Map { + @Suppress("UNCHECKED_CAST") val jwksType: TypeToken> = + TypeToken.getParameterized( + Map::class.java, + String::class.java, + PublicKey::class.java + ) as TypeToken> + return pojoFrom(json, jwksType) } -} + private companion object { + private const val VALID_RSA_JWKS = "src/test/resources/rsa_jwks.json" + private const val EXPECTED_KEY_ID = "key123" + private const val EXPECTED_RSA_EXPONENT = "65537" + private const val EXPECTED_RSA_MODULUS = "2327856100899355911632462598898247024131242" + + "69568893466584055046785206443536944170967694954399904576260402148130300731927741648861" + + "77036082957412916823253078715836599659671998742580694113788009114660385412566349874736" + + "27869308481943996880794168096537223920950531497564162778062893250580915368070350845084" + + "20860279004024750131874921675175697075713453754160892451823567877023128161490580261931" + + "58312146038158019813447205810433184619008248223295213470806341823186239417071266118809" + + "63334488448657815599232564013868981211014327205461460864291477265210472076542261630382" + + "8138891725285516030216809064067106806135514473091101324387" + } +} \ No newline at end of file diff --git a/auth0/src/test/java/com/auth0/android/request/internal/UserIdentityGsonTest.kt b/auth0/src/test/java/com/auth0/android/request/internal/UserIdentityGsonTest.kt index 2fa17a1f0..780ca77f7 100755 --- a/auth0/src/test/java/com/auth0/android/request/internal/UserIdentityGsonTest.kt +++ b/auth0/src/test/java/com/auth0/android/request/internal/UserIdentityGsonTest.kt @@ -1,63 +1,84 @@ -package com.auth0.android.request.internal; +package com.auth0.android.request.internal -import com.auth0.android.result.UserIdentity; -import com.google.gson.JsonParseException; +import com.auth0.android.result.UserIdentity +import com.auth0.android.util.UserIdentityMatcher +import com.google.gson.JsonParseException +import org.hamcrest.MatcherAssert +import org.hamcrest.Matchers +import org.hamcrest.collection.IsMapWithSize +import org.junit.Assert +import org.junit.Before +import org.junit.Test -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; - -import static com.auth0.android.util.UserIdentityMatcher.isUserIdentity; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.hasEntry; -import static org.hamcrest.Matchers.is; -import static org.hamcrest.Matchers.nullValue; -import static org.hamcrest.collection.IsMapWithSize.anEmptyMap; - -public class UserIdentityGsonTest extends GsonBaseTest { - - private static final String AUTH0 = "src/test/resources/identity_auth0.json"; - private static final String FACEBOOK = "src/test/resources/identity_facebook.json"; - - @Rule - public ExpectedException expectedException = ExpectedException.none(); +public class UserIdentityGsonTest : GsonBaseTest() { @Before - public void setUp() { - gson = GsonProvider.buildGson(); + public fun setUp() { + gson = GsonProvider.gson } @Test - public void shouldFailWithInvalidJson() throws Exception { - expectedException.expect(JsonParseException.class); - pojoFrom(json(INVALID), UserIdentity.class); + @Throws(Exception::class) + public fun shouldFailWithInvalidJson() { + Assert.assertThrows(JsonParseException::class.java) { + pojoFrom(json(INVALID), UserIdentity::class.java) + } } @Test - public void shouldFailWithEmptyJson() throws Exception { - expectedException.expect(JsonParseException.class); - pojoFrom(json(EMPTY_OBJECT), UserIdentity.class); + @Throws(Exception::class) + public fun shouldFailWithEmptyJson() { + Assert.assertThrows(JsonParseException::class.java) { + pojoFrom(json(EMPTY_OBJECT), UserIdentity::class.java) + } } @Test - public void shouldBuildBasic() throws Exception { - UserIdentity identity = pojoFrom(json(AUTH0), UserIdentity.class); - assertThat(identity, isUserIdentity("1234567890", "auth0", "Username-Password-Authentication")); - assertThat(identity.getProfileInfo(), anEmptyMap()); - assertThat(identity.isSocial(), is(false)); - assertThat(identity.getAccessToken(), nullValue()); - assertThat(identity.getAccessTokenSecret(), nullValue()); + @Throws(Exception::class) + public fun shouldBuildBasic() { + val identity = pojoFrom(json(AUTH0), UserIdentity::class.java) + MatcherAssert.assertThat( + identity, + UserIdentityMatcher.isUserIdentity( + "1234567890", + "auth0", + "Username-Password-Authentication" + ) + ) + MatcherAssert.assertThat(identity.getProfileInfo(), IsMapWithSize.anEmptyMap()) + MatcherAssert.assertThat(identity.isSocial, Matchers.`is`(false)) + MatcherAssert.assertThat(identity.accessToken, Matchers.nullValue()) + MatcherAssert.assertThat(identity.accessTokenSecret, Matchers.nullValue()) } @Test - public void shouldBuildWithExtraValues() throws Exception { - UserIdentity identity = pojoFrom(json(FACEBOOK), UserIdentity.class); - assertThat(identity, isUserIdentity("999997950999976", "facebook", "facebook")); - assertThat(identity.getProfileInfo(), hasEntry("given_name", (Object) "John")); - assertThat(identity.getProfileInfo(), hasEntry("family_name", (Object) "Foobar")); - assertThat(identity.getProfileInfo(), hasEntry("email_verified", (Object) true)); - assertThat(identity.getProfileInfo(), hasEntry("gender", (Object) "male")); + @Throws(Exception::class) + public fun shouldBuildWithExtraValues() { + val identity = pojoFrom(json(FACEBOOK), UserIdentity::class.java) + MatcherAssert.assertThat( + identity, + UserIdentityMatcher.isUserIdentity("999997950999976", "facebook", "facebook") + ) + MatcherAssert.assertThat( + identity.getProfileInfo(), + Matchers.hasEntry("given_name", "John" as Any) + ) + MatcherAssert.assertThat( + identity.getProfileInfo(), + Matchers.hasEntry("family_name", "Foobar" as Any) + ) + MatcherAssert.assertThat( + identity.getProfileInfo(), + Matchers.hasEntry("email_verified", true as Any) + ) + MatcherAssert.assertThat( + identity.getProfileInfo(), + Matchers.hasEntry("gender", "male" as Any) + ) } -} + private companion object { + private const val AUTH0 = "src/test/resources/identity_auth0.json" + private const val FACEBOOK = "src/test/resources/identity_facebook.json" + } +} \ No newline at end of file diff --git a/auth0/src/test/java/com/auth0/android/request/internal/UserProfileGsonTest.kt b/auth0/src/test/java/com/auth0/android/request/internal/UserProfileGsonTest.kt index 35e55849d..aa4853fe6 100755 --- a/auth0/src/test/java/com/auth0/android/request/internal/UserProfileGsonTest.kt +++ b/auth0/src/test/java/com/auth0/android/request/internal/UserProfileGsonTest.kt @@ -1,220 +1,334 @@ -package com.auth0.android.request.internal; - -import com.auth0.android.result.UserIdentity; -import com.auth0.android.result.UserProfile; -import com.google.gson.JsonParseException; - -import org.hamcrest.Matcher; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; - -import java.io.StringReader; -import java.text.SimpleDateFormat; -import java.util.Collections; -import java.util.Locale; - -import static com.auth0.android.util.UserIdentityMatcher.isUserIdentity; -import static com.auth0.android.util.UserProfileMatcher.isNormalizedProfile; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.anyOf; -import static org.hamcrest.Matchers.emptyCollectionOf; -import static org.hamcrest.Matchers.equalTo; -import static org.hamcrest.Matchers.hasEntry; -import static org.hamcrest.Matchers.hasItem; -import static org.hamcrest.Matchers.hasKey; -import static org.hamcrest.Matchers.hasSize; -import static org.hamcrest.Matchers.is; -import static org.hamcrest.Matchers.not; -import static org.hamcrest.Matchers.notNullValue; -import static org.hamcrest.Matchers.nullValue; -import static org.hamcrest.collection.IsMapWithSize.aMapWithSize; -import static org.hamcrest.collection.IsMapWithSize.anEmptyMap; - -public class UserProfileGsonTest extends GsonBaseTest { - private static final String NICKNAME = "a0"; - private static final String NAME = "info @ auth0"; - private static final String ID = "auth0|1234567890"; - private static final String PROFILE_OAUTH = "src/test/resources/profile_oauth.json"; - private static final String PROFILE_FULL = "src/test/resources/profile_full.json"; - private static final String PROFILE_BASIC = "src/test/resources/profile_basic.json"; - private static final String PROFILE = "src/test/resources/profile.json"; - - @Rule - public ExpectedException expectedException = ExpectedException.none(); +package com.auth0.android.request.internal + +import com.auth0.android.result.UserIdentity +import com.auth0.android.result.UserProfile +import com.auth0.android.util.UserIdentityMatcher +import com.auth0.android.util.UserProfileMatcher +import com.google.gson.JsonParseException +import org.hamcrest.MatcherAssert +import org.hamcrest.MatcherAssert.assertThat +import org.hamcrest.Matchers +import org.hamcrest.Matchers.* +import org.hamcrest.collection.IsMapWithSize +import org.junit.Assert +import org.junit.Before +import org.junit.Test +import java.io.StringReader +import java.text.SimpleDateFormat +import java.util.* + +public class UserProfileGsonTest : GsonBaseTest() { @Before - public void setUp() { - gson = GsonProvider.buildGson(); + public fun setUp() { + gson = GsonProvider.gson } @Test - public void shouldFailWithInvalidJson() throws Exception { - expectedException.expect(JsonParseException.class); - pojoFrom(json(INVALID), UserProfile.class); + @Throws(Exception::class) + public fun shouldFailWithInvalidJson() { + Assert.assertThrows(JsonParseException::class.java) { + pojoFrom(json(INVALID), UserProfile::class.java) + } } @Test - public void shouldFailWithEmptyJson() throws Exception { - expectedException.expect(JsonParseException.class); - pojoFrom(json(EMPTY_OBJECT), UserProfile.class); + @Throws(Exception::class) + public fun shouldFailWithEmptyJson() { + Assert.assertThrows(JsonParseException::class.java) { + pojoFrom(json(EMPTY_OBJECT), UserProfile::class.java) + } } @Test - public void shouldNotRequireUserId() throws Exception { - UserProfile userProfile = pojoFrom(new StringReader("{\n" + - " \"picture\": \"https://secure.gravatar.com/avatar/cfacbe113a96fdfc85134534771d88b4?s=480&r=pg&d=https%3A%2F%2Fssl.gstatic.com%2Fs2%2Fprofiles%2Fimages%2Fsilhouette80.png\",\n" + - " \"name\": \"info @ auth0\",\n" + - " \"nickname\": \"a0\",\n" + - " \"identities\": [\n" + - " {\n" + - " \"user_id\": \"1234567890\",\n" + - " \"provider\": \"auth0\",\n" + - " \"connection\": \"Username-Password-Authentication\",\n" + - " \"isSocial\": false\n" + - " }\n" + - " ],\n" + - " \"created_at\": \"2014-07-06T18:33:49.005Z\"\n" + - "}" - ), UserProfile.class); - assertThat(userProfile, is(notNullValue())); + @Throws(Exception::class) + public fun shouldNotRequireUserId() { + val userProfile = pojoFrom( + StringReader( + """{ + "picture": "https://secure.gravatar.com/avatar/cfacbe113a96fdfc85134534771d88b4?s=480&r=pg&d=https%3A%2F%2Fssl.gstatic.com%2Fs2%2Fprofiles%2Fimages%2Fsilhouette80.png", + "name": "info @ auth0", + "nickname": "a0", + "identities": [ + { + "user_id": "1234567890", + "provider": "auth0", + "connection": "Username-Password-Authentication", + "isSocial": false + } + ], + "created_at": "2014-07-06T18:33:49.005Z" +}""" + ), UserProfile::class.java + ) + MatcherAssert.assertThat(userProfile, Matchers.`is`(Matchers.notNullValue())) } @Test - public void shouldNotRequireName() throws Exception { - UserProfile userProfile = pojoFrom(new StringReader("{\n" + - " \"picture\": \"https://secure.gravatar.com/avatar/cfacbe113a96fdfc85134534771d88b4?s=480&r=pg&d=https%3A%2F%2Fssl.gstatic.com%2Fs2%2Fprofiles%2Fimages%2Fsilhouette80.png\",\n" + - " \"nickname\": \"a0\",\n" + - " \"user_id\": \"auth0|1234567890\",\n" + - " \"identities\": [\n" + - " {\n" + - " \"user_id\": \"1234567890\",\n" + - " \"provider\": \"auth0\",\n" + - " \"connection\": \"Username-Password-Authentication\",\n" + - " \"isSocial\": false\n" + - " }\n" + - " ],\n" + - " \"created_at\": \"2014-07-06T18:33:49.005Z\"\n" + - "}" - ), UserProfile.class); - assertThat(userProfile, is(notNullValue())); + @Throws(Exception::class) + public fun shouldNotRequireName() { + val userProfile = pojoFrom( + StringReader( + """{ + "picture": "https://secure.gravatar.com/avatar/cfacbe113a96fdfc85134534771d88b4?s=480&r=pg&d=https%3A%2F%2Fssl.gstatic.com%2Fs2%2Fprofiles%2Fimages%2Fsilhouette80.png", + "nickname": "a0", + "user_id": "auth0|1234567890", + "identities": [ + { + "user_id": "1234567890", + "provider": "auth0", + "connection": "Username-Password-Authentication", + "isSocial": false + } + ], + "created_at": "2014-07-06T18:33:49.005Z" +}""" + ), UserProfile::class.java + ) + MatcherAssert.assertThat(userProfile, Matchers.`is`(Matchers.notNullValue())) } @Test - public void shouldNotRequireNickname() throws Exception { - UserProfile userProfile = pojoFrom(new StringReader("{\n" + - " \"picture\": \"https://secure.gravatar.com/avatar/cfacbe113a96fdfc85134534771d88b4?s=480&r=pg&d=https%3A%2F%2Fssl.gstatic.com%2Fs2%2Fprofiles%2Fimages%2Fsilhouette80.png\",\n" + - " \"name\": \"info @ auth0\",\n" + - " \"user_id\": \"auth0|1234567890\",\n" + - " \"identities\": [\n" + - " {\n" + - " \"user_id\": \"1234567890\",\n" + - " \"provider\": \"auth0\",\n" + - " \"connection\": \"Username-Password-Authentication\",\n" + - " \"isSocial\": false\n" + - " }\n" + - " ],\n" + - " \"created_at\": \"2014-07-06T18:33:49.005Z\"\n" + - "}" - ), UserProfile.class); - assertThat(userProfile, is(notNullValue())); + @Throws(Exception::class) + public fun shouldNotRequireNickname() { + val userProfile = pojoFrom( + StringReader( + """{ + "picture": "https://secure.gravatar.com/avatar/cfacbe113a96fdfc85134534771d88b4?s=480&r=pg&d=https%3A%2F%2Fssl.gstatic.com%2Fs2%2Fprofiles%2Fimages%2Fsilhouette80.png", + "name": "info @ auth0", + "user_id": "auth0|1234567890", + "identities": [ + { + "user_id": "1234567890", + "provider": "auth0", + "connection": "Username-Password-Authentication", + "isSocial": false + } + ], + "created_at": "2014-07-06T18:33:49.005Z" +}""" + ), UserProfile::class.java + ) + MatcherAssert.assertThat(userProfile, Matchers.`is`(Matchers.notNullValue())) } @Test - public void shouldNotRequirePicture() throws Exception { - UserProfile userProfile = pojoFrom(new StringReader("{\n" + - " \"name\": \"info @ auth0\",\n" + - " \"nickname\": \"a0\",\n" + - " \"user_id\": \"auth0|1234567890\",\n" + - " \"identities\": [\n" + - " {\n" + - " \"user_id\": \"1234567890\",\n" + - " \"provider\": \"auth0\",\n" + - " \"connection\": \"Username-Password-Authentication\",\n" + - " \"isSocial\": false\n" + - " }\n" + - " ],\n" + - " \"created_at\": \"2014-07-06T18:33:49.005Z\"\n" + - "}" - ), UserProfile.class); - assertThat(userProfile, is(notNullValue())); + @Throws(Exception::class) + public fun shouldNotRequirePicture() { + val userProfile = pojoFrom( + StringReader( + """{ + "name": "info @ auth0", + "nickname": "a0", + "user_id": "auth0|1234567890", + "identities": [ + { + "user_id": "1234567890", + "provider": "auth0", + "connection": "Username-Password-Authentication", + "isSocial": false + } + ], + "created_at": "2014-07-06T18:33:49.005Z" +}""" + ), UserProfile::class.java + ) + MatcherAssert.assertThat(userProfile, Matchers.`is`(Matchers.notNullValue())) } @Test - public void shouldReturnOAuthProfile() throws Exception { - UserProfile profile = pojoFrom(json(PROFILE_OAUTH), UserProfile.class); - assertThat(profile.getId(), is("google-oauth2|9883254263433883220")); - assertThat(profile.getName(), is(nullValue())); - assertThat(profile.getNickname(), is(nullValue())); - assertThat(profile.getPictureURL(), is(nullValue())); - assertThat(profile.getIdentities(), is(emptyCollectionOf(UserIdentity.class))); - assertThat(profile.getUserMetadata(), anEmptyMap()); - assertThat(profile.getAppMetadata(), anEmptyMap()); - assertThat(profile.getExtraInfo(), aMapWithSize(1)); - assertThat(profile.getExtraInfo(), hasEntry("sub", (Object) "google-oauth2|9883254263433883220")); + @Throws(Exception::class) + public fun shouldReturnOAuthProfile() { + val profile = pojoFrom(json(PROFILE_OAUTH), UserProfile::class.java) + MatcherAssert.assertThat( + profile.getId(), + Matchers.`is`("google-oauth2|9883254263433883220") + ) + MatcherAssert.assertThat(profile.name, Matchers.`is`(Matchers.nullValue())) + MatcherAssert.assertThat(profile.nickname, Matchers.`is`(Matchers.nullValue())) + MatcherAssert.assertThat(profile.pictureURL, Matchers.`is`(Matchers.nullValue())) + MatcherAssert.assertThat( + profile.getIdentities(), Matchers.`is`( + Matchers.emptyCollectionOf( + UserIdentity::class.java + ) + ) + ) + MatcherAssert.assertThat(profile.getUserMetadata(), IsMapWithSize.anEmptyMap()) + MatcherAssert.assertThat(profile.getAppMetadata(), IsMapWithSize.anEmptyMap()) + MatcherAssert.assertThat(profile.getExtraInfo(), IsMapWithSize.aMapWithSize(1)) + MatcherAssert.assertThat( + profile.getExtraInfo(), + Matchers.hasEntry("sub", "google-oauth2|9883254263433883220" as Any) + ) } @Test - public void shouldReturnProfileWithOnlyRequiredValues() throws Exception { - UserProfile profile = pojoFrom(json(PROFILE_BASIC), UserProfile.class); - assertThat(profile, isNormalizedProfile(ID, NAME, NICKNAME)); - assertThat(profile.getIdentities(), hasSize(1)); - assertThat(profile.getIdentities(), hasItem(isUserIdentity("1234567890", "auth0", "Username-Password-Authentication"))); - assertThat(profile.getUserMetadata(), anEmptyMap()); - assertThat(profile.getAppMetadata(), anEmptyMap()); - assertThat(profile.getExtraInfo(), anEmptyMap()); + @Throws(Exception::class) + public fun shouldReturnProfileWithOnlyRequiredValues() { + val profile = pojoFrom(json(PROFILE_BASIC), UserProfile::class.java) + MatcherAssert.assertThat( + profile, + UserProfileMatcher.isNormalizedProfile(ID, NAME, NICKNAME) + ) + MatcherAssert.assertThat(profile.getIdentities(), Matchers.hasSize(1)) + MatcherAssert.assertThat( + profile.getIdentities(), + Matchers.hasItem( + UserIdentityMatcher.isUserIdentity( + "1234567890", + "auth0", + "Username-Password-Authentication" + ) + ) + ) + MatcherAssert.assertThat(profile.getUserMetadata(), IsMapWithSize.anEmptyMap()) + MatcherAssert.assertThat(profile.getAppMetadata(), IsMapWithSize.anEmptyMap()) + MatcherAssert.assertThat(profile.getExtraInfo(), IsMapWithSize.anEmptyMap()) } @Test - public void shouldReturnNormalizedProfile() throws Exception { - UserProfile profile = pojoFrom(json(PROFILE), UserProfile.class); - assertThat(profile, isNormalizedProfile(ID, NAME, NICKNAME)); - assertThat(profile.getIdentities(), hasSize(1)); - assertThat(profile.getIdentities(), hasItem(isUserIdentity("1234567890", "auth0", "Username-Password-Authentication"))); - assertThat(profile.getUserMetadata(), anEmptyMap()); - assertThat(profile.getAppMetadata(), anEmptyMap()); - assertThat(profile.getExtraInfo(), notNullValue()); + @Throws(Exception::class) + public fun shouldReturnNormalizedProfile() { + val profile = pojoFrom(json(PROFILE), UserProfile::class.java) + MatcherAssert.assertThat( + profile, + UserProfileMatcher.isNormalizedProfile(ID, NAME, NICKNAME) + ) + MatcherAssert.assertThat(profile.getIdentities(), Matchers.hasSize(1)) + MatcherAssert.assertThat( + profile.getIdentities(), + Matchers.hasItem( + UserIdentityMatcher.isUserIdentity( + "1234567890", + "auth0", + "Username-Password-Authentication" + ) + ) + ) + MatcherAssert.assertThat(profile.getUserMetadata(), IsMapWithSize.anEmptyMap()) + MatcherAssert.assertThat(profile.getAppMetadata(), IsMapWithSize.anEmptyMap()) + MatcherAssert.assertThat(profile.getExtraInfo(), Matchers.notNullValue()) } @Test - public void shouldReturnProfileWithOptionalFields() throws Exception { - UserProfile profile = pojoFrom(json(PROFILE_FULL), UserProfile.class); - assertThat(profile, isNormalizedProfile(ID, NAME, NICKNAME)); - assertThat(profile.getEmail(), equalTo("info@auth0.com")); - assertThat(profile.getGivenName(), equalTo("John")); - assertThat(profile.getFamilyName(), equalTo("Foobar")); - assertThat(profile.isEmailVerified(), is(false)); - assertThat(profile.getCreatedAt(), equalTo(new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", Locale.US).parse("2014-07-06T18:33:49.005Z"))); + @Throws(Exception::class) + public fun shouldReturnProfileWithOptionalFields() { + val profile = pojoFrom(json(PROFILE_FULL), UserProfile::class.java) + MatcherAssert.assertThat( + profile, + UserProfileMatcher.isNormalizedProfile(ID, NAME, NICKNAME) + ) + MatcherAssert.assertThat(profile.email, Matchers.equalTo("info@auth0.com")) + MatcherAssert.assertThat(profile.givenName, Matchers.equalTo("John")) + MatcherAssert.assertThat(profile.familyName, Matchers.equalTo("Foobar")) + MatcherAssert.assertThat(profile.isEmailVerified, Matchers.`is`(false)) + MatcherAssert.assertThat( + profile.createdAt, + Matchers.equalTo( + SimpleDateFormat( + "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", + Locale.US + ).parse("2014-07-06T18:33:49.005Z") + ) + ) } @Test - public void shouldReturnProfileWithMultipleIdentities() throws Exception { - UserProfile profile = pojoFrom(json(PROFILE_FULL), UserProfile.class); - assertThat(profile, isNormalizedProfile(ID, NAME, NICKNAME)); - assertThat(profile.getIdentities(), hasItem(isUserIdentity("1234567890", "auth0", "Username-Password-Authentication"))); - assertThat(profile.getIdentities(), hasItem(isUserIdentity("999997950999976", "facebook", "facebook"))); + @Throws(Exception::class) + public fun shouldReturnProfileWithMultipleIdentities() { + val profile = pojoFrom(json(PROFILE_FULL), UserProfile::class.java) + MatcherAssert.assertThat( + profile, + UserProfileMatcher.isNormalizedProfile(ID, NAME, NICKNAME) + ) + MatcherAssert.assertThat( + profile.getIdentities(), + Matchers.hasItem( + UserIdentityMatcher.isUserIdentity( + "1234567890", + "auth0", + "Username-Password-Authentication" + ) + ) + ) + MatcherAssert.assertThat( + profile.getIdentities(), + Matchers.hasItem( + UserIdentityMatcher.isUserIdentity( + "999997950999976", + "facebook", + "facebook" + ) + ) + ) } @Test - public void shouldReturnProfileWithExtraInfo() throws Exception { - UserProfile profile = pojoFrom(json(PROFILE_FULL), UserProfile.class); - assertThat(profile, isNormalizedProfile(ID, NAME, NICKNAME)); - assertThat(profile.getExtraInfo(), hasEntry("multifactor", (Object) Collections.singletonList("google-authenticator"))); - assertThat(profile.getExtraInfo(), not(anyOf(new Matcher[]{hasKey("user_id"), hasKey("name"), hasKey("nickname"), hasKey("picture"), hasKey("email"), hasKey("created_at")}))); - assertThat(profile.getExtraInfo(), not(anyOf(new Matcher[]{hasKey("identities"), hasKey("user_metadata"), hasKey("app_metadata")}))); + @Throws(Exception::class) + public fun shouldReturnProfileWithExtraInfo() { + val profile = pojoFrom(json(PROFILE_FULL), UserProfile::class.java) + MatcherAssert.assertThat( + profile, + UserProfileMatcher.isNormalizedProfile(ID, NAME, NICKNAME) + ) + MatcherAssert.assertThat( + profile.getExtraInfo(), + Matchers.hasEntry("multifactor", listOf("google-authenticator")) + ) + assertThat( + profile.getExtraInfo(), + not( + anyOf( + hasKey("user_id"), + hasKey("name"), + hasKey("nickname"), + hasKey("picture"), + hasKey("email"), + hasKey("created_at") + ) + ) + ) } @Test - public void shouldReturnProfileWithMetadata() throws Exception { - UserProfile profile = pojoFrom(json(PROFILE_FULL), UserProfile.class); - assertThat(profile, isNormalizedProfile(ID, NAME, NICKNAME)); - assertThat(profile.getUserMetadata(), hasEntry("first_name", (Object) "Info")); - assertThat(profile.getUserMetadata(), hasEntry("last_name", (Object) "Auth0")); - assertThat(profile.getUserMetadata(), hasEntry("first_name", (Object) "Info")); - assertThat(profile.getAppMetadata(), hasEntry("role", (Object) "admin")); - assertThat(profile.getAppMetadata(), hasEntry("tier", (Object) 2.0)); - assertThat(profile.getAppMetadata(), hasEntry("blocked", (Object) false)); - } - -} + @Throws(Exception::class) + public fun shouldReturnProfileWithMetadata() { + val profile = pojoFrom(json(PROFILE_FULL), UserProfile::class.java) + MatcherAssert.assertThat( + profile, + UserProfileMatcher.isNormalizedProfile(ID, NAME, NICKNAME) + ) + MatcherAssert.assertThat( + profile.getUserMetadata(), + Matchers.hasEntry("first_name", "Info" as Any) + ) + MatcherAssert.assertThat( + profile.getUserMetadata(), + Matchers.hasEntry("last_name", "Auth0" as Any) + ) + MatcherAssert.assertThat( + profile.getUserMetadata(), + Matchers.hasEntry("first_name", "Info" as Any) + ) + MatcherAssert.assertThat( + profile.getAppMetadata(), + Matchers.hasEntry("role", "admin" as Any) + ) + MatcherAssert.assertThat(profile.getAppMetadata(), Matchers.hasEntry("tier", 2.0 as Any)) + MatcherAssert.assertThat( + profile.getAppMetadata(), + Matchers.hasEntry("blocked", false as Any) + ) + } + + private companion object { + private const val NICKNAME = "a0" + private const val NAME = "info @ auth0" + private const val ID = "auth0|1234567890" + private const val PROFILE_OAUTH = "src/test/resources/profile_oauth.json" + private const val PROFILE_FULL = "src/test/resources/profile_full.json" + private const val PROFILE_BASIC = "src/test/resources/profile_basic.json" + private const val PROFILE = "src/test/resources/profile.json" + } +} \ No newline at end of file From 21bcfafbe72ff5e81fc33b77c5e6ceeb1be08474 Mon Sep 17 00:00:00 2001 From: Luciano Balmaceda Date: Thu, 14 Jan 2021 17:47:34 +0100 Subject: [PATCH 5/5] Fix leftover usages of Gson() --- .../auth0/android/authentication/AuthenticationAPIClient.kt | 2 +- .../main/java/com/auth0/android/management/UsersAPIClient.kt | 2 +- auth0/src/main/java/com/auth0/android/util/Auth0UserAgent.kt | 4 ++-- 3 files changed, 4 insertions(+), 4 deletions(-) diff --git a/auth0/src/main/java/com/auth0/android/authentication/AuthenticationAPIClient.kt b/auth0/src/main/java/com/auth0/android/authentication/AuthenticationAPIClient.kt index 72db84907..523f6d999 100755 --- a/auth0/src/main/java/com/auth0/android/authentication/AuthenticationAPIClient.kt +++ b/auth0/src/main/java/com/auth0/android/authentication/AuthenticationAPIClient.kt @@ -678,7 +678,7 @@ public class AuthenticationAPIClient @VisibleForTesting(otherwise = VisibleForTe private const val WELL_KNOWN_PATH = ".well-known" private const val JWKS_FILE_PATH = "jwks.json" private fun createErrorAdapter(): ErrorAdapter { - val mapAdapter = forMap(Gson()) + val mapAdapter = forMap(GsonProvider.gson) return object : ErrorAdapter { override fun fromRawResponse( statusCode: Int, diff --git a/auth0/src/main/java/com/auth0/android/management/UsersAPIClient.kt b/auth0/src/main/java/com/auth0/android/management/UsersAPIClient.kt index 922d31d41..261c26358 100755 --- a/auth0/src/main/java/com/auth0/android/management/UsersAPIClient.kt +++ b/auth0/src/main/java/com/auth0/android/management/UsersAPIClient.kt @@ -236,7 +236,7 @@ public class UsersAPIClient @VisibleForTesting(otherwise = VisibleForTesting.PRI private const val USER_METADATA_KEY = "user_metadata" private fun createErrorAdapter(): ErrorAdapter { - val mapAdapter = forMap(Gson()) + val mapAdapter = forMap(GsonProvider.gson) return object : ErrorAdapter { override fun fromRawResponse( statusCode: Int, diff --git a/auth0/src/main/java/com/auth0/android/util/Auth0UserAgent.kt b/auth0/src/main/java/com/auth0/android/util/Auth0UserAgent.kt index 1fc4971ad..b2cbb453e 100755 --- a/auth0/src/main/java/com/auth0/android/util/Auth0UserAgent.kt +++ b/auth0/src/main/java/com/auth0/android/util/Auth0UserAgent.kt @@ -5,7 +5,7 @@ import android.text.TextUtils import android.util.Base64 import androidx.annotation.VisibleForTesting import com.auth0.android.auth0.BuildConfig -import com.google.gson.Gson +import com.auth0.android.request.internal.GsonProvider import java.nio.charset.StandardCharsets import java.util.* @@ -54,7 +54,7 @@ public class Auth0UserAgent public constructor( values[NAME_KEY] = name values[VERSION_KEY] = version values[ENV_KEY] = environment - val json = Gson().toJson(values) + val json = GsonProvider.gson.toJson(values) val bytes = json.toByteArray(StandardCharsets.UTF_8) value = String( Base64.encode(bytes, Base64.URL_SAFE or Base64.NO_WRAP),