diff --git a/.github/workflows/samples-kotlin-client.yaml b/.github/workflows/samples-kotlin-client.yaml index 23ffc655a9e2..4b0dd3d3df36 100644 --- a/.github/workflows/samples-kotlin-client.yaml +++ b/.github/workflows/samples-kotlin-client.yaml @@ -71,6 +71,7 @@ jobs: - samples/client/others/kotlin-jvm-okhttp-path-comments - samples/client/others/kotlin-integer-enum - samples/client/petstore/kotlin-allOff-discriminator-kotlinx-serialization + - samples/client/petstore/kotlin-fix-double-serializable-annotation steps: - uses: actions/checkout@v5 - uses: actions/setup-java@v5 diff --git a/bin/configs/kotlin-fix-double-serializable-annotation.yaml b/bin/configs/kotlin-fix-double-serializable-annotation.yaml new file mode 100644 index 000000000000..b77c60f56568 --- /dev/null +++ b/bin/configs/kotlin-fix-double-serializable-annotation.yaml @@ -0,0 +1,10 @@ +generatorName: kotlin +library: multiplatform +outputDir: samples/client/petstore/kotlin-fix-double-serializable-annotation +inputSpec: modules/openapi-generator/src/test/resources/bugs/issue_18904.yaml +templateDir: modules/openapi-generator/src/main/resources/kotlin-client +additionalProperties: + serializationLibrary: kotlinx_serialization + dateLibrary: kotlinx-datetime + generateOneOfAnyOfWrappers: true + diff --git a/modules/openapi-generator/src/main/resources/kotlin-client/anyof_class.mustache b/modules/openapi-generator/src/main/resources/kotlin-client/anyof_class.mustache index 213b2fc15645..69afceaa6f6c 100644 --- a/modules/openapi-generator/src/main/resources/kotlin-client/anyof_class.mustache +++ b/modules/openapi-generator/src/main/resources/kotlin-client/anyof_class.mustache @@ -66,7 +66,7 @@ import java.io.IOException {{#parcelizeModels}} @Parcelize {{/parcelizeModels}} -{{#multiplatform}}{{^discriminator}}@Serializable{{/discriminator}}{{/multiplatform}}{{#kotlinx_serialization}}{{#serializableModel}}@KSerializable{{/serializableModel}}{{^serializableModel}}@Serializable{{/serializableModel}}{{/kotlinx_serialization}}{{#moshi}}{{#moshiCodeGen}}@JsonClass(generateAdapter = true){{/moshiCodeGen}}{{/moshi}}{{#jackson}}{{#discriminator}}{{>typeInfoAnnotation}}{{/discriminator}}{{/jackson}} +{{#multiplatform}}{{^discriminator}}@Serializable{{/discriminator}}{{/multiplatform}}{{#kotlinx_serialization}}{{#serializableModel}}@KSerializable{{/serializableModel}}{{^serializableModel}}{{^multiplatform}}@Serializable{{/multiplatform}}{{/serializableModel}}{{/kotlinx_serialization}}{{#moshi}}{{#moshiCodeGen}}@JsonClass(generateAdapter = true){{/moshiCodeGen}}{{/moshi}}{{#jackson}}{{#discriminator}}{{>typeInfoAnnotation}}{{/discriminator}}{{/jackson}} {{#isDeprecated}} @Deprecated(message = "This schema is deprecated.") {{/isDeprecated}} diff --git a/modules/openapi-generator/src/main/resources/kotlin-client/data_class.mustache b/modules/openapi-generator/src/main/resources/kotlin-client/data_class.mustache index 564ce0214e50..35eb23fec0df 100644 --- a/modules/openapi-generator/src/main/resources/kotlin-client/data_class.mustache +++ b/modules/openapi-generator/src/main/resources/kotlin-client/data_class.mustache @@ -77,7 +77,7 @@ import {{packageName}}.infrastructure.ITransformForStorage {{#parcelizeModels}} @Parcelize {{/parcelizeModels}} -{{#multiplatform}}@Serializable{{/multiplatform}}{{#kotlinx_serialization}}{{#serializableModel}}@KSerializable{{/serializableModel}}{{^serializableModel}}@Serializable{{/serializableModel}}{{/kotlinx_serialization}}{{#moshi}}{{#moshiCodeGen}}@JsonClass(generateAdapter = true){{/moshiCodeGen}}{{/moshi}}{{#jackson}}{{#discriminator}}{{>typeInfoAnnotation}}{{/discriminator}}{{/jackson}} +{{#multiplatform}}@Serializable{{/multiplatform}}{{#kotlinx_serialization}}{{#serializableModel}}@KSerializable{{/serializableModel}}{{^serializableModel}}{{^multiplatform}}@Serializable{{/multiplatform}}{{/serializableModel}}{{/kotlinx_serialization}}{{#moshi}}{{#moshiCodeGen}}@JsonClass(generateAdapter = true){{/moshiCodeGen}}{{/moshi}}{{#jackson}}{{#discriminator}}{{>typeInfoAnnotation}}{{/discriminator}}{{/jackson}} {{#isDeprecated}} @Deprecated(message = "This schema is deprecated.") {{/isDeprecated}} diff --git a/modules/openapi-generator/src/main/resources/kotlin-client/enum_class.mustache b/modules/openapi-generator/src/main/resources/kotlin-client/enum_class.mustache index 16326a77fe02..8969631cb3aa 100644 --- a/modules/openapi-generator/src/main/resources/kotlin-client/enum_class.mustache +++ b/modules/openapi-generator/src/main/resources/kotlin-client/enum_class.mustache @@ -46,7 +46,7 @@ import kotlinx.serialization.* * * Values: {{#allowableValues}}{{#enumVars}}{{&name}}{{^-last}},{{/-last}}{{/enumVars}}{{/allowableValues}} */ -{{#multiplatform}}@Serializable{{/multiplatform}}{{#kotlinx_serialization}}@Serializable{{#enumUnknownDefaultCase}}(with = {{classname}}Serializer::class){{/enumUnknownDefaultCase}}{{^enumUnknownDefaultCase}}{{^isString}}(with = {{classname}}Serializer::class){{/isString}}{{/enumUnknownDefaultCase}}{{/kotlinx_serialization}} +{{#multiplatform}}@Serializable{{/multiplatform}}{{#kotlinx_serialization}}{{^multiplatform}}@Serializable{{/multiplatform}}{{#enumUnknownDefaultCase}}(with = {{classname}}Serializer::class){{/enumUnknownDefaultCase}}{{^enumUnknownDefaultCase}}{{^isString}}(with = {{classname}}Serializer::class){{/isString}}{{/enumUnknownDefaultCase}}{{/kotlinx_serialization}} {{^multiplatform}} {{#moshi}} @JsonClass(generateAdapter = false) diff --git a/modules/openapi-generator/src/main/resources/kotlin-client/oneof_class.mustache b/modules/openapi-generator/src/main/resources/kotlin-client/oneof_class.mustache index a6423598c0b9..442228682a0b 100644 --- a/modules/openapi-generator/src/main/resources/kotlin-client/oneof_class.mustache +++ b/modules/openapi-generator/src/main/resources/kotlin-client/oneof_class.mustache @@ -66,7 +66,7 @@ import java.io.IOException {{#parcelizeModels}} @Parcelize {{/parcelizeModels}} -{{#multiplatform}}{{^discriminator}}@Serializable{{/discriminator}}{{/multiplatform}}{{#kotlinx_serialization}}{{#serializableModel}}@KSerializable{{/serializableModel}}{{^serializableModel}}@Serializable{{/serializableModel}}{{/kotlinx_serialization}}{{#moshi}}{{#moshiCodeGen}}@JsonClass(generateAdapter = true){{/moshiCodeGen}}{{/moshi}}{{#jackson}}{{#discriminator}}{{>typeInfoAnnotation}}{{/discriminator}}{{/jackson}} +{{#multiplatform}}{{^discriminator}}@Serializable{{/discriminator}}{{/multiplatform}}{{#kotlinx_serialization}}{{#serializableModel}}@KSerializable{{/serializableModel}}{{^serializableModel}}{{^multiplatform}}@Serializable{{/multiplatform}}{{/serializableModel}}{{/kotlinx_serialization}}{{#moshi}}{{#moshiCodeGen}}@JsonClass(generateAdapter = true){{/moshiCodeGen}}{{/moshi}}{{#jackson}}{{#discriminator}}{{>typeInfoAnnotation}}{{/discriminator}}{{/jackson}} {{#isDeprecated}} @Deprecated(message = "This schema is deprecated.") {{/isDeprecated}} diff --git a/modules/openapi-generator/src/test/resources/bugs/issue_18904.yaml b/modules/openapi-generator/src/test/resources/bugs/issue_18904.yaml new file mode 100644 index 000000000000..49c69cae59d9 --- /dev/null +++ b/modules/openapi-generator/src/test/resources/bugs/issue_18904.yaml @@ -0,0 +1,64 @@ +openapi: 3.0.3 +info: { title: demo, version: 1.0.0 } +paths: {} +components: + schemas: + + # data_class + enum_class + Pet: + type: object + required: [id, name, kind] + properties: + id: { type: string } + name: { type: string } + kind: { $ref: '#/components/schemas/PetKind' } + + PetKind: + type: string + enum: [cat, dog, fish] + + # oneOf no discriminator + Animal: + oneOf: + - $ref: '#/components/schemas/Cat' + - $ref: '#/components/schemas/Dog' + + Cat: + type: object + required: [kind, meow] + properties: + kind: + type: string + enum: [cat] + meow: + type: string + + Dog: + type: object + required: [kind, bark] + properties: + kind: + type: string + enum: [dog] + bark: + type: string + + # anyOf no discriminator + Device: + anyOf: + - $ref: '#/components/schemas/Phone' + - $ref: '#/components/schemas/Laptop' + + Phone: + type: object + required: [model, number] + properties: + model: { type: string } + number: { type: string } + + Laptop: + type: object + required: [model, ramGb] + properties: + model: { type: string } + ramGb: { type: integer, format: int32 } diff --git a/samples/client/petstore/kotlin-fix-double-serializable-annotation/.openapi-generator-ignore b/samples/client/petstore/kotlin-fix-double-serializable-annotation/.openapi-generator-ignore new file mode 100644 index 000000000000..7484ee590a38 --- /dev/null +++ b/samples/client/petstore/kotlin-fix-double-serializable-annotation/.openapi-generator-ignore @@ -0,0 +1,23 @@ +# OpenAPI Generator Ignore +# Generated by openapi-generator https://github.com/openapitools/openapi-generator + +# Use this file to prevent files from being overwritten by the generator. +# The patterns follow closely to .gitignore or .dockerignore. + +# As an example, the C# client generator defines ApiClient.cs. +# You can make changes and tell OpenAPI Generator to ignore just this file by uncommenting the following line: +#ApiClient.cs + +# You can match any string of characters against a directory, file or extension with a single asterisk (*): +#foo/*/qux +# The above matches foo/bar/qux and foo/baz/qux, but not foo/bar/baz/qux + +# You can recursively match patterns against a directory, file or extension with a double asterisk (**): +#foo/**/qux +# This matches foo/bar/qux, foo/baz/qux, and foo/bar/baz/qux + +# You can also negate patterns with an exclamation (!). +# For example, you can ignore all files in a docs folder with the file extension .md: +#docs/*.md +# Then explicitly reverse the ignore rule for a single file: +#!docs/README.md diff --git a/samples/client/petstore/kotlin-fix-double-serializable-annotation/.openapi-generator/FILES b/samples/client/petstore/kotlin-fix-double-serializable-annotation/.openapi-generator/FILES new file mode 100644 index 000000000000..b8b250a11998 --- /dev/null +++ b/samples/client/petstore/kotlin-fix-double-serializable-annotation/.openapi-generator/FILES @@ -0,0 +1,46 @@ +.openapi-generator-ignore +README.md +build.gradle.kts +docs/Animal.md +docs/Cat.md +docs/Device.md +docs/Dog.md +docs/Laptop.md +docs/Pet.md +docs/PetKind.md +docs/Phone.md +gradle/wrapper/gradle-wrapper.jar +gradle/wrapper/gradle-wrapper.properties +gradlew +gradlew.bat +settings.gradle.kts +src/commonMain/kotlin/org/openapitools/client/auth/ApiKeyAuth.kt +src/commonMain/kotlin/org/openapitools/client/auth/Authentication.kt +src/commonMain/kotlin/org/openapitools/client/auth/HttpBasicAuth.kt +src/commonMain/kotlin/org/openapitools/client/auth/HttpBearerAuth.kt +src/commonMain/kotlin/org/openapitools/client/auth/OAuth.kt +src/commonMain/kotlin/org/openapitools/client/infrastructure/ApiAbstractions.kt +src/commonMain/kotlin/org/openapitools/client/infrastructure/ApiClient.kt +src/commonMain/kotlin/org/openapitools/client/infrastructure/Base64ByteArray.kt +src/commonMain/kotlin/org/openapitools/client/infrastructure/Bytes.kt +src/commonMain/kotlin/org/openapitools/client/infrastructure/HttpResponse.kt +src/commonMain/kotlin/org/openapitools/client/infrastructure/OctetByteArray.kt +src/commonMain/kotlin/org/openapitools/client/infrastructure/PartConfig.kt +src/commonMain/kotlin/org/openapitools/client/infrastructure/RequestConfig.kt +src/commonMain/kotlin/org/openapitools/client/infrastructure/RequestMethod.kt +src/commonMain/kotlin/org/openapitools/client/models/Animal.kt +src/commonMain/kotlin/org/openapitools/client/models/Cat.kt +src/commonMain/kotlin/org/openapitools/client/models/Device.kt +src/commonMain/kotlin/org/openapitools/client/models/Dog.kt +src/commonMain/kotlin/org/openapitools/client/models/Laptop.kt +src/commonMain/kotlin/org/openapitools/client/models/Pet.kt +src/commonMain/kotlin/org/openapitools/client/models/PetKind.kt +src/commonMain/kotlin/org/openapitools/client/models/Phone.kt +src/test/kotlin/org/openapitools/client/models/AnimalTest.kt +src/test/kotlin/org/openapitools/client/models/CatTest.kt +src/test/kotlin/org/openapitools/client/models/DeviceTest.kt +src/test/kotlin/org/openapitools/client/models/DogTest.kt +src/test/kotlin/org/openapitools/client/models/LaptopTest.kt +src/test/kotlin/org/openapitools/client/models/PetKindTest.kt +src/test/kotlin/org/openapitools/client/models/PetTest.kt +src/test/kotlin/org/openapitools/client/models/PhoneTest.kt diff --git a/samples/client/petstore/kotlin-fix-double-serializable-annotation/.openapi-generator/VERSION b/samples/client/petstore/kotlin-fix-double-serializable-annotation/.openapi-generator/VERSION new file mode 100644 index 000000000000..5e5282953086 --- /dev/null +++ b/samples/client/petstore/kotlin-fix-double-serializable-annotation/.openapi-generator/VERSION @@ -0,0 +1 @@ +7.16.0-SNAPSHOT diff --git a/samples/client/petstore/kotlin-fix-double-serializable-annotation/README.md b/samples/client/petstore/kotlin-fix-double-serializable-annotation/README.md new file mode 100644 index 000000000000..25dda88ea8ea --- /dev/null +++ b/samples/client/petstore/kotlin-fix-double-serializable-annotation/README.md @@ -0,0 +1,58 @@ +# org.openapitools.client - Kotlin client library for demo + +No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + +## Overview +This API client was generated by the [OpenAPI Generator](https://openapi-generator.tech) project. By using the [openapi-spec](https://github.com/OAI/OpenAPI-Specification) from a remote server, you can easily generate an API client. + +- API version: 1.0.0 +- Package version: +- Generator version: 7.16.0-SNAPSHOT +- Build package: org.openapitools.codegen.languages.KotlinClientCodegen + +## Requires + +* Kotlin 1.5.10 + +## Build + +``` +./gradlew check assemble +``` + +This runs all tests and packages the library. + +## Features/Implementation Notes + +* Supports JSON inputs/outputs, File inputs, and Form inputs. +* Supports collection formats for query parameters: csv, tsv, ssv, pipes. +* Some Kotlin and Java types are fully qualified to avoid conflicts with types defined in OpenAPI definitions. + + + +## Documentation for API Endpoints + +All URIs are relative to *http://localhost* + +| Class | Method | HTTP request | Description | +| ------------ | ------------- | ------------- | ------------- | + + + +## Documentation for Models + + - [org.openapitools.client.models.Animal](docs/Animal.md) + - [org.openapitools.client.models.Cat](docs/Cat.md) + - [org.openapitools.client.models.Device](docs/Device.md) + - [org.openapitools.client.models.Dog](docs/Dog.md) + - [org.openapitools.client.models.Laptop](docs/Laptop.md) + - [org.openapitools.client.models.Pet](docs/Pet.md) + - [org.openapitools.client.models.PetKind](docs/PetKind.md) + - [org.openapitools.client.models.Phone](docs/Phone.md) + + + +## Documentation for Authorization + +Endpoints do not require authorization. + diff --git a/samples/client/petstore/kotlin-fix-double-serializable-annotation/build.gradle.kts b/samples/client/petstore/kotlin-fix-double-serializable-annotation/build.gradle.kts new file mode 100644 index 000000000000..c18e8595dfca --- /dev/null +++ b/samples/client/petstore/kotlin-fix-double-serializable-annotation/build.gradle.kts @@ -0,0 +1,95 @@ +import org.jetbrains.kotlin.gradle.plugin.mpp.KotlinNativeTarget + +plugins { + kotlin("multiplatform") version "2.1.21" // kotlin_version + kotlin("plugin.serialization") version "2.1.21" // kotlin_version +} + +group = "org.openapitools" +version = "1.0.0" + +val kotlin_version = "2.1.21" +val coroutines_version = "1.10.2" +val serialization_version = "1.8.1" +val ktor_version = "3.1.3" + +repositories { + mavenCentral() +} + +kotlin { + jvm() + iosX64() + iosArm64() + iosSimulatorArm64() + js { + browser() + nodejs() + } + + sourceSets { + commonMain { + dependencies { + implementation("org.jetbrains.kotlinx:kotlinx-coroutines-core:$coroutines_version") + implementation("org.jetbrains.kotlinx:kotlinx-serialization-core:$serialization_version") + + api("io.ktor:ktor-client-core:$ktor_version") + api("io.ktor:ktor-client-serialization:$ktor_version") + api("io.ktor:ktor-client-content-negotiation:$ktor_version") + api("io.ktor:ktor-serialization-kotlinx-json:$ktor_version") + + api("org.jetbrains.kotlinx:kotlinx-datetime:0.6.2") + } + } + + commonTest { + dependencies { + implementation(kotlin("test")) + implementation("io.ktor:ktor-client-mock:$ktor_version") + } + } + + jvmMain { + dependencies { + implementation(kotlin("stdlib-jdk7")) + implementation("io.ktor:ktor-client-cio-jvm:$ktor_version") + } + } + + jvmTest { + dependencies { + implementation(kotlin("test-junit")) + } + } + + iosMain { + dependencies { + api("io.ktor:ktor-client-ios:$ktor_version") + } + } + + jsMain { + dependencies { + api("io.ktor:ktor-client-js:$ktor_version") + } + } + } +} + +tasks { + register("iosTest") { + val device = project.findProperty("device")?.toString() ?: "iPhone 8" + dependsOn("linkDebugTestIosX64") + group = JavaBasePlugin.VERIFICATION_GROUP + description = "Execute unit tests on ${device} simulator" + doLast { + val binary = kotlin.targets.getByName("iosX64").binaries.getTest("DEBUG") + exec { + commandLine("xcrun", "simctl", "spawn", device, binary.outputFile) + } + } + } + register("test") { + dependsOn("allTests") + } +} diff --git a/samples/client/petstore/kotlin-fix-double-serializable-annotation/docs/Animal.md b/samples/client/petstore/kotlin-fix-double-serializable-annotation/docs/Animal.md new file mode 100644 index 000000000000..8b789827f311 --- /dev/null +++ b/samples/client/petstore/kotlin-fix-double-serializable-annotation/docs/Animal.md @@ -0,0 +1,19 @@ + +# Animal + +## Properties +| Name | Type | Description | Notes | +| ------------ | ------------- | ------------- | ------------- | +| **kind** | [**inline**](#Kind) | | | +| **meow** | **kotlin.String** | | | +| **bark** | **kotlin.String** | | | + + + +## Enum: kind +| Name | Value | +| ---- | ----- | +| kind | dog | + + + diff --git a/samples/client/petstore/kotlin-fix-double-serializable-annotation/docs/Cat.md b/samples/client/petstore/kotlin-fix-double-serializable-annotation/docs/Cat.md new file mode 100644 index 000000000000..90778dd2b21b --- /dev/null +++ b/samples/client/petstore/kotlin-fix-double-serializable-annotation/docs/Cat.md @@ -0,0 +1,18 @@ + +# Cat + +## Properties +| Name | Type | Description | Notes | +| ------------ | ------------- | ------------- | ------------- | +| **kind** | [**inline**](#Kind) | | | +| **meow** | **kotlin.String** | | | + + + +## Enum: kind +| Name | Value | +| ---- | ----- | +| kind | cat | + + + diff --git a/samples/client/petstore/kotlin-fix-double-serializable-annotation/docs/Device.md b/samples/client/petstore/kotlin-fix-double-serializable-annotation/docs/Device.md new file mode 100644 index 000000000000..56e9af9276f5 --- /dev/null +++ b/samples/client/petstore/kotlin-fix-double-serializable-annotation/docs/Device.md @@ -0,0 +1,12 @@ + +# Device + +## Properties +| Name | Type | Description | Notes | +| ------------ | ------------- | ------------- | ------------- | +| **model** | **kotlin.String** | | | +| **number** | **kotlin.String** | | | +| **ramGb** | **kotlin.Int** | | | + + + diff --git a/samples/client/petstore/kotlin-fix-double-serializable-annotation/docs/Dog.md b/samples/client/petstore/kotlin-fix-double-serializable-annotation/docs/Dog.md new file mode 100644 index 000000000000..801faee0a971 --- /dev/null +++ b/samples/client/petstore/kotlin-fix-double-serializable-annotation/docs/Dog.md @@ -0,0 +1,18 @@ + +# Dog + +## Properties +| Name | Type | Description | Notes | +| ------------ | ------------- | ------------- | ------------- | +| **kind** | [**inline**](#Kind) | | | +| **bark** | **kotlin.String** | | | + + + +## Enum: kind +| Name | Value | +| ---- | ----- | +| kind | dog | + + + diff --git a/samples/client/petstore/kotlin-fix-double-serializable-annotation/docs/Laptop.md b/samples/client/petstore/kotlin-fix-double-serializable-annotation/docs/Laptop.md new file mode 100644 index 000000000000..f0f412aa77ba --- /dev/null +++ b/samples/client/petstore/kotlin-fix-double-serializable-annotation/docs/Laptop.md @@ -0,0 +1,11 @@ + +# Laptop + +## Properties +| Name | Type | Description | Notes | +| ------------ | ------------- | ------------- | ------------- | +| **model** | **kotlin.String** | | | +| **ramGb** | **kotlin.Int** | | | + + + diff --git a/samples/client/petstore/kotlin-fix-double-serializable-annotation/docs/Pet.md b/samples/client/petstore/kotlin-fix-double-serializable-annotation/docs/Pet.md new file mode 100644 index 000000000000..b6478f58bfe1 --- /dev/null +++ b/samples/client/petstore/kotlin-fix-double-serializable-annotation/docs/Pet.md @@ -0,0 +1,12 @@ + +# Pet + +## Properties +| Name | Type | Description | Notes | +| ------------ | ------------- | ------------- | ------------- | +| **id** | **kotlin.String** | | | +| **name** | **kotlin.String** | | | +| **kind** | [**PetKind**](PetKind.md) | | | + + + diff --git a/samples/client/petstore/kotlin-fix-double-serializable-annotation/docs/PetKind.md b/samples/client/petstore/kotlin-fix-double-serializable-annotation/docs/PetKind.md new file mode 100644 index 000000000000..dd47ca91b356 --- /dev/null +++ b/samples/client/petstore/kotlin-fix-double-serializable-annotation/docs/PetKind.md @@ -0,0 +1,14 @@ + +# PetKind + +## Enum + + + * `cat` (value: `"cat"`) + + * `dog` (value: `"dog"`) + + * `fish` (value: `"fish"`) + + + diff --git a/samples/client/petstore/kotlin-fix-double-serializable-annotation/docs/Phone.md b/samples/client/petstore/kotlin-fix-double-serializable-annotation/docs/Phone.md new file mode 100644 index 000000000000..7a5e45bbd24a --- /dev/null +++ b/samples/client/petstore/kotlin-fix-double-serializable-annotation/docs/Phone.md @@ -0,0 +1,11 @@ + +# Phone + +## Properties +| Name | Type | Description | Notes | +| ------------ | ------------- | ------------- | ------------- | +| **model** | **kotlin.String** | | | +| **number** | **kotlin.String** | | | + + + diff --git a/samples/client/petstore/kotlin-fix-double-serializable-annotation/gradle/wrapper/gradle-wrapper.jar b/samples/client/petstore/kotlin-fix-double-serializable-annotation/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 000000000000..d64cd4917707 Binary files /dev/null and b/samples/client/petstore/kotlin-fix-double-serializable-annotation/gradle/wrapper/gradle-wrapper.jar differ diff --git a/samples/client/petstore/kotlin-fix-double-serializable-annotation/gradle/wrapper/gradle-wrapper.properties b/samples/client/petstore/kotlin-fix-double-serializable-annotation/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 000000000000..e7646dead063 --- /dev/null +++ b/samples/client/petstore/kotlin-fix-double-serializable-annotation/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,7 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-8.7-all.zip +networkTimeout=10000 +validateDistributionUrl=true +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/samples/client/petstore/kotlin-fix-double-serializable-annotation/gradlew b/samples/client/petstore/kotlin-fix-double-serializable-annotation/gradlew new file mode 100644 index 000000000000..9d0ce634cb11 --- /dev/null +++ b/samples/client/petstore/kotlin-fix-double-serializable-annotation/gradlew @@ -0,0 +1,249 @@ +#!/bin/sh + +# +# Copyright © 2015-2021 the original authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +############################################################################## +# +# Gradle start up script for POSIX generated by Gradle. +# +# Important for running: +# +# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is +# noncompliant, but you have some other compliant shell such as ksh or +# bash, then to run this script, type that shell name before the whole +# command line, like: +# +# ksh Gradle +# +# Busybox and similar reduced shells will NOT work, because this script +# requires all of these POSIX shell features: +# * functions; +# * expansions «$var», «${var}», «${var:-default}», «${var+SET}», +# «${var#prefix}», «${var%suffix}», and «$( cmd )»; +# * compound commands having a testable exit status, especially «case»; +# * various built-in commands including «command», «set», and «ulimit». +# +# Important for patching: +# +# (2) This script targets any POSIX shell, so it avoids extensions provided +# by Bash, Ksh, etc; in particular arrays are avoided. +# +# The "traditional" practice of packing multiple parameters into a +# space-separated string is a well documented source of bugs and security +# problems, so this is (mostly) avoided, by progressively accumulating +# options in "$@", and eventually passing that to Java. +# +# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, +# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; +# see the in-line comments for details. +# +# There are tweaks for specific operating systems such as AIX, CygWin, +# Darwin, MinGW, and NonStop. +# +# (3) This script is generated from the Groovy template +# https://github.com/gradle/gradle/blob/HEAD/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt +# within the Gradle project. +# +# You can find Gradle at https://github.com/gradle/gradle/. +# +############################################################################## + +# Attempt to set APP_HOME + +# Resolve links: $0 may be a link +app_path=$0 + +# Need this for daisy-chained symlinks. +while +APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path +[ -h "$app_path" ] +do +ls=$( ls -ld "$app_path" ) +link=${ls#*' -> '} +case $link in #( +/*) app_path=$link ;; #( +*) app_path=$APP_HOME$link ;; +esac +done + +# This is normally unused +# shellcheck disable=SC2034 +APP_BASE_NAME=${0##*/} +# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036) +APP_HOME=$( cd "${APP_HOME:-./}" > /dev/null && pwd -P ) || exit + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD=maximum + +warn () { +echo "$*" +} >&2 + +die () { +echo +echo "$*" +echo +exit 1 +} >&2 + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +nonstop=false +case "$( uname )" in #( +CYGWIN* ) cygwin=true ;; #( +Darwin* ) darwin=true ;; #( +MSYS* | MINGW* ) msys=true ;; #( +NONSTOP* ) nonstop=true ;; +esac + +CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar + + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then +if [ -x "$JAVA_HOME/jre/sh/java" ] ; then +# IBM's JDK on AIX uses strange locations for the executables +JAVACMD=$JAVA_HOME/jre/sh/java +else +JAVACMD=$JAVA_HOME/bin/java +fi +if [ ! -x "$JAVACMD" ] ; then +die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." +fi +else +JAVACMD=java +if ! command -v java >/dev/null 2>&1 +then +die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." +fi +fi + +# Increase the maximum file descriptors if we can. +if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then +case $MAX_FD in #( +max*) +# In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked. +# shellcheck disable=SC2039,SC3045 +MAX_FD=$( ulimit -H -n ) || +warn "Could not query maximum file descriptor limit" +esac +case $MAX_FD in #( +'' | soft) :;; #( +*) +# In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked. +# shellcheck disable=SC2039,SC3045 +ulimit -n "$MAX_FD" || +warn "Could not set maximum file descriptor limit to $MAX_FD" +esac +fi + +# Collect all arguments for the java command, stacking in reverse order: +# * args from the command line +# * the main class name +# * -classpath +# * -D...appname settings +# * --module-path (only if needed) +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. + +# For Cygwin or MSYS, switch paths to Windows format before running java +if "$cygwin" || "$msys" ; then +APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) +CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) + +JAVACMD=$( cygpath --unix "$JAVACMD" ) + +# Now convert the arguments - kludge to limit ourselves to /bin/sh +for arg do +if +case $arg in #( +-*) false ;; # don't mess with options #( +/?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath +[ -e "$t" ] ;; #( +*) false ;; +esac +then +arg=$( cygpath --path --ignore --mixed "$arg" ) +fi +# Roll the args list around exactly as many times as the number of +# args, so each arg winds up back in the position where it started, but +# possibly modified. +# +# NB: a `for` loop captures its iteration list before it begins, so +# changing the positional parameters here affects neither the number of +# iterations, nor the values presented in `arg`. +shift # remove old arg +set -- "$@" "$arg" # push replacement arg +done +fi + + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' + +# Collect all arguments for the java command: +# * DEFAULT_JVM_OPTS, JAVA_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments, +# and any embedded shellness will be escaped. +# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be +# treated as '${Hostname}' itself on the command line. + +set -- \ +"-Dorg.gradle.appname=$APP_BASE_NAME" \ +-classpath "$CLASSPATH" \ +org.gradle.wrapper.GradleWrapperMain \ +"$@" + +# Stop when "xargs" is not available. +if ! command -v xargs >/dev/null 2>&1 +then +die "xargs is not available" +fi + +# Use "xargs" to parse quoted args. +# +# With -n1 it outputs one arg per line, with the quotes and backslashes removed. +# +# In Bash we could simply go: +# +# readarray ARGS < <( xargs -n1 <<<"$var" ) && +# set -- "${ARGS[@]}" "$@" +# +# but POSIX shell has neither arrays nor command substitution, so instead we +# post-process each arg (as a line of input to sed) to backslash-escape any +# character that might be a shell metacharacter, then use eval to reverse +# that process (while maintaining the separation between arguments), and wrap +# the whole thing up as a single "set" statement. +# +# This will of course break if any of these variables contains a newline or +# an unmatched quote. +# + +eval "set -- $( +printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | +xargs -n1 | +sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | +tr '\n' ' ' +)" '"$@"' + +exec "$JAVACMD" "$@" diff --git a/samples/client/petstore/kotlin-fix-double-serializable-annotation/gradlew.bat b/samples/client/petstore/kotlin-fix-double-serializable-annotation/gradlew.bat new file mode 100644 index 000000000000..107acd32c4e6 --- /dev/null +++ b/samples/client/petstore/kotlin-fix-double-serializable-annotation/gradlew.bat @@ -0,0 +1,89 @@ +@rem +@rem Copyright 2015 the original author or authors. +@rem +@rem Licensed under the Apache License, Version 2.0 (the "License"); +@rem you may not use this file except in compliance with the License. +@rem You may obtain a copy of the License at +@rem +@rem https://www.apache.org/licenses/LICENSE-2.0 +@rem +@rem Unless required by applicable law or agreed to in writing, software +@rem distributed under the License is distributed on an "AS IS" BASIS, +@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +@rem See the License for the specific language governing permissions and +@rem limitations under the License. +@rem + +@if "%DEBUG%" == "" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +set DIRNAME=%~dp0 +if "%DIRNAME%" == "" set DIRNAME=. +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Resolve any "." and ".." in APP_HOME to make it shorter. +for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if "%ERRORLEVEL%" == "0" goto execute + +echo. +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto execute + +echo. +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:execute +@rem Setup the command line + +set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar + + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* + +:end +@rem End local scope for the variables with windows NT shell +if "%ERRORLEVEL%"=="0" goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 +exit /b 1 + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/samples/client/petstore/kotlin-fix-double-serializable-annotation/settings.gradle.kts b/samples/client/petstore/kotlin-fix-double-serializable-annotation/settings.gradle.kts new file mode 100644 index 000000000000..90b39979b36f --- /dev/null +++ b/samples/client/petstore/kotlin-fix-double-serializable-annotation/settings.gradle.kts @@ -0,0 +1 @@ +rootProject.name = "kotlin-client" diff --git a/samples/client/petstore/kotlin-fix-double-serializable-annotation/src/commonMain/kotlin/org/openapitools/client/auth/ApiKeyAuth.kt b/samples/client/petstore/kotlin-fix-double-serializable-annotation/src/commonMain/kotlin/org/openapitools/client/auth/ApiKeyAuth.kt new file mode 100644 index 000000000000..8bd8b59a8f82 --- /dev/null +++ b/samples/client/petstore/kotlin-fix-double-serializable-annotation/src/commonMain/kotlin/org/openapitools/client/auth/ApiKeyAuth.kt @@ -0,0 +1,16 @@ +package org.openapitools.client.auth + +class ApiKeyAuth(private val location: String, val paramName: String) : Authentication { + var apiKey: String? = null + var apiKeyPrefix: String? = null + + override fun apply(query: MutableMap>, headers: MutableMap) { + val key: String = apiKey ?: return + val prefix: String? = apiKeyPrefix + val value: String = if (prefix != null) "$prefix $key" else key + when (location) { + "query" -> query[paramName] = listOf(value) + "header" -> headers[paramName] = value + } + } +} diff --git a/samples/client/petstore/kotlin-fix-double-serializable-annotation/src/commonMain/kotlin/org/openapitools/client/auth/Authentication.kt b/samples/client/petstore/kotlin-fix-double-serializable-annotation/src/commonMain/kotlin/org/openapitools/client/auth/Authentication.kt new file mode 100644 index 000000000000..2c5dfb4acc56 --- /dev/null +++ b/samples/client/petstore/kotlin-fix-double-serializable-annotation/src/commonMain/kotlin/org/openapitools/client/auth/Authentication.kt @@ -0,0 +1,13 @@ +package org.openapitools.client.auth + +interface Authentication { + + /** + * Apply authentication settings to header and query params. + * + * @param query Query parameters. + * @param headers Header parameters. + */ + fun apply(query: MutableMap>, headers: MutableMap) + +} diff --git a/samples/client/petstore/kotlin-fix-double-serializable-annotation/src/commonMain/kotlin/org/openapitools/client/auth/HttpBasicAuth.kt b/samples/client/petstore/kotlin-fix-double-serializable-annotation/src/commonMain/kotlin/org/openapitools/client/auth/HttpBasicAuth.kt new file mode 100644 index 000000000000..7c4761bbd6f7 --- /dev/null +++ b/samples/client/petstore/kotlin-fix-double-serializable-annotation/src/commonMain/kotlin/org/openapitools/client/auth/HttpBasicAuth.kt @@ -0,0 +1,15 @@ +package org.openapitools.client.auth + +import io.ktor.util.encodeBase64 + +class HttpBasicAuth : Authentication { + var username: String? = null + var password: String? = null + + override fun apply(query: MutableMap>, headers: MutableMap) { + if (username == null && password == null) return + val str = (username ?: "") + ":" + (password ?: "") + val auth = str.encodeBase64() + headers["Authorization"] = "Basic $auth" + } +} diff --git a/samples/client/petstore/kotlin-fix-double-serializable-annotation/src/commonMain/kotlin/org/openapitools/client/auth/HttpBearerAuth.kt b/samples/client/petstore/kotlin-fix-double-serializable-annotation/src/commonMain/kotlin/org/openapitools/client/auth/HttpBearerAuth.kt new file mode 100644 index 000000000000..a6fb285af5c3 --- /dev/null +++ b/samples/client/petstore/kotlin-fix-double-serializable-annotation/src/commonMain/kotlin/org/openapitools/client/auth/HttpBearerAuth.kt @@ -0,0 +1,14 @@ +package org.openapitools.client.auth + +class HttpBearerAuth(private val scheme: String?) : Authentication { + var bearerToken: String? = null + + override fun apply(query: MutableMap>, headers: MutableMap) { + val token: String = bearerToken ?: return + headers["Authorization"] = (if (scheme != null) upperCaseBearer(scheme)!! + " " else "") + token + } + + private fun upperCaseBearer(scheme: String): String? { + return if ("bearer".equals(scheme, ignoreCase = true)) "Bearer" else scheme + } +} diff --git a/samples/client/petstore/kotlin-fix-double-serializable-annotation/src/commonMain/kotlin/org/openapitools/client/auth/OAuth.kt b/samples/client/petstore/kotlin-fix-double-serializable-annotation/src/commonMain/kotlin/org/openapitools/client/auth/OAuth.kt new file mode 100644 index 000000000000..0e8f30f39383 --- /dev/null +++ b/samples/client/petstore/kotlin-fix-double-serializable-annotation/src/commonMain/kotlin/org/openapitools/client/auth/OAuth.kt @@ -0,0 +1,10 @@ +package org.openapitools.client.auth + +class OAuth : Authentication { + var accessToken: String? = null + + override fun apply(query: MutableMap>, headers: MutableMap) { + val token: String = accessToken ?: return + headers["Authorization"] = "Bearer $token" + } +} diff --git a/samples/client/petstore/kotlin-fix-double-serializable-annotation/src/commonMain/kotlin/org/openapitools/client/infrastructure/ApiAbstractions.kt b/samples/client/petstore/kotlin-fix-double-serializable-annotation/src/commonMain/kotlin/org/openapitools/client/infrastructure/ApiAbstractions.kt new file mode 100644 index 000000000000..7fe8da468374 --- /dev/null +++ b/samples/client/petstore/kotlin-fix-double-serializable-annotation/src/commonMain/kotlin/org/openapitools/client/infrastructure/ApiAbstractions.kt @@ -0,0 +1,23 @@ +package org.openapitools.client.infrastructure + +typealias MultiValueMap = MutableMap> + +fun collectionDelimiter(collectionFormat: String): String = when(collectionFormat) { + "csv" -> "," + "tsv" -> "\t" + "pipe" -> "|" + "space" -> " " + else -> "" +} + +val defaultMultiValueConverter: (item: Any?) -> String = { item -> "$item" } + +fun toMultiValue(items: Array, collectionFormat: String, map: (item: T) -> String = defaultMultiValueConverter): List + = toMultiValue(items.asIterable(), collectionFormat, map) + +fun toMultiValue(items: Iterable, collectionFormat: String, map: (item: T) -> String = defaultMultiValueConverter): List { + return when(collectionFormat) { + "multi" -> items.map(map) + else -> listOf(items.joinToString(separator = collectionDelimiter(collectionFormat), transform = map)) + } +} diff --git a/samples/client/petstore/kotlin-fix-double-serializable-annotation/src/commonMain/kotlin/org/openapitools/client/infrastructure/ApiClient.kt b/samples/client/petstore/kotlin-fix-double-serializable-annotation/src/commonMain/kotlin/org/openapitools/client/infrastructure/ApiClient.kt new file mode 100644 index 000000000000..081b4b08c51f --- /dev/null +++ b/samples/client/petstore/kotlin-fix-double-serializable-annotation/src/commonMain/kotlin/org/openapitools/client/infrastructure/ApiClient.kt @@ -0,0 +1,188 @@ +package org.openapitools.client.infrastructure + +import io.ktor.client.HttpClient +import io.ktor.client.HttpClientConfig +import io.ktor.client.engine.HttpClientEngine +import io.ktor.client.plugins.contentnegotiation.ContentNegotiation +import io.ktor.client.request.* +import io.ktor.client.request.forms.FormDataContent +import io.ktor.client.request.forms.MultiPartFormDataContent +import io.ktor.client.request.header +import io.ktor.client.request.parameter +import io.ktor.client.statement.HttpResponse +import io.ktor.http.ContentType +import io.ktor.serialization.kotlinx.json.json +import io.ktor.http.* +import io.ktor.http.content.PartData +import io.ktor.http.contentType +import kotlin.Unit +import kotlinx.serialization.json.Json + +import org.openapitools.client.auth.* + +open class ApiClient( + private val baseUrl: String +) { + + private lateinit var client: HttpClient + + constructor( + baseUrl: String, + httpClientEngine: HttpClientEngine?, + httpClientConfig: ((HttpClientConfig<*>) -> Unit)? = null, + jsonBlock: Json, + ) : this(baseUrl = baseUrl) { + val clientConfig: (HttpClientConfig<*>) -> Unit by lazy { + { + it.install(ContentNegotiation) { json(jsonBlock) } + httpClientConfig?.invoke(it) + } + } + + client = httpClientEngine?.let { HttpClient(it, clientConfig) } ?: HttpClient(clientConfig) + } + + constructor( + baseUrl: String, + httpClient: HttpClient + ): this(baseUrl = baseUrl) { + this.client = httpClient + } + + private val authentications: kotlin.collections.Map? = null + + companion object { + const val BASE_URL: String = "http://localhost" + val JSON_DEFAULT: Json = Json { + ignoreUnknownKeys = true + prettyPrint = true + isLenient = true + } + protected val UNSAFE_HEADERS: List = listOf(HttpHeaders.ContentType) + } + + /** + * Set the username for the first HTTP basic authentication. + * + * @param username Username + */ + fun setUsername(username: String) { + val auth = authentications?.values?.firstOrNull { it is HttpBasicAuth } as HttpBasicAuth? + ?: throw Exception("No HTTP basic authentication configured") + auth.username = username + } + + /** + * Set the password for the first HTTP basic authentication. + * + * @param password Password + */ + fun setPassword(password: String) { + val auth = authentications?.values?.firstOrNull { it is HttpBasicAuth } as HttpBasicAuth? + ?: throw Exception("No HTTP basic authentication configured") + auth.password = password + } + + /** + * Set the API key value for the first API key authentication. + * + * @param apiKey API key + * @param paramName The name of the API key parameter, or null or set the first key. + */ + fun setApiKey(apiKey: String, paramName: String? = null) { + val auth = authentications?.values?.firstOrNull { it is ApiKeyAuth && (paramName == null || paramName == it.paramName)} as ApiKeyAuth? + ?: throw Exception("No API key authentication configured") + auth.apiKey = apiKey + } + + /** + * Set the API key prefix for the first API key authentication. + * + * @param apiKeyPrefix API key prefix + * @param paramName The name of the API key parameter, or null or set the first key. + */ + fun setApiKeyPrefix(apiKeyPrefix: String, paramName: String? = null) { + val auth = authentications?.values?.firstOrNull { it is ApiKeyAuth && (paramName == null || paramName == it.paramName) } as ApiKeyAuth? + ?: throw Exception("No API key authentication configured") + auth.apiKeyPrefix = apiKeyPrefix + } + + /** + * Set the access token for the first OAuth2 authentication. + * + * @param accessToken Access token + */ + fun setAccessToken(accessToken: String) { + val auth = authentications?.values?.firstOrNull { it is OAuth } as OAuth? + ?: throw Exception("No OAuth2 authentication configured") + auth.accessToken = accessToken + } + + /** + * Set the access token for the first Bearer authentication. + * + * @param bearerToken The bearer token. + */ + fun setBearerToken(bearerToken: String) { + val auth = authentications?.values?.firstOrNull { it is HttpBearerAuth } as HttpBearerAuth? + ?: throw Exception("No Bearer authentication configured") + auth.bearerToken = bearerToken + } + + protected suspend fun multipartFormRequest(requestConfig: RequestConfig, body: kotlin.collections.List?, authNames: kotlin.collections.List): HttpResponse { + return request(requestConfig, MultiPartFormDataContent(body ?: listOf()), authNames) + } + + protected suspend fun urlEncodedFormRequest(requestConfig: RequestConfig, body: Parameters?, authNames: kotlin.collections.List): HttpResponse { + return request(requestConfig, FormDataContent(body ?: Parameters.Empty), authNames) + } + + protected suspend fun jsonRequest(requestConfig: RequestConfig, body: Any? = null, authNames: kotlin.collections.List): HttpResponse = request(requestConfig, body, authNames) + + protected suspend fun request(requestConfig: RequestConfig, body: Any? = null, authNames: kotlin.collections.List): HttpResponse { + requestConfig.updateForAuth(authNames) + val headers = requestConfig.headers + + return client.request { + this.url { + this.takeFrom(URLBuilder(baseUrl)) + appendPath(requestConfig.path.trimStart('/').split('/')) + requestConfig.query.forEach { query -> + query.value.forEach { value -> + parameter(query.key, value) + } + } + } + this.method = requestConfig.method.httpMethod + headers.filter { header -> !UNSAFE_HEADERS.contains(header.key) }.forEach { header -> this.header(header.key, header.value) } + if (requestConfig.method in listOf(RequestMethod.PUT, RequestMethod.POST, RequestMethod.PATCH)) { + val contentType = (requestConfig.headers[HttpHeaders.ContentType]?.let { ContentType.parse(it) } + ?: ContentType.Application.Json) + this.contentType(contentType) + this.setBody(body) + } + } + } + + private fun RequestConfig.updateForAuth(authNames: kotlin.collections.List) { + for (authName in authNames) { + val auth = authentications?.get(authName) ?: throw Exception("Authentication undefined: $authName") + auth.apply(query, headers) + } + } + + private fun URLBuilder.appendPath(components: kotlin.collections.List): URLBuilder = apply { + encodedPath = encodedPath.trimEnd('/') + components.joinToString("/", prefix = "/") { it.encodeURLQueryComponent() } + } + + private val RequestMethod.httpMethod: HttpMethod + get() = when (this) { + RequestMethod.DELETE -> HttpMethod.Delete + RequestMethod.GET -> HttpMethod.Get + RequestMethod.HEAD -> HttpMethod.Head + RequestMethod.PATCH -> HttpMethod.Patch + RequestMethod.PUT -> HttpMethod.Put + RequestMethod.POST -> HttpMethod.Post + RequestMethod.OPTIONS -> HttpMethod.Options + } +} diff --git a/samples/client/petstore/kotlin-fix-double-serializable-annotation/src/commonMain/kotlin/org/openapitools/client/infrastructure/Base64ByteArray.kt b/samples/client/petstore/kotlin-fix-double-serializable-annotation/src/commonMain/kotlin/org/openapitools/client/infrastructure/Base64ByteArray.kt new file mode 100644 index 000000000000..743d6650085d --- /dev/null +++ b/samples/client/petstore/kotlin-fix-double-serializable-annotation/src/commonMain/kotlin/org/openapitools/client/infrastructure/Base64ByteArray.kt @@ -0,0 +1,29 @@ +package org.openapitools.client.infrastructure + +import kotlinx.serialization.* +import kotlinx.serialization.descriptors.* +import kotlinx.serialization.encoding.* + +@Serializable(Base64ByteArray.Companion::class) +class Base64ByteArray(val value: ByteArray) { + companion object : KSerializer { + override val descriptor: SerialDescriptor = PrimitiveSerialDescriptor("Base64ByteArray", PrimitiveKind.STRING) + override fun serialize(encoder: Encoder, value: Base64ByteArray): Unit = encoder.encodeString(value.value.encodeBase64()) + override fun deserialize(decoder: Decoder): Base64ByteArray = Base64ByteArray(decoder.decodeString().decodeBase64Bytes()) + } + + override fun equals(other: Any?): Boolean { + if (this === other) return true + if (other == null || this::class != other::class) return false + other as Base64ByteArray + return value.contentEquals(other.value) + } + + override fun hashCode(): Int { + return value.contentHashCode() + } + + override fun toString(): String { + return "Base64ByteArray(${hex(value)})" + } +} diff --git a/samples/client/petstore/kotlin-fix-double-serializable-annotation/src/commonMain/kotlin/org/openapitools/client/infrastructure/Bytes.kt b/samples/client/petstore/kotlin-fix-double-serializable-annotation/src/commonMain/kotlin/org/openapitools/client/infrastructure/Bytes.kt new file mode 100644 index 000000000000..fe511d948125 --- /dev/null +++ b/samples/client/petstore/kotlin-fix-double-serializable-annotation/src/commonMain/kotlin/org/openapitools/client/infrastructure/Bytes.kt @@ -0,0 +1,104 @@ +package org.openapitools.client.infrastructure + +import io.ktor.utils.io.core.* +import kotlinx.io.Source +import kotlinx.io.readByteArray +import kotlin.experimental.and + +private val digits = "0123456789abcdef".toCharArray() +private const val BASE64_ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/" +private const val BASE64_MASK: Byte = 0x3f +private const val BASE64_PAD = '=' +private val BASE64_INVERSE_ALPHABET = IntArray(256) { BASE64_ALPHABET.indexOf(it.toChar()) } + +private fun String.toCharArray(): CharArray = CharArray(length) { get(it) } +private fun ByteArray.clearFrom(from: Int) = (from until size).forEach { this[it] = 0 } +private fun Int.toBase64(): Char = BASE64_ALPHABET[this] +private fun Byte.fromBase64(): Byte = BASE64_INVERSE_ALPHABET[toInt() and 0xff].toByte() and BASE64_MASK +internal fun ByteArray.encodeBase64(): String = buildPacket { writeFully(this@encodeBase64) }.encodeBase64() +internal fun String.decodeBase64Bytes(): ByteArray = + buildPacket { writeText(dropLastWhile { it == BASE64_PAD }) }.decodeBase64Bytes().readByteArray() + +/** + * Encode [bytes] as a HEX string with no spaces, newlines and `0x` prefixes. + * + * Taken from https://github.com/ktorio/ktor/blob/master/ktor-utils/common/src/io/ktor/util/Crypto.kt + */ +internal fun hex(bytes: ByteArray): String { + val result = CharArray(bytes.size * 2) + var resultIndex = 0 + val digits = digits + + for (element in bytes) { + val b = element.toInt() and 0xff + result[resultIndex++] = digits[b shr 4] + result[resultIndex++] = digits[b and 0x0f] + } + + return result.concatToString() +} + +/** + * Decode bytes from HEX string. It should be no spaces and `0x` prefixes. + * + * Taken from https://github.com/ktorio/ktor/blob/master/ktor-utils/common/src/io/ktor/util/Crypto.kt + */ +internal fun hex(s: String): ByteArray { + val result = ByteArray(s.length / 2) + for (idx in result.indices) { + val srcIdx = idx * 2 + val high = s[srcIdx].toString().toInt(16) shl 4 + val low = s[srcIdx + 1].toString().toInt(16) + result[idx] = (high or low).toByte() + } + + return result +} + +/** + * Encode [ByteReadPacket] in base64 format. + * + * Taken from https://github.com/ktorio/ktor/blob/424d1d2cfaa3281302c60af9500f738c8c2fc846/ktor-utils/common/src/io/ktor/util/Base64.kt + */ +private fun Source.encodeBase64(): String = buildString { + val data = ByteArray(3) + while (remaining > 0) { + val read = readAvailable(data) + data.clearFrom(read) + + val padSize = (data.size - read) * 8 / 6 + val chunk = ((data[0].toInt() and 0xFF) shl 16) or + ((data[1].toInt() and 0xFF) shl 8) or + (data[2].toInt() and 0xFF) + + for (index in data.size downTo padSize) { + val char = (chunk shr (6 * index)) and BASE64_MASK.toInt() + append(char.toBase64()) + } + + repeat(padSize) { append(BASE64_PAD) } + } +} + +/** + * Decode [ByteReadPacket] from base64 format + * + * Taken from https://github.com/ktorio/ktor/blob/424d1d2cfaa3281302c60af9500f738c8c2fc846/ktor-utils/common/src/io/ktor/util/Base64.kt + */ +@Suppress("DEPRECATION") +private fun ByteReadPacket.decodeBase64Bytes(): Input = buildPacket { + val data = ByteArray(4) + + while (remaining > 0) { + val read = readAvailable(data) + + val chunk = data.foldIndexed(0) { index, result, current -> + result or (current.fromBase64().toInt() shl ((3 - index) * 6)) + } + + for (index in data.size - 2 downTo (data.size - read)) { + val origin = (chunk shr (8 * index)) and 0xff + writeByte(origin.toByte()) + } + } +} diff --git a/samples/client/petstore/kotlin-fix-double-serializable-annotation/src/commonMain/kotlin/org/openapitools/client/infrastructure/HttpResponse.kt b/samples/client/petstore/kotlin-fix-double-serializable-annotation/src/commonMain/kotlin/org/openapitools/client/infrastructure/HttpResponse.kt new file mode 100644 index 000000000000..4285d605ea62 --- /dev/null +++ b/samples/client/petstore/kotlin-fix-double-serializable-annotation/src/commonMain/kotlin/org/openapitools/client/infrastructure/HttpResponse.kt @@ -0,0 +1,51 @@ +package org.openapitools.client.infrastructure + +import io.ktor.http.Headers +import io.ktor.http.isSuccess +import io.ktor.util.reflect.TypeInfo +import io.ktor.util.reflect.typeInfo + +open class HttpResponse(val response: io.ktor.client.statement.HttpResponse, val provider: BodyProvider) { + val status: Int = response.status.value + val success: Boolean = response.status.isSuccess() + val headers: Map> = response.headers.mapEntries() + suspend fun body(): T = provider.body(response) + suspend fun typedBody(type: TypeInfo): V = provider.typedBody(response, type) + + companion object { + private fun Headers.mapEntries(): Map> { + val result = mutableMapOf>() + entries().forEach { result[it.key] = it.value } + return result + } + } +} + +interface BodyProvider { + suspend fun body(response: io.ktor.client.statement.HttpResponse): T + suspend fun typedBody(response: io.ktor.client.statement.HttpResponse, type: TypeInfo): V +} + +class TypedBodyProvider(private val type: TypeInfo) : BodyProvider { + @Suppress("UNCHECKED_CAST") + override suspend fun body(response: io.ktor.client.statement.HttpResponse): T = + response.call.body(type) as T + + @Suppress("UNCHECKED_CAST") + override suspend fun typedBody(response: io.ktor.client.statement.HttpResponse, type: TypeInfo): V = + response.call.body(type) as V +} + +class MappedBodyProvider(private val provider: BodyProvider, private val block: S.() -> T) : BodyProvider { + override suspend fun body(response: io.ktor.client.statement.HttpResponse): T = + block(provider.body(response)) + + override suspend fun typedBody(response: io.ktor.client.statement.HttpResponse, type: TypeInfo): V = + provider.typedBody(response, type) +} + +inline fun io.ktor.client.statement.HttpResponse.wrap(): HttpResponse = + HttpResponse(this, TypedBodyProvider(typeInfo())) + +fun HttpResponse.map(block: T.() -> V): HttpResponse = + HttpResponse(response, MappedBodyProvider(provider, block)) diff --git a/samples/client/petstore/kotlin-fix-double-serializable-annotation/src/commonMain/kotlin/org/openapitools/client/infrastructure/OctetByteArray.kt b/samples/client/petstore/kotlin-fix-double-serializable-annotation/src/commonMain/kotlin/org/openapitools/client/infrastructure/OctetByteArray.kt new file mode 100644 index 000000000000..215042551235 --- /dev/null +++ b/samples/client/petstore/kotlin-fix-double-serializable-annotation/src/commonMain/kotlin/org/openapitools/client/infrastructure/OctetByteArray.kt @@ -0,0 +1,29 @@ +package org.openapitools.client.infrastructure + +import kotlinx.serialization.* +import kotlinx.serialization.descriptors.* +import kotlinx.serialization.encoding.* + +@Serializable(OctetByteArray.Companion::class) +class OctetByteArray(val value: ByteArray) { + companion object : KSerializer { + override val descriptor: SerialDescriptor = PrimitiveSerialDescriptor("OctetByteArray", PrimitiveKind.STRING) + override fun serialize(encoder: Encoder, value: OctetByteArray): Unit = encoder.encodeString(hex(value.value)) + override fun deserialize(decoder: Decoder): OctetByteArray = OctetByteArray(hex(decoder.decodeString())) + } + + override fun equals(other: Any?): Boolean { + if (this === other) return true + if (other == null || this::class != other::class) return false + other as OctetByteArray + return value.contentEquals(other.value) + } + + override fun hashCode(): Int { + return value.contentHashCode() + } + + override fun toString(): String { + return "OctetByteArray(${hex(value)})" + } +} diff --git a/samples/client/petstore/kotlin-fix-double-serializable-annotation/src/commonMain/kotlin/org/openapitools/client/infrastructure/PartConfig.kt b/samples/client/petstore/kotlin-fix-double-serializable-annotation/src/commonMain/kotlin/org/openapitools/client/infrastructure/PartConfig.kt new file mode 100644 index 000000000000..be00e38fbaee --- /dev/null +++ b/samples/client/petstore/kotlin-fix-double-serializable-annotation/src/commonMain/kotlin/org/openapitools/client/infrastructure/PartConfig.kt @@ -0,0 +1,11 @@ +package org.openapitools.client.infrastructure + +/** + * Defines a config object for a given part of a multi-part request. + * NOTE: Headers is a Map because rfc2616 defines + * multi-valued headers as csv-only. + */ +data class PartConfig( + val headers: MutableMap = mutableMapOf(), + val body: T? = null +) diff --git a/samples/client/petstore/kotlin-fix-double-serializable-annotation/src/commonMain/kotlin/org/openapitools/client/infrastructure/RequestConfig.kt b/samples/client/petstore/kotlin-fix-double-serializable-annotation/src/commonMain/kotlin/org/openapitools/client/infrastructure/RequestConfig.kt new file mode 100644 index 000000000000..6578b9381b78 --- /dev/null +++ b/samples/client/petstore/kotlin-fix-double-serializable-annotation/src/commonMain/kotlin/org/openapitools/client/infrastructure/RequestConfig.kt @@ -0,0 +1,19 @@ +package org.openapitools.client.infrastructure + +/** + * Defines a config object for a given request. + * NOTE: This object doesn't include 'body' because it + * allows for caching of the constructed object + * for many request definitions. + * NOTE: Headers is a Map because rfc2616 defines + * multi-valued headers as csv-only. + */ +data class RequestConfig( + val method: RequestMethod, + val path: String, + val headers: MutableMap = mutableMapOf(), + val params: MutableMap = mutableMapOf(), + val query: MutableMap> = mutableMapOf(), + val requiresAuthentication: Boolean, + val body: T? = null +) diff --git a/samples/client/petstore/kotlin-fix-double-serializable-annotation/src/commonMain/kotlin/org/openapitools/client/infrastructure/RequestMethod.kt b/samples/client/petstore/kotlin-fix-double-serializable-annotation/src/commonMain/kotlin/org/openapitools/client/infrastructure/RequestMethod.kt new file mode 100644 index 000000000000..beb56f07cdde --- /dev/null +++ b/samples/client/petstore/kotlin-fix-double-serializable-annotation/src/commonMain/kotlin/org/openapitools/client/infrastructure/RequestMethod.kt @@ -0,0 +1,8 @@ +package org.openapitools.client.infrastructure + +/** + * Provides enumerated HTTP verbs + */ +enum class RequestMethod { + GET, DELETE, HEAD, OPTIONS, PATCH, POST, PUT +} diff --git a/samples/client/petstore/kotlin-fix-double-serializable-annotation/src/commonMain/kotlin/org/openapitools/client/models/Animal.kt b/samples/client/petstore/kotlin-fix-double-serializable-annotation/src/commonMain/kotlin/org/openapitools/client/models/Animal.kt new file mode 100644 index 000000000000..9c951a6c0375 --- /dev/null +++ b/samples/client/petstore/kotlin-fix-double-serializable-annotation/src/commonMain/kotlin/org/openapitools/client/models/Animal.kt @@ -0,0 +1,149 @@ +/** + * + * Please note: + * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * Do not edit this file manually. + * + */ + +@file:Suppress( + "ArrayInDataClass", + "EnumEntryName", + "RemoveRedundantQualifierName", + "UnusedImport" +) + +package org.openapitools.client.models + +import org.openapitools.client.models.Cat +import org.openapitools.client.models.Dog + +import kotlinx.serialization.* +import kotlinx.serialization.descriptors.* +import kotlinx.serialization.encoding.* +import java.io.IOException + +/** + * + * + */ +@Serializable + +data class Animal(var actualInstance: Any? = null) { + + class CustomTypeAdapterFactory : TypeAdapterFactory { + override fun create(gson: Gson, type: TypeToken): TypeAdapter? { + if (!Animal::class.java.isAssignableFrom(type.rawType)) { + return null // this class only serializes 'Animal' and its subtypes + } + val elementAdapter = gson.getAdapter(JsonElement::class.java) + val adapterCat = gson.getDelegateAdapter(this, TypeToken.get(Cat::class.java)) + val adapterDog = gson.getDelegateAdapter(this, TypeToken.get(Dog::class.java)) + + @Suppress("UNCHECKED_CAST") + return object : TypeAdapter() { + @Throws(IOException::class) + override fun write(out: JsonWriter,value: Animal?) { + if (value?.actualInstance == null) { + elementAdapter.write(out, null) + return + } + + // check if the actual instance is of the type `Cat` + if (value.actualInstance is Cat) { + val element = adapterCat.toJsonTree(value.actualInstance as Cat?) + elementAdapter.write(out, element) + return + } + // check if the actual instance is of the type `Dog` + if (value.actualInstance is Dog) { + val element = adapterDog.toJsonTree(value.actualInstance as Dog?) + elementAdapter.write(out, element) + return + } + throw IOException("Failed to serialize as the type doesn't match oneOf schemas: Cat, Dog") + } + + @Throws(IOException::class) + override fun read(jsonReader: JsonReader): Animal { + val jsonElement = elementAdapter.read(jsonReader) + var match = 0 + val errorMessages = ArrayList() + var actualAdapter: TypeAdapter<*> = elementAdapter + + // deserialize Cat + try { + // validate the JSON object to see if any exception is thrown + Cat.validateJsonElement(jsonElement) + actualAdapter = adapterCat + match++ + //log.log(Level.FINER, "Input data matches schema 'Cat'") + } catch (e: Exception) { + // deserialization failed, continue + errorMessages.add(String.format("Deserialization for Cat failed with `%s`.", e.message)) + //log.log(Level.FINER, "Input data does not match schema 'Cat'", e) + } + // deserialize Dog + try { + // validate the JSON object to see if any exception is thrown + Dog.validateJsonElement(jsonElement) + actualAdapter = adapterDog + match++ + //log.log(Level.FINER, "Input data matches schema 'Dog'") + } catch (e: Exception) { + // deserialization failed, continue + errorMessages.add(String.format("Deserialization for Dog failed with `%s`.", e.message)) + //log.log(Level.FINER, "Input data does not match schema 'Dog'", e) + } + + if (match == 1) { + val ret = Animal() + ret.actualInstance = actualAdapter.fromJsonTree(jsonElement) + return ret + } + + throw IOException(String.format("Failed deserialization for Animal: %d classes match result, expected 1. Detailed failure message for oneOf schemas: %s. JSON: %s", match, errorMessages, jsonElement.toString())) + } + }.nullSafe() as TypeAdapter + } + } + + companion object { + /** + * Validates the JSON Element and throws an exception if issues found + * + * @param jsonElement JSON Element + * @throws IOException if the JSON Element is invalid with respect to Animal + */ + @Throws(IOException::class) + fun validateJsonElement(jsonElement: JsonElement?) { + requireNotNull(jsonElement) { + "Provided json element must not be null" + } + var match = 0 + val errorMessages = ArrayList() + // validate the json string with Cat + try { + // validate the JSON object to see if any exception is thrown + Cat.validateJsonElement(jsonElement) + match++ + } catch (e: Exception) { + // Validation failed, continue + errorMessages.add(String.format("Validation for Cat failed with `%s`.", e.message)) + } + // validate the json string with Dog + try { + // validate the JSON object to see if any exception is thrown + Dog.validateJsonElement(jsonElement) + match++ + } catch (e: Exception) { + // Validation failed, continue + errorMessages.add(String.format("Validation for Dog failed with `%s`.", e.message)) + } + + if (match != 1) { + throw IOException(String.format("Failed validation for Animal: %d classes match result, expected 1. Detailed failure message for oneOf schemas: %s. JSON: %s", match, errorMessages, jsonElement.toString())) + } + } + } +} diff --git a/samples/client/petstore/kotlin-fix-double-serializable-annotation/src/commonMain/kotlin/org/openapitools/client/models/Cat.kt b/samples/client/petstore/kotlin-fix-double-serializable-annotation/src/commonMain/kotlin/org/openapitools/client/models/Cat.kt new file mode 100644 index 000000000000..258aa7791c8e --- /dev/null +++ b/samples/client/petstore/kotlin-fix-double-serializable-annotation/src/commonMain/kotlin/org/openapitools/client/models/Cat.kt @@ -0,0 +1,50 @@ +/** + * + * Please note: + * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * Do not edit this file manually. + * + */ + +@file:Suppress( + "ArrayInDataClass", + "EnumEntryName", + "RemoveRedundantQualifierName", + "UnusedImport" +) + +package org.openapitools.client.models + + +import kotlinx.serialization.* +import kotlinx.serialization.descriptors.* +import kotlinx.serialization.encoding.* + +/** + * + * + * @param kind + * @param meow + */ +@Serializable + +data class Cat ( + + @SerialName(value = "kind") @Required val kind: Cat.Kind, + + @SerialName(value = "meow") @Required val meow: kotlin.String + +) { + + /** + * + * + * Values: cat + */ + @Serializable + enum class Kind(val value: kotlin.String) { + @SerialName(value = "cat") cat("cat"); + } + +} + diff --git a/samples/client/petstore/kotlin-fix-double-serializable-annotation/src/commonMain/kotlin/org/openapitools/client/models/Device.kt b/samples/client/petstore/kotlin-fix-double-serializable-annotation/src/commonMain/kotlin/org/openapitools/client/models/Device.kt new file mode 100644 index 000000000000..4a12ea800747 --- /dev/null +++ b/samples/client/petstore/kotlin-fix-double-serializable-annotation/src/commonMain/kotlin/org/openapitools/client/models/Device.kt @@ -0,0 +1,145 @@ +/** + * + * Please note: + * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * Do not edit this file manually. + * + */ + +@file:Suppress( + "ArrayInDataClass", + "EnumEntryName", + "RemoveRedundantQualifierName", + "UnusedImport" +) + +package org.openapitools.client.models + +import org.openapitools.client.models.Laptop +import org.openapitools.client.models.Phone + +import kotlinx.serialization.* +import kotlinx.serialization.descriptors.* +import kotlinx.serialization.encoding.* +import java.io.IOException + +/** + * + * + */ +@Serializable + +data class Device(var actualInstance: Any? = null) { + + class CustomTypeAdapterFactory : TypeAdapterFactory { + override fun create(gson: Gson, type: TypeToken): TypeAdapter? { + if (!Device::class.java.isAssignableFrom(type.rawType)) { + return null // this class only serializes 'Device' and its subtypes + } + val elementAdapter = gson.getAdapter(JsonElement::class.java) + val adapterPhone = gson.getDelegateAdapter(this, TypeToken.get(Phone::class.java)) + val adapterLaptop = gson.getDelegateAdapter(this, TypeToken.get(Laptop::class.java)) + + @Suppress("UNCHECKED_CAST") + return object : TypeAdapter() { + @Throws(IOException::class) + override fun write(out: JsonWriter,value: Device?) { + if (value?.actualInstance == null) { + elementAdapter.write(out, null) + return + } + + // check if the actual instance is of the type `Phone` + if (value.actualInstance is Phone) { + val element = adapterPhone.toJsonTree(value.actualInstance as Phone?) + elementAdapter.write(out, element) + return + } + // check if the actual instance is of the type `Laptop` + if (value.actualInstance is Laptop) { + val element = adapterLaptop.toJsonTree(value.actualInstance as Laptop?) + elementAdapter.write(out, element) + return + } + throw IOException("Failed to serialize as the type doesn't match anyOf schemas: Laptop, Phone") + } + + @Throws(IOException::class) + override fun read(jsonReader: JsonReader): Device { + val jsonElement = elementAdapter.read(jsonReader) + val errorMessages = ArrayList() + var actualAdapter: TypeAdapter<*> + val ret = Device() + + // deserialize Phone + try { + // validate the JSON object to see if any exception is thrown + Phone.validateJsonElement(jsonElement) + actualAdapter = adapterPhone + ret.actualInstance = actualAdapter.fromJsonTree(jsonElement) + return ret + //log.log(Level.FINER, "Input data matches schema 'Phone'") + } catch (e: Exception) { + // deserialization failed, continue + errorMessages.add(String.format("Deserialization for Phone failed with `%s`.", e.message)) + //log.log(Level.FINER, "Input data does not match schema 'Phone'", e) + } + // deserialize Laptop + try { + // validate the JSON object to see if any exception is thrown + Laptop.validateJsonElement(jsonElement) + actualAdapter = adapterLaptop + ret.actualInstance = actualAdapter.fromJsonTree(jsonElement) + return ret + //log.log(Level.FINER, "Input data matches schema 'Laptop'") + } catch (e: Exception) { + // deserialization failed, continue + errorMessages.add(String.format("Deserialization for Laptop failed with `%s`.", e.message)) + //log.log(Level.FINER, "Input data does not match schema 'Laptop'", e) + } + + throw IOException(String.format("Failed deserialization for Device: no schema match result. Detailed failure message for anyOf schemas: %s. JSON: %s", errorMessages, jsonElement.toString())) + } + }.nullSafe() as TypeAdapter + } + } + + companion object { + /** + * Validates the JSON Element and throws an exception if issues found + * + * @param jsonElement JSON Element + * @throws IOException if the JSON Element is invalid with respect to Device + */ + @Throws(IOException::class) + fun validateJsonElement(jsonElement: JsonElement?) { + requireNotNull(jsonElement) { + "Provided json element must not be null" + } + var match = 0 + val errorMessages = ArrayList() + // validate the json string with Phone + try { + // validate the JSON object to see if any exception is thrown + Phone.validateJsonElement(jsonElement) + match++ + } catch (e: Exception) { + // Validation failed, continue + errorMessages.add(String.format("Validation for Phone failed with `%s`.", e.message)) + } + // validate the json string with Laptop + try { + // validate the JSON object to see if any exception is thrown + Laptop.validateJsonElement(jsonElement) + match++ + } catch (e: Exception) { + // Validation failed, continue + errorMessages.add(String.format("Validation for Laptop failed with `%s`.", e.message)) + } + + if (match != 1) { + throw IOException(String.format("Failed validation for Device: %d classes match result, expected 1. Detailed failure message for oneOf schemas: %s. JSON: %s", match, errorMessages, jsonElement.toString())) + } + } + } +} diff --git a/samples/client/petstore/kotlin-fix-double-serializable-annotation/src/commonMain/kotlin/org/openapitools/client/models/Dog.kt b/samples/client/petstore/kotlin-fix-double-serializable-annotation/src/commonMain/kotlin/org/openapitools/client/models/Dog.kt new file mode 100644 index 000000000000..4bddbb9fd76f --- /dev/null +++ b/samples/client/petstore/kotlin-fix-double-serializable-annotation/src/commonMain/kotlin/org/openapitools/client/models/Dog.kt @@ -0,0 +1,50 @@ +/** + * + * Please note: + * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * Do not edit this file manually. + * + */ + +@file:Suppress( + "ArrayInDataClass", + "EnumEntryName", + "RemoveRedundantQualifierName", + "UnusedImport" +) + +package org.openapitools.client.models + + +import kotlinx.serialization.* +import kotlinx.serialization.descriptors.* +import kotlinx.serialization.encoding.* + +/** + * + * + * @param kind + * @param bark + */ +@Serializable + +data class Dog ( + + @SerialName(value = "kind") @Required val kind: Dog.Kind, + + @SerialName(value = "bark") @Required val bark: kotlin.String + +) { + + /** + * + * + * Values: dog + */ + @Serializable + enum class Kind(val value: kotlin.String) { + @SerialName(value = "dog") dog("dog"); + } + +} + diff --git a/samples/client/petstore/kotlin-fix-double-serializable-annotation/src/commonMain/kotlin/org/openapitools/client/models/Laptop.kt b/samples/client/petstore/kotlin-fix-double-serializable-annotation/src/commonMain/kotlin/org/openapitools/client/models/Laptop.kt new file mode 100644 index 000000000000..9bc9b06b963a --- /dev/null +++ b/samples/client/petstore/kotlin-fix-double-serializable-annotation/src/commonMain/kotlin/org/openapitools/client/models/Laptop.kt @@ -0,0 +1,41 @@ +/** + * + * Please note: + * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * Do not edit this file manually. + * + */ + +@file:Suppress( + "ArrayInDataClass", + "EnumEntryName", + "RemoveRedundantQualifierName", + "UnusedImport" +) + +package org.openapitools.client.models + + +import kotlinx.serialization.* +import kotlinx.serialization.descriptors.* +import kotlinx.serialization.encoding.* + +/** + * + * + * @param model + * @param ramGb + */ +@Serializable + +data class Laptop ( + + @SerialName(value = "model") @Required val model: kotlin.String, + + @SerialName(value = "ramGb") @Required val ramGb: kotlin.Int + +) { + + +} + diff --git a/samples/client/petstore/kotlin-fix-double-serializable-annotation/src/commonMain/kotlin/org/openapitools/client/models/Pet.kt b/samples/client/petstore/kotlin-fix-double-serializable-annotation/src/commonMain/kotlin/org/openapitools/client/models/Pet.kt new file mode 100644 index 000000000000..e7761ec55504 --- /dev/null +++ b/samples/client/petstore/kotlin-fix-double-serializable-annotation/src/commonMain/kotlin/org/openapitools/client/models/Pet.kt @@ -0,0 +1,45 @@ +/** + * + * Please note: + * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * Do not edit this file manually. + * + */ + +@file:Suppress( + "ArrayInDataClass", + "EnumEntryName", + "RemoveRedundantQualifierName", + "UnusedImport" +) + +package org.openapitools.client.models + +import org.openapitools.client.models.PetKind + +import kotlinx.serialization.* +import kotlinx.serialization.descriptors.* +import kotlinx.serialization.encoding.* + +/** + * + * + * @param id + * @param name + * @param kind + */ +@Serializable + +data class Pet ( + + @SerialName(value = "id") @Required val id: kotlin.String, + + @SerialName(value = "name") @Required val name: kotlin.String, + + @SerialName(value = "kind") @Required val kind: PetKind + +) { + + +} + diff --git a/samples/client/petstore/kotlin-fix-double-serializable-annotation/src/commonMain/kotlin/org/openapitools/client/models/PetKind.kt b/samples/client/petstore/kotlin-fix-double-serializable-annotation/src/commonMain/kotlin/org/openapitools/client/models/PetKind.kt new file mode 100644 index 000000000000..16c5c920fbd5 --- /dev/null +++ b/samples/client/petstore/kotlin-fix-double-serializable-annotation/src/commonMain/kotlin/org/openapitools/client/models/PetKind.kt @@ -0,0 +1,65 @@ +/** + * + * Please note: + * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * Do not edit this file manually. + * + */ + +@file:Suppress( + "ArrayInDataClass", + "EnumEntryName", + "RemoveRedundantQualifierName", + "UnusedImport" +) + +package org.openapitools.client.models + + +import kotlinx.serialization.* + +/** + * + * + * Values: cat,dog,fish + */ +@Serializable +enum class PetKind(val value: kotlin.String) { + + @SerialName(value = "cat") + cat("cat"), + + @SerialName(value = "dog") + dog("dog"), + + @SerialName(value = "fish") + fish("fish"); + + /** + * Override [toString()] to avoid using the enum variable name as the value, and instead use + * the actual value defined in the API spec file. + * + * This solves a problem when the variable name and its value are different, and ensures that + * the client sends the correct enum values to the server always. + */ + override fun toString(): kotlin.String = value + + companion object { + /** + * Converts the provided [data] to a [String] on success, null otherwise. + */ + fun encode(data: kotlin.Any?): kotlin.String? = if (data is PetKind) "$data" else null + + /** + * Returns a valid [PetKind] for [data], null otherwise. + */ + fun decode(data: kotlin.Any?): PetKind? = data?.let { + val normalizedData = "$it".lowercase() + values().firstOrNull { value -> + it == value || normalizedData == "$value".lowercase() + } + } + } +} + + diff --git a/samples/client/petstore/kotlin-fix-double-serializable-annotation/src/commonMain/kotlin/org/openapitools/client/models/Phone.kt b/samples/client/petstore/kotlin-fix-double-serializable-annotation/src/commonMain/kotlin/org/openapitools/client/models/Phone.kt new file mode 100644 index 000000000000..c1fc4f89ef09 --- /dev/null +++ b/samples/client/petstore/kotlin-fix-double-serializable-annotation/src/commonMain/kotlin/org/openapitools/client/models/Phone.kt @@ -0,0 +1,41 @@ +/** + * + * Please note: + * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * Do not edit this file manually. + * + */ + +@file:Suppress( + "ArrayInDataClass", + "EnumEntryName", + "RemoveRedundantQualifierName", + "UnusedImport" +) + +package org.openapitools.client.models + + +import kotlinx.serialization.* +import kotlinx.serialization.descriptors.* +import kotlinx.serialization.encoding.* + +/** + * + * + * @param model + * @param number + */ +@Serializable + +data class Phone ( + + @SerialName(value = "model") @Required val model: kotlin.String, + + @SerialName(value = "number") @Required val number: kotlin.String + +) { + + +} + diff --git a/samples/client/petstore/kotlin-fix-double-serializable-annotation/src/test/kotlin/org/openapitools/client/models/AnimalTest.kt b/samples/client/petstore/kotlin-fix-double-serializable-annotation/src/test/kotlin/org/openapitools/client/models/AnimalTest.kt new file mode 100644 index 000000000000..76d3b5f48df5 --- /dev/null +++ b/samples/client/petstore/kotlin-fix-double-serializable-annotation/src/test/kotlin/org/openapitools/client/models/AnimalTest.kt @@ -0,0 +1,49 @@ +/** + * + * Please note: + * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * Do not edit this file manually. + * + */ + +@file:Suppress( + "ArrayInDataClass", + "EnumEntryName", + "RemoveRedundantQualifierName", + "UnusedImport" +) + +package org.openapitools.client.models + +import io.kotlintest.shouldBe +import io.kotlintest.specs.ShouldSpec + +import org.openapitools.client.models.Animal +import org.openapitools.client.models.Cat +import org.openapitools.client.models.Dog + +class AnimalTest : ShouldSpec() { + init { + // uncomment below to create an instance of Animal + //val modelInstance = Animal() + + // to test the property `kind` + should("test kind") { + // uncomment below to test the property + //modelInstance.kind shouldBe ("TODO") + } + + // to test the property `meow` + should("test meow") { + // uncomment below to test the property + //modelInstance.meow shouldBe ("TODO") + } + + // to test the property `bark` + should("test bark") { + // uncomment below to test the property + //modelInstance.bark shouldBe ("TODO") + } + + } +} diff --git a/samples/client/petstore/kotlin-fix-double-serializable-annotation/src/test/kotlin/org/openapitools/client/models/CatTest.kt b/samples/client/petstore/kotlin-fix-double-serializable-annotation/src/test/kotlin/org/openapitools/client/models/CatTest.kt new file mode 100644 index 000000000000..6a05c26f5e9e --- /dev/null +++ b/samples/client/petstore/kotlin-fix-double-serializable-annotation/src/test/kotlin/org/openapitools/client/models/CatTest.kt @@ -0,0 +1,41 @@ +/** + * + * Please note: + * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * Do not edit this file manually. + * + */ + +@file:Suppress( + "ArrayInDataClass", + "EnumEntryName", + "RemoveRedundantQualifierName", + "UnusedImport" +) + +package org.openapitools.client.models + +import io.kotlintest.shouldBe +import io.kotlintest.specs.ShouldSpec + +import org.openapitools.client.models.Cat + +class CatTest : ShouldSpec() { + init { + // uncomment below to create an instance of Cat + //val modelInstance = Cat() + + // to test the property `kind` + should("test kind") { + // uncomment below to test the property + //modelInstance.kind shouldBe ("TODO") + } + + // to test the property `meow` + should("test meow") { + // uncomment below to test the property + //modelInstance.meow shouldBe ("TODO") + } + + } +} diff --git a/samples/client/petstore/kotlin-fix-double-serializable-annotation/src/test/kotlin/org/openapitools/client/models/DeviceTest.kt b/samples/client/petstore/kotlin-fix-double-serializable-annotation/src/test/kotlin/org/openapitools/client/models/DeviceTest.kt new file mode 100644 index 000000000000..adfc4d97013f --- /dev/null +++ b/samples/client/petstore/kotlin-fix-double-serializable-annotation/src/test/kotlin/org/openapitools/client/models/DeviceTest.kt @@ -0,0 +1,49 @@ +/** + * + * Please note: + * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * Do not edit this file manually. + * + */ + +@file:Suppress( + "ArrayInDataClass", + "EnumEntryName", + "RemoveRedundantQualifierName", + "UnusedImport" +) + +package org.openapitools.client.models + +import io.kotlintest.shouldBe +import io.kotlintest.specs.ShouldSpec + +import org.openapitools.client.models.Device +import org.openapitools.client.models.Laptop +import org.openapitools.client.models.Phone + +class DeviceTest : ShouldSpec() { + init { + // uncomment below to create an instance of Device + //val modelInstance = Device() + + // to test the property `model` + should("test model") { + // uncomment below to test the property + //modelInstance.model shouldBe ("TODO") + } + + // to test the property `number` + should("test number") { + // uncomment below to test the property + //modelInstance.number shouldBe ("TODO") + } + + // to test the property `ramGb` + should("test ramGb") { + // uncomment below to test the property + //modelInstance.ramGb shouldBe ("TODO") + } + + } +} diff --git a/samples/client/petstore/kotlin-fix-double-serializable-annotation/src/test/kotlin/org/openapitools/client/models/DogTest.kt b/samples/client/petstore/kotlin-fix-double-serializable-annotation/src/test/kotlin/org/openapitools/client/models/DogTest.kt new file mode 100644 index 000000000000..8b3e95c326af --- /dev/null +++ b/samples/client/petstore/kotlin-fix-double-serializable-annotation/src/test/kotlin/org/openapitools/client/models/DogTest.kt @@ -0,0 +1,41 @@ +/** + * + * Please note: + * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * Do not edit this file manually. + * + */ + +@file:Suppress( + "ArrayInDataClass", + "EnumEntryName", + "RemoveRedundantQualifierName", + "UnusedImport" +) + +package org.openapitools.client.models + +import io.kotlintest.shouldBe +import io.kotlintest.specs.ShouldSpec + +import org.openapitools.client.models.Dog + +class DogTest : ShouldSpec() { + init { + // uncomment below to create an instance of Dog + //val modelInstance = Dog() + + // to test the property `kind` + should("test kind") { + // uncomment below to test the property + //modelInstance.kind shouldBe ("TODO") + } + + // to test the property `bark` + should("test bark") { + // uncomment below to test the property + //modelInstance.bark shouldBe ("TODO") + } + + } +} diff --git a/samples/client/petstore/kotlin-fix-double-serializable-annotation/src/test/kotlin/org/openapitools/client/models/LaptopTest.kt b/samples/client/petstore/kotlin-fix-double-serializable-annotation/src/test/kotlin/org/openapitools/client/models/LaptopTest.kt new file mode 100644 index 000000000000..9e791caaf886 --- /dev/null +++ b/samples/client/petstore/kotlin-fix-double-serializable-annotation/src/test/kotlin/org/openapitools/client/models/LaptopTest.kt @@ -0,0 +1,41 @@ +/** + * + * Please note: + * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * Do not edit this file manually. + * + */ + +@file:Suppress( + "ArrayInDataClass", + "EnumEntryName", + "RemoveRedundantQualifierName", + "UnusedImport" +) + +package org.openapitools.client.models + +import io.kotlintest.shouldBe +import io.kotlintest.specs.ShouldSpec + +import org.openapitools.client.models.Laptop + +class LaptopTest : ShouldSpec() { + init { + // uncomment below to create an instance of Laptop + //val modelInstance = Laptop() + + // to test the property `model` + should("test model") { + // uncomment below to test the property + //modelInstance.model shouldBe ("TODO") + } + + // to test the property `ramGb` + should("test ramGb") { + // uncomment below to test the property + //modelInstance.ramGb shouldBe ("TODO") + } + + } +} diff --git a/samples/client/petstore/kotlin-fix-double-serializable-annotation/src/test/kotlin/org/openapitools/client/models/PetKindTest.kt b/samples/client/petstore/kotlin-fix-double-serializable-annotation/src/test/kotlin/org/openapitools/client/models/PetKindTest.kt new file mode 100644 index 000000000000..7e0942fbf22b --- /dev/null +++ b/samples/client/petstore/kotlin-fix-double-serializable-annotation/src/test/kotlin/org/openapitools/client/models/PetKindTest.kt @@ -0,0 +1,29 @@ +/** + * + * Please note: + * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * Do not edit this file manually. + * + */ + +@file:Suppress( + "ArrayInDataClass", + "EnumEntryName", + "RemoveRedundantQualifierName", + "UnusedImport" +) + +package org.openapitools.client.models + +import io.kotlintest.shouldBe +import io.kotlintest.specs.ShouldSpec + +import org.openapitools.client.models.PetKind + +class PetKindTest : ShouldSpec() { + init { + // uncomment below to create an instance of PetKind + //val modelInstance = PetKind() + + } +} diff --git a/samples/client/petstore/kotlin-fix-double-serializable-annotation/src/test/kotlin/org/openapitools/client/models/PetTest.kt b/samples/client/petstore/kotlin-fix-double-serializable-annotation/src/test/kotlin/org/openapitools/client/models/PetTest.kt new file mode 100644 index 000000000000..e0fbc78d3621 --- /dev/null +++ b/samples/client/petstore/kotlin-fix-double-serializable-annotation/src/test/kotlin/org/openapitools/client/models/PetTest.kt @@ -0,0 +1,48 @@ +/** + * + * Please note: + * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * Do not edit this file manually. + * + */ + +@file:Suppress( + "ArrayInDataClass", + "EnumEntryName", + "RemoveRedundantQualifierName", + "UnusedImport" +) + +package org.openapitools.client.models + +import io.kotlintest.shouldBe +import io.kotlintest.specs.ShouldSpec + +import org.openapitools.client.models.Pet +import org.openapitools.client.models.PetKind + +class PetTest : ShouldSpec() { + init { + // uncomment below to create an instance of Pet + //val modelInstance = Pet() + + // to test the property `id` + should("test id") { + // uncomment below to test the property + //modelInstance.id shouldBe ("TODO") + } + + // to test the property `name` + should("test name") { + // uncomment below to test the property + //modelInstance.name shouldBe ("TODO") + } + + // to test the property `kind` + should("test kind") { + // uncomment below to test the property + //modelInstance.kind shouldBe ("TODO") + } + + } +} diff --git a/samples/client/petstore/kotlin-fix-double-serializable-annotation/src/test/kotlin/org/openapitools/client/models/PhoneTest.kt b/samples/client/petstore/kotlin-fix-double-serializable-annotation/src/test/kotlin/org/openapitools/client/models/PhoneTest.kt new file mode 100644 index 000000000000..41407333efc0 --- /dev/null +++ b/samples/client/petstore/kotlin-fix-double-serializable-annotation/src/test/kotlin/org/openapitools/client/models/PhoneTest.kt @@ -0,0 +1,41 @@ +/** + * + * Please note: + * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * Do not edit this file manually. + * + */ + +@file:Suppress( + "ArrayInDataClass", + "EnumEntryName", + "RemoveRedundantQualifierName", + "UnusedImport" +) + +package org.openapitools.client.models + +import io.kotlintest.shouldBe +import io.kotlintest.specs.ShouldSpec + +import org.openapitools.client.models.Phone + +class PhoneTest : ShouldSpec() { + init { + // uncomment below to create an instance of Phone + //val modelInstance = Phone() + + // to test the property `model` + should("test model") { + // uncomment below to test the property + //modelInstance.model shouldBe ("TODO") + } + + // to test the property `number` + should("test number") { + // uncomment below to test the property + //modelInstance.number shouldBe ("TODO") + } + + } +}