Skip to content

Commit 7747cc9

Browse files
authored
[Kotlin] update ApiClient to register all adapters for GsonBuilder (#18965)
* update api client to register type adapter * update samples * remove json array variable name
1 parent cf303d4 commit 7747cc9

File tree

12 files changed

+243
-236
lines changed
  • modules/openapi-generator/src/main/resources/kotlin-client
  • samples/client
    • echo_api/kotlin-model-prefix-type-mappings/src/main/kotlin/org/openapitools/client/infrastructure
    • petstore
      • kotlin-default-values-jvm-retrofit2/src/main/kotlin/org/openapitools/client/infrastructure
      • kotlin-jvm-jackson/src/main/kotlin/org/openapitools/client/infrastructure
      • kotlin-model-prefix-type-mappings/src
      • kotlin-retrofit2/src/main/kotlin/org/openapitools/client/infrastructure
      • kotlin-retrofit2-jackson/src/main/kotlin/org/openapitools/client/infrastructure
      • kotlin-retrofit2-kotlinx_serialization/src/main/kotlin/org/openapitools/client/infrastructure
      • kotlin-retrofit2-rx3/src/main/kotlin/org/openapitools/client/infrastructure

12 files changed

+243
-236
lines changed

modules/openapi-generator/src/main/resources/kotlin-client/data_class.mustache

+7-7
Original file line numberDiff line numberDiff line change
@@ -163,6 +163,7 @@ import {{packageName}}.infrastructure.ITransformForStorage
163163
{{/vars}}
164164
{{/hasEnums}}
165165
{{#generateOneOfAnyOfWrappers}}
166+
{{#gson}}
166167

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

252-
val jsonArray{{name}} = jsonObj.getAsJsonArray("{{{baseName}}}")
253253
// validate the required field `{{{baseName}}}` (array)
254-
for (i in 0 until jsonArray{{name}}.size()) {
255-
{{{items.dataType}}}.validateJsonElement(jsonArray{{name}}.get(i))
254+
for (i in 0 until jsonObj.getAsJsonArray("{{{baseName}}}").size()) {
255+
{{{items.dataType}}}.validateJsonElement(jsonObj.getAsJsonArray("{{{baseName}}}").get(i))
256256
}
257257
{{/required}}
258258
{{^required}}
259259
if (jsonObj["{{{baseName}}}"] != null && !jsonObj["{{{baseName}}}"].isJsonNull) {
260-
val jsonArray{{name}} = jsonObj.getAsJsonArray("{{{baseName}}}")
261-
if (jsonArray{{name}} != null) {
260+
if (jsonObj.getAsJsonArray("{{{baseName}}}") != null) {
262261
// ensure the json data is an array
263262
require(jsonObj["{{{baseName}}}"].isJsonArray) {
264263
String.format("Expected the field `{{{baseName}}}` to be an array in the JSON string but got `%s`", jsonObj["{{{baseName}}}"].toString())
265264
}
266265

267266
// validate the optional field `{{{baseName}}}` (array)
268-
for (i in 0 until jsonArray{{name}}.size()) {
269-
{{{items.dataType}}}.validateJsonElement(jsonArray{{name}}[i])
267+
for (i in 0 until jsonObj.getAsJsonArray("{{{baseName}}}").size()) {
268+
{{{items.dataType}}}.validateJsonElement(jsonObj.getAsJsonArray("{{{baseName}}}").get(i))
270269
}
271270
}
272271
}
@@ -356,6 +355,7 @@ import {{packageName}}.infrastructure.ITransformForStorage
356355
{{/discriminator}}
357356
}
358357
}
358+
{{/gson}}
359359
{{/generateOneOfAnyOfWrappers}}
360360

361361
{{#vendorExtensions.x-has-data-class-body}}

modules/openapi-generator/src/main/resources/kotlin-client/libraries/jvm-retrofit2/infrastructure/ApiClient.kt.mustache

+64-70
Original file line numberDiff line numberDiff line change
@@ -64,9 +64,9 @@ import okhttp3.MediaType.Companion.toMediaType
6464
private var baseUrl: String = defaultBasePath,
6565
private val okHttpClientBuilder: OkHttpClient.Builder? = null,
6666
{{^kotlinx_serialization}}
67-
private val serializerBuilder: {{#gson}}GsonBuilder{{/gson}}{{#moshi}}Moshi.Builder{{/moshi}}{{#jackson}}ObjectMapper{{/jackson}} = Serializer.{{#gson}}gsonBuilder{{/gson}}{{#moshi}}moshiBuilder{{/moshi}}{{#jackson}}jacksonObjectMapper{{/jackson}},
67+
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}},
6868
{{/kotlinx_serialization}}
69-
private val callFactory : Call.Factory? = null,
69+
private val callFactory: Call.Factory? = null,
7070
private val callAdapterFactories: List<CallAdapter.Factory> = listOf(
7171
{{#useRxJava}}
7272
RxJavaCallAdapterFactory.create(),
@@ -148,7 +148,7 @@ import okhttp3.MediaType.Companion.toMediaType
148148
addAuthorization(authName, auth)
149149
}
150150
}
151-
{{#generateOneOfAnyOfWrappers}}
151+
{{#generateOneOfAnyOfWrappers}}
152152
{{^kotlinx_serialization}}
153153
{{#gson}}
154154
{{#models}}
@@ -162,7 +162,7 @@ import okhttp3.MediaType.Companion.toMediaType
162162
{{/models}}
163163
{{/gson}}
164164
{{/kotlinx_serialization}}
165-
{{/generateOneOfAnyOfWrappers}}
165+
{{/generateOneOfAnyOfWrappers}}
166166
}
167167

168168
{{#authMethods}}
@@ -177,21 +177,6 @@ import okhttp3.MediaType.Companion.toMediaType
177177
password: String
178178
) : this(baseUrl, okHttpClientBuilder, {{^kotlinx_serialization}}serializerBuilder, {{/kotlinx_serialization}}arrayOf(authName)) {
179179
setCredentials(username, password)
180-
{{#generateOneOfAnyOfWrappers}}
181-
{{^kotlinx_serialization}}
182-
{{#gson}}
183-
{{#models}}
184-
{{#model}}
185-
{{^isEnum}}
186-
{{^hasChildren}}
187-
serializerBuilder.registerTypeAdapterFactory({{modelPackage}}.{{{classname}}}.CustomTypeAdapterFactory())
188-
{{/hasChildren}}
189-
{{/isEnum}}
190-
{{/model}}
191-
{{/models}}
192-
{{/gson}}
193-
{{/kotlinx_serialization}}
194-
{{/generateOneOfAnyOfWrappers}}
195180
}
196181

197182
{{/isBasicBasic}}
@@ -204,21 +189,6 @@ import okhttp3.MediaType.Companion.toMediaType
204189
bearerToken: String
205190
) : this(baseUrl, okHttpClientBuilder, {{^kotlinx_serialization}}serializerBuilder, {{/kotlinx_serialization}}arrayOf(authName)) {
206191
setBearerToken(bearerToken)
207-
{{#generateOneOfAnyOfWrappers}}
208-
{{^kotlinx_serialization}}
209-
{{#gson}}
210-
{{#models}}
211-
{{#model}}
212-
{{^isEnum}}
213-
{{^hasChildren}}
214-
serializerBuilder.registerTypeAdapterFactory({{modelPackage}}.{{{classname}}}.CustomTypeAdapterFactory())
215-
{{/hasChildren}}
216-
{{/isEnum}}
217-
{{/model}}
218-
{{/models}}
219-
{{/gson}}
220-
{{/kotlinx_serialization}}
221-
{{/generateOneOfAnyOfWrappers}}
222192
}
223193

224194
{{/isBasicBearer}}
@@ -240,21 +210,6 @@ import okhttp3.MediaType.Companion.toMediaType
240210
?.setClientSecret(secret)
241211
?.setUsername(username)
242212
?.setPassword(password)
243-
{{#generateOneOfAnyOfWrappers}}
244-
{{^kotlinx_serialization}}
245-
{{#gson}}
246-
{{#models}}
247-
{{#model}}
248-
{{^isEnum}}
249-
{{^hasChildren}}
250-
serializerBuilder.registerTypeAdapterFactory({{modelPackage}}.{{{classname}}}.CustomTypeAdapterFactory())
251-
{{/hasChildren}}
252-
{{/isEnum}}
253-
{{/model}}
254-
{{/models}}
255-
{{/gson}}
256-
{{/kotlinx_serialization}}
257-
{{/generateOneOfAnyOfWrappers}}
258213
}
259214

260215
{{/hasOAuthMethods}}
@@ -298,9 +253,9 @@ import okhttp3.MediaType.Companion.toMediaType
298253
{{/hasAuthMethods}}
299254
{{#hasOAuthMethods}}
300255
/**
301-
* Helper method to configure the token endpoint of the first oauth found in the apiAuthorizations (there should be only one)
302-
* @return Token request builder
303-
*/
256+
* Helper method to configure the token endpoint of the first oauth found in the apiAuthorizations (there should be only one)
257+
* @return Token request builder
258+
*/
304259
fun getTokenEndPoint(): TokenRequestBuilder? {
305260
var result: TokenRequestBuilder? = null
306261
apiAuthorizations.values.runOnFirst<Interceptor, OAuth> {
@@ -310,9 +265,9 @@ import okhttp3.MediaType.Companion.toMediaType
310265
}
311266

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

324279
/**
325-
* Helper method to pre-set the oauth access token of the first oauth found in the apiAuthorizations (there should be only one)
326-
* @param accessToken Access token
327-
* @return ApiClient
328-
*/
280+
* Helper method to pre-set the oauth access token of the first oauth found in the apiAuthorizations (there should be only one)
281+
* @param accessToken Access token
282+
* @return ApiClient
283+
*/
329284
fun setAccessToken(accessToken: String): ApiClient {
330285
apiAuthorizations.values.runOnFirst<Interceptor, OAuth> {
331286
setAccessToken(accessToken)
@@ -334,12 +289,12 @@ import okhttp3.MediaType.Companion.toMediaType
334289
}
335290

336291
/**
337-
* Helper method to configure the oauth accessCode/implicit flow parameters
338-
* @param clientId Client ID
339-
* @param clientSecret Client secret
340-
* @param redirectURI Redirect URI
341-
* @return ApiClient
342-
*/
292+
* Helper method to configure the oauth accessCode/implicit flow parameters
293+
* @param clientId Client ID
294+
* @param clientSecret Client secret
295+
* @param redirectURI Redirect URI
296+
* @return ApiClient
297+
*/
343298
fun configureAuthorizationFlow(clientId: String, clientSecret: String, redirectURI: String): ApiClient {
344299
apiAuthorizations.values.runOnFirst<Interceptor, OAuth> {
345300
tokenRequestBuilder
@@ -354,10 +309,10 @@ import okhttp3.MediaType.Companion.toMediaType
354309
}
355310

356311
/**
357-
* Configures a listener which is notified when a new access token is received.
358-
* @param accessTokenListener Access token listener
359-
* @return ApiClient
360-
*/
312+
* Configures a listener which is notified when a new access token is received.
313+
* @param accessTokenListener Access token listener
314+
* @return ApiClient
315+
*/
361316
fun registerAccessTokenListener(accessTokenListener: AccessTokenListener): ApiClient {
362317
apiAuthorizations.values.runOnFirst<Interceptor, OAuth> {
363318
registerAccessTokenListener(accessTokenListener)
@@ -391,6 +346,20 @@ import okhttp3.MediaType.Companion.toMediaType
391346
return retrofitBuilder.callFactory(usedCallFactory).build().create(serviceClass)
392347
}
393348

349+
{{#generateOneOfAnyOfWrappers}}
350+
{{^kotlinx_serialization}}
351+
{{#gson}}
352+
/**
353+
* Gets the serializer builder.
354+
* @return serial builder
355+
*/
356+
fun getSerializerBuilder(): GsonBuilder {
357+
return serializerBuilder
358+
}
359+
360+
{{/gson}}
361+
{{/kotlinx_serialization}}
362+
{{/generateOneOfAnyOfWrappers}}
394363
private fun normalizeBaseUrl() {
395364
if (!baseUrl.endsWith("/")) {
396365
baseUrl += "/"
@@ -399,7 +368,7 @@ import okhttp3.MediaType.Companion.toMediaType
399368

400369
private inline fun <T, reified U> Iterable<T>.runOnFirst(callback: U.() -> Unit) {
401370
for (element in this) {
402-
if (element is U) {
371+
if (element is U) {
403372
callback.invoke(element)
404373
break
405374
}
@@ -416,3 +385,28 @@ import okhttp3.MediaType.Companion.toMediaType
416385
}
417386
}
418387
}
388+
{{#generateOneOfAnyOfWrappers}}
389+
{{^kotlinx_serialization}}
390+
{{#gson}}
391+
392+
/**
393+
* Registers all models with the type adapter factory.
394+
*
395+
* @param gsonBuilder gson builder
396+
* @return GSON builder
397+
*/
398+
fun registerTypeAdapterFactoryForAllModels(gsonBuilder: GsonBuilder): GsonBuilder {
399+
{{#models}}
400+
{{#model}}
401+
{{^isEnum}}
402+
{{^hasChildren}}
403+
gsonBuilder.registerTypeAdapterFactory({{modelPackage}}.{{{classname}}}.CustomTypeAdapterFactory())
404+
{{/hasChildren}}
405+
{{/isEnum}}
406+
{{/model}}
407+
{{/models}}
408+
return gsonBuilder
409+
}
410+
{{/gson}}
411+
{{/kotlinx_serialization}}
412+
{{/generateOneOfAnyOfWrappers}}

samples/client/echo_api/kotlin-model-prefix-type-mappings/src/main/kotlin/org/openapitools/client/infrastructure/ApiClient.kt

+2-2
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,7 @@ class ApiClient(
2020
private var baseUrl: String = defaultBasePath,
2121
private val okHttpClientBuilder: OkHttpClient.Builder? = null,
2222
private val serializerBuilder: GsonBuilder = Serializer.gsonBuilder,
23-
private val callFactory : Call.Factory? = null,
23+
private val callFactory: Call.Factory? = null,
2424
private val callAdapterFactories: List<CallAdapter.Factory> = listOf(
2525
),
2626
private val converterFactories: List<Converter.Factory> = listOf(
@@ -150,7 +150,7 @@ class ApiClient(
150150

151151
private inline fun <T, reified U> Iterable<T>.runOnFirst(callback: U.() -> Unit) {
152152
for (element in this) {
153-
if (element is U) {
153+
if (element is U) {
154154
callback.invoke(element)
155155
break
156156
}

samples/client/petstore/kotlin-default-values-jvm-retrofit2/src/main/kotlin/org/openapitools/client/infrastructure/ApiClient.kt

+2-2
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@ class ApiClient(
1717
private var baseUrl: String = defaultBasePath,
1818
private val okHttpClientBuilder: OkHttpClient.Builder? = null,
1919
private val serializerBuilder: Moshi.Builder = Serializer.moshiBuilder,
20-
private val callFactory : Call.Factory? = null,
20+
private val callFactory: Call.Factory? = null,
2121
private val callAdapterFactories: List<CallAdapter.Factory> = listOf(
2222
),
2323
private val converterFactories: List<Converter.Factory> = listOf(
@@ -92,7 +92,7 @@ class ApiClient(
9292

9393
private inline fun <T, reified U> Iterable<T>.runOnFirst(callback: U.() -> Unit) {
9494
for (element in this) {
95-
if (element is U) {
95+
if (element is U) {
9696
callback.invoke(element)
9797
break
9898
}

0 commit comments

Comments
 (0)