Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Kotlin] update ApiClient to register all adapters for GsonBuilder #18965

Merged
merged 3 commits into from
Jun 19, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -163,6 +163,7 @@ import {{packageName}}.infrastructure.ITransformForStorage
{{/vars}}
{{/hasEnums}}
{{#generateOneOfAnyOfWrappers}}
{{#gson}}

class CustomTypeAdapterFactory : TypeAdapterFactory {
override fun <T> create(gson: Gson, type: TypeToken<T>): TypeAdapter<T>? {
Expand Down Expand Up @@ -249,24 +250,22 @@ import {{packageName}}.infrastructure.ITransformForStorage
throw IllegalArgumentException(String.format("Expected the field `{{{baseName}}}` to be an array in the JSON string but got `%s`", jsonObj["{{{baseName}}}"].toString()))
}

val jsonArray{{name}} = jsonObj.getAsJsonArray("{{{baseName}}}")
// validate the required field `{{{baseName}}}` (array)
for (i in 0 until jsonArray{{name}}.size()) {
{{{items.dataType}}}.validateJsonElement(jsonArray{{name}}.get(i))
for (i in 0 until jsonObj.getAsJsonArray("{{{baseName}}}").size()) {
{{{items.dataType}}}.validateJsonElement(jsonObj.getAsJsonArray("{{{baseName}}}").get(i))
}
{{/required}}
{{^required}}
if (jsonObj["{{{baseName}}}"] != null && !jsonObj["{{{baseName}}}"].isJsonNull) {
val jsonArray{{name}} = jsonObj.getAsJsonArray("{{{baseName}}}")
if (jsonArray{{name}} != null) {
if (jsonObj.getAsJsonArray("{{{baseName}}}") != null) {
// ensure the json data is an array
require(jsonObj["{{{baseName}}}"].isJsonArray) {
String.format("Expected the field `{{{baseName}}}` to be an array in the JSON string but got `%s`", jsonObj["{{{baseName}}}"].toString())
}

// validate the optional field `{{{baseName}}}` (array)
for (i in 0 until jsonArray{{name}}.size()) {
{{{items.dataType}}}.validateJsonElement(jsonArray{{name}}[i])
for (i in 0 until jsonObj.getAsJsonArray("{{{baseName}}}").size()) {
{{{items.dataType}}}.validateJsonElement(jsonObj.getAsJsonArray("{{{baseName}}}").get(i))
}
}
}
Expand Down Expand Up @@ -356,6 +355,7 @@ import {{packageName}}.infrastructure.ITransformForStorage
{{/discriminator}}
}
}
{{/gson}}
{{/generateOneOfAnyOfWrappers}}

{{#vendorExtensions.x-has-data-class-body}}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -64,9 +64,9 @@ import okhttp3.MediaType.Companion.toMediaType
private var baseUrl: String = defaultBasePath,
private val okHttpClientBuilder: OkHttpClient.Builder? = null,
{{^kotlinx_serialization}}
private val serializerBuilder: {{#gson}}GsonBuilder{{/gson}}{{#moshi}}Moshi.Builder{{/moshi}}{{#jackson}}ObjectMapper{{/jackson}} = Serializer.{{#gson}}gsonBuilder{{/gson}}{{#moshi}}moshiBuilder{{/moshi}}{{#jackson}}jacksonObjectMapper{{/jackson}},
private val serializerBuilder: {{#gson}}GsonBuilder{{/gson}}{{#moshi}}Moshi.Builder{{/moshi}}{{#jackson}}ObjectMapper{{/jackson}} = {{#generateOneOfAnyOfWrappers}}{{#gson}}registerTypeAdapterFactoryForAllModels({{/gson}}{{/generateOneOfAnyOfWrappers}}Serializer.{{#gson}}gsonBuilder{{/gson}}{{#generateOneOfAnyOfWrappers}}{{#gson}}){{/gson}}{{/generateOneOfAnyOfWrappers}}{{#moshi}}moshiBuilder{{/moshi}}{{#jackson}}jacksonObjectMapper{{/jackson}},
{{/kotlinx_serialization}}
private val callFactory : Call.Factory? = null,
private val callFactory: Call.Factory? = null,
private val callAdapterFactories: List<CallAdapter.Factory> = listOf(
{{#useRxJava}}
RxJavaCallAdapterFactory.create(),
Expand Down Expand Up @@ -148,7 +148,7 @@ import okhttp3.MediaType.Companion.toMediaType
addAuthorization(authName, auth)
}
}
{{#generateOneOfAnyOfWrappers}}
{{#generateOneOfAnyOfWrappers}}
{{^kotlinx_serialization}}
{{#gson}}
{{#models}}
Expand All @@ -162,7 +162,7 @@ import okhttp3.MediaType.Companion.toMediaType
{{/models}}
{{/gson}}
{{/kotlinx_serialization}}
{{/generateOneOfAnyOfWrappers}}
{{/generateOneOfAnyOfWrappers}}
}

{{#authMethods}}
Expand All @@ -177,21 +177,6 @@ import okhttp3.MediaType.Companion.toMediaType
password: String
) : this(baseUrl, okHttpClientBuilder, {{^kotlinx_serialization}}serializerBuilder, {{/kotlinx_serialization}}arrayOf(authName)) {
setCredentials(username, password)
{{#generateOneOfAnyOfWrappers}}
{{^kotlinx_serialization}}
{{#gson}}
{{#models}}
{{#model}}
{{^isEnum}}
{{^hasChildren}}
serializerBuilder.registerTypeAdapterFactory({{modelPackage}}.{{{classname}}}.CustomTypeAdapterFactory())
{{/hasChildren}}
{{/isEnum}}
{{/model}}
{{/models}}
{{/gson}}
{{/kotlinx_serialization}}
{{/generateOneOfAnyOfWrappers}}
}

{{/isBasicBasic}}
Expand All @@ -204,21 +189,6 @@ import okhttp3.MediaType.Companion.toMediaType
bearerToken: String
) : this(baseUrl, okHttpClientBuilder, {{^kotlinx_serialization}}serializerBuilder, {{/kotlinx_serialization}}arrayOf(authName)) {
setBearerToken(bearerToken)
{{#generateOneOfAnyOfWrappers}}
{{^kotlinx_serialization}}
{{#gson}}
{{#models}}
{{#model}}
{{^isEnum}}
{{^hasChildren}}
serializerBuilder.registerTypeAdapterFactory({{modelPackage}}.{{{classname}}}.CustomTypeAdapterFactory())
{{/hasChildren}}
{{/isEnum}}
{{/model}}
{{/models}}
{{/gson}}
{{/kotlinx_serialization}}
{{/generateOneOfAnyOfWrappers}}
}

{{/isBasicBearer}}
Expand All @@ -240,21 +210,6 @@ import okhttp3.MediaType.Companion.toMediaType
?.setClientSecret(secret)
?.setUsername(username)
?.setPassword(password)
{{#generateOneOfAnyOfWrappers}}
{{^kotlinx_serialization}}
{{#gson}}
{{#models}}
{{#model}}
{{^isEnum}}
{{^hasChildren}}
serializerBuilder.registerTypeAdapterFactory({{modelPackage}}.{{{classname}}}.CustomTypeAdapterFactory())
{{/hasChildren}}
{{/isEnum}}
{{/model}}
{{/models}}
{{/gson}}
{{/kotlinx_serialization}}
{{/generateOneOfAnyOfWrappers}}
}

{{/hasOAuthMethods}}
Expand Down Expand Up @@ -298,9 +253,9 @@ import okhttp3.MediaType.Companion.toMediaType
{{/hasAuthMethods}}
{{#hasOAuthMethods}}
/**
* Helper method to configure the token endpoint of the first oauth found in the apiAuthorizations (there should be only one)
* @return Token request builder
*/
* Helper method to configure the token endpoint of the first oauth found in the apiAuthorizations (there should be only one)
* @return Token request builder
*/
fun getTokenEndPoint(): TokenRequestBuilder? {
var result: TokenRequestBuilder? = null
apiAuthorizations.values.runOnFirst<Interceptor, OAuth> {
Expand All @@ -310,9 +265,9 @@ import okhttp3.MediaType.Companion.toMediaType
}

/**
* Helper method to configure authorization endpoint of the first oauth found in the apiAuthorizations (there should be only one)
* @return Authentication request builder
*/
* Helper method to configure authorization endpoint of the first oauth found in the apiAuthorizations (there should be only one)
* @return Authentication request builder
*/
fun getAuthorizationEndPoint(): AuthenticationRequestBuilder? {
var result: AuthenticationRequestBuilder? = null
apiAuthorizations.values.runOnFirst<Interceptor, OAuth> {
Expand All @@ -322,10 +277,10 @@ import okhttp3.MediaType.Companion.toMediaType
}

/**
* Helper method to pre-set the oauth access token of the first oauth found in the apiAuthorizations (there should be only one)
* @param accessToken Access token
* @return ApiClient
*/
* Helper method to pre-set the oauth access token of the first oauth found in the apiAuthorizations (there should be only one)
* @param accessToken Access token
* @return ApiClient
*/
fun setAccessToken(accessToken: String): ApiClient {
apiAuthorizations.values.runOnFirst<Interceptor, OAuth> {
setAccessToken(accessToken)
Expand All @@ -334,12 +289,12 @@ import okhttp3.MediaType.Companion.toMediaType
}

/**
* Helper method to configure the oauth accessCode/implicit flow parameters
* @param clientId Client ID
* @param clientSecret Client secret
* @param redirectURI Redirect URI
* @return ApiClient
*/
* Helper method to configure the oauth accessCode/implicit flow parameters
* @param clientId Client ID
* @param clientSecret Client secret
* @param redirectURI Redirect URI
* @return ApiClient
*/
fun configureAuthorizationFlow(clientId: String, clientSecret: String, redirectURI: String): ApiClient {
apiAuthorizations.values.runOnFirst<Interceptor, OAuth> {
tokenRequestBuilder
Expand All @@ -354,10 +309,10 @@ import okhttp3.MediaType.Companion.toMediaType
}

/**
* Configures a listener which is notified when a new access token is received.
* @param accessTokenListener Access token listener
* @return ApiClient
*/
* Configures a listener which is notified when a new access token is received.
* @param accessTokenListener Access token listener
* @return ApiClient
*/
fun registerAccessTokenListener(accessTokenListener: AccessTokenListener): ApiClient {
apiAuthorizations.values.runOnFirst<Interceptor, OAuth> {
registerAccessTokenListener(accessTokenListener)
Expand Down Expand Up @@ -391,6 +346,20 @@ import okhttp3.MediaType.Companion.toMediaType
return retrofitBuilder.callFactory(usedCallFactory).build().create(serviceClass)
}

{{#generateOneOfAnyOfWrappers}}
{{^kotlinx_serialization}}
{{#gson}}
/**
* Gets the serializer builder.
* @return serial builder
*/
fun getSerializerBuilder(): GsonBuilder {
return serializerBuilder
}

{{/gson}}
{{/kotlinx_serialization}}
{{/generateOneOfAnyOfWrappers}}
private fun normalizeBaseUrl() {
if (!baseUrl.endsWith("/")) {
baseUrl += "/"
Expand All @@ -399,7 +368,7 @@ import okhttp3.MediaType.Companion.toMediaType

private inline fun <T, reified U> Iterable<T>.runOnFirst(callback: U.() -> Unit) {
for (element in this) {
if (element is U) {
if (element is U) {
callback.invoke(element)
break
}
Expand All @@ -416,3 +385,28 @@ import okhttp3.MediaType.Companion.toMediaType
}
}
}
{{#generateOneOfAnyOfWrappers}}
{{^kotlinx_serialization}}
{{#gson}}

/**
* Registers all models with the type adapter factory.
*
* @param gsonBuilder gson builder
* @return GSON builder
*/
fun registerTypeAdapterFactoryForAllModels(gsonBuilder: GsonBuilder): GsonBuilder {
{{#models}}
{{#model}}
{{^isEnum}}
{{^hasChildren}}
gsonBuilder.registerTypeAdapterFactory({{modelPackage}}.{{{classname}}}.CustomTypeAdapterFactory())
{{/hasChildren}}
{{/isEnum}}
{{/model}}
{{/models}}
return gsonBuilder
}
{{/gson}}
{{/kotlinx_serialization}}
{{/generateOneOfAnyOfWrappers}}
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ class ApiClient(
private var baseUrl: String = defaultBasePath,
private val okHttpClientBuilder: OkHttpClient.Builder? = null,
private val serializerBuilder: GsonBuilder = Serializer.gsonBuilder,
private val callFactory : Call.Factory? = null,
private val callFactory: Call.Factory? = null,
private val callAdapterFactories: List<CallAdapter.Factory> = listOf(
),
private val converterFactories: List<Converter.Factory> = listOf(
Expand Down Expand Up @@ -150,7 +150,7 @@ class ApiClient(

private inline fun <T, reified U> Iterable<T>.runOnFirst(callback: U.() -> Unit) {
for (element in this) {
if (element is U) {
if (element is U) {
callback.invoke(element)
break
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ class ApiClient(
private var baseUrl: String = defaultBasePath,
private val okHttpClientBuilder: OkHttpClient.Builder? = null,
private val serializerBuilder: Moshi.Builder = Serializer.moshiBuilder,
private val callFactory : Call.Factory? = null,
private val callFactory: Call.Factory? = null,
private val callAdapterFactories: List<CallAdapter.Factory> = listOf(
),
private val converterFactories: List<Converter.Factory> = listOf(
Expand Down Expand Up @@ -92,7 +92,7 @@ class ApiClient(

private inline fun <T, reified U> Iterable<T>.runOnFirst(callback: U.() -> Unit) {
for (element in this) {
if (element is U) {
if (element is U) {
callback.invoke(element)
break
}
Expand Down
Loading
Loading