Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions bin/configs/kotlin-jvm-ktor-gson.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
generatorName: kotlin
outputDir: samples/client/petstore/kotlin-jvm-ktor-gson
library: jvm-ktor
inputSpec: modules/openapi-generator/src/test/resources/2_0/petstore.yaml
templateDir: modules/openapi-generator/src/main/resources/kotlin-client
additionalProperties:
artifactId: kotlin-petstore-jvm-ktor-gson
enumUnknownDefaultCase: true
serializationLibrary: gson
9 changes: 9 additions & 0 deletions bin/configs/kotlin-jvm-ktor-jackson.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
generatorName: kotlin
outputDir: samples/client/petstore/kotlin-jvm-ktor-jackson
library: jvm-ktor
inputSpec: modules/openapi-generator/src/test/resources/2_0/petstore.yaml
templateDir: modules/openapi-generator/src/main/resources/kotlin-client
additionalProperties:
artifactId: kotlin-petstore-jvm-ktor-jackson
enumUnknownDefaultCase: true
serializationLibrary: jackson
2 changes: 1 addition & 1 deletion docs/generators/kotlin.md
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl
|enumPropertyNaming|Naming convention for enum properties: 'camelCase', 'PascalCase', 'snake_case', 'UPPERCASE', and 'original'| |camelCase|
|generateRoomModels|Generate Android Room database models in addition to API models (JVM Volley library only)| |false|
|groupId|Generated artifact package's organization (i.e. maven groupId).| |org.openapitools|
|library|Library template (sub-template) to use|<dl><dt>**jvm-okhttp4**</dt><dd>[DEFAULT] Platform: Java Virtual Machine. HTTP client: OkHttp 4.2.0 (Android 5.0+ and Java 8+). JSON processing: Moshi 1.8.0.</dd><dt>**jvm-okhttp3**</dt><dd>Platform: Java Virtual Machine. HTTP client: OkHttp 3.12.4 (Android 2.3+ and Java 7+). JSON processing: Moshi 1.8.0.</dd><dt>**jvm-retrofit2**</dt><dd>Platform: Java Virtual Machine. HTTP client: Retrofit 2.6.2.</dd><dt>**multiplatform**</dt><dd>Platform: Kotlin multiplatform. HTTP client: Ktor 1.6.0. JSON processing: Kotlinx Serialization: 1.2.1.</dd><dt>**jvm-volley**</dt><dd>Platform: JVM for Android. HTTP client: Volley 1.2.1. JSON processing: gson 2.8.9</dd></dl>|jvm-okhttp4|
|library|Library template (sub-template) to use|<dl><dt>**jvm-ktor**</dt><dd>Platform: Java Virtual Machine. HTTP client: Ktor 1.6.7.</dd><dt>**jvm-okhttp4**</dt><dd>[DEFAULT] Platform: Java Virtual Machine. HTTP client: OkHttp 4.2.0 (Android 5.0+ and Java 8+). JSON processing: Moshi 1.8.0.</dd><dt>**jvm-okhttp3**</dt><dd>Platform: Java Virtual Machine. HTTP client: OkHttp 3.12.4 (Android 2.3+ and Java 7+). JSON processing: Moshi 1.8.0.</dd><dt>**jvm-retrofit2**</dt><dd>Platform: Java Virtual Machine. HTTP client: Retrofit 2.6.2.</dd><dt>**multiplatform**</dt><dd>Platform: Kotlin multiplatform. HTTP client: Ktor 1.6.7. JSON processing: Kotlinx Serialization: 1.2.1.</dd><dt>**jvm-volley**</dt><dd>Platform: JVM for Android. HTTP client: Volley 1.2.1. JSON processing: gson 2.8.9</dd></dl>|jvm-okhttp4|
|modelMutable|Create mutable models| |false|
|moshiCodeGen|Whether to enable codegen with the Moshi library. Refer to the [official Moshi doc](https://github.com/square/moshi#codegen) for more info.| |false|
|omitGradlePluginVersions|Whether to declare Gradle plugin versions in build files.| |false|
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,14 @@

package org.openapitools.codegen.languages;

import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Predicate;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import org.apache.commons.lang3.StringUtils;
import org.openapitools.codegen.CliOption;
import org.openapitools.codegen.CodegenConstants;
Expand All @@ -37,21 +45,14 @@
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Predicate;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import static java.util.Collections.sort;

public class KotlinClientCodegen extends AbstractKotlinCodegen {

private final Logger LOGGER = LoggerFactory.getLogger(KotlinClientCodegen.class);

protected static final String JVM = "jvm";
protected static final String JVM_KTOR = "jvm-ktor";
protected static final String JVM_OKHTTP = "jvm-okhttp";
protected static final String JVM_OKHTTP4 = "jvm-okhttp4";
protected static final String JVM_OKHTTP3 = "jvm-okhttp3";
Expand Down Expand Up @@ -202,10 +203,11 @@ public KotlinClientCodegen() {
collectionType.setDefault(this.collectionType);
cliOptions.add(collectionType);

supportedLibraries.put(JVM_KTOR, "Platform: Java Virtual Machine. HTTP client: Ktor 1.6.7. JSON processing: Gson, Jackson (default).");
supportedLibraries.put(JVM_OKHTTP4, "[DEFAULT] Platform: Java Virtual Machine. HTTP client: OkHttp 4.2.0 (Android 5.0+ and Java 8+). JSON processing: Moshi 1.8.0.");
supportedLibraries.put(JVM_OKHTTP3, "Platform: Java Virtual Machine. HTTP client: OkHttp 3.12.4 (Android 2.3+ and Java 7+). JSON processing: Moshi 1.8.0.");
supportedLibraries.put(JVM_RETROFIT2, "Platform: Java Virtual Machine. HTTP client: Retrofit 2.6.2.");
supportedLibraries.put(MULTIPLATFORM, "Platform: Kotlin multiplatform. HTTP client: Ktor 1.6.0. JSON processing: Kotlinx Serialization: 1.2.1.");
supportedLibraries.put(MULTIPLATFORM, "Platform: Kotlin multiplatform. HTTP client: Ktor 1.6.7. JSON processing: Kotlinx Serialization: 1.2.1.");
supportedLibraries.put(JVM_VOLLEY, "Platform: JVM for Android. HTTP client: Volley 1.2.1. JSON processing: gson 2.8.9");

CliOption libraryOption = new CliOption(CodegenConstants.LIBRARY, "Library template (sub-template) to use");
Expand Down Expand Up @@ -415,6 +417,9 @@ public void processOpts() {
commonSupportingFiles();

switch (getLibrary()) {
case JVM_KTOR:
processJVMKtorLibrary(infrastructureFolder);
break;
case JVM_OKHTTP3:
case JVM_OKHTTP4:
processJVMOkHttpLibrary(infrastructureFolder);
Expand Down Expand Up @@ -626,6 +631,32 @@ private void addSupportingSerializerAdapters(final String infrastructureFolder)
}
}

private void processJVMKtorLibrary(final String infrastructureFolder) {
// in future kotlinx.serialization may be added
if (this.serializationLibrary != SERIALIZATION_LIBRARY_TYPE.gson && this.serializationLibrary != SERIALIZATION_LIBRARY_TYPE.jackson) {
this.serializationLibrary = SERIALIZATION_LIBRARY_TYPE.jackson;
}

additionalProperties.put(JVM, true);
additionalProperties.put(JVM_KTOR, true);

defaultIncludes.add("io.ktor.client.request.forms.InputProvider");

importMapping.put("InputProvider", "io.ktor.client.request.forms.InputProvider");

supportingFiles.add(new SupportingFile("infrastructure/ApiAbstractions.kt.mustache", infrastructureFolder, "ApiAbstractions.kt"));
supportingFiles.add(new SupportingFile("infrastructure/ApiClient.kt.mustache", infrastructureFolder, "ApiClient.kt"));
supportingFiles.add(new SupportingFile("infrastructure/HttpResponse.kt.mustache", infrastructureFolder, "HttpResponse.kt"));
supportingFiles.add(new SupportingFile("infrastructure/RequestConfig.kt.mustache", infrastructureFolder, "RequestConfig.kt"));
supportingFiles.add(new SupportingFile("infrastructure/RequestMethod.kt.mustache", infrastructureFolder, "RequestMethod.kt"));

supportingFiles.add(new SupportingFile("auth/ApiKeyAuth.kt.mustache", authFolder, "ApiKeyAuth.kt"));
supportingFiles.add(new SupportingFile("auth/Authentication.kt.mustache", authFolder, "Authentication.kt"));
supportingFiles.add(new SupportingFile("auth/HttpBasicAuth.kt.mustache", authFolder, "HttpBasicAuth.kt"));
supportingFiles.add(new SupportingFile("auth/HttpBearerAuth.kt.mustache", authFolder, "HttpBearerAuth.kt"));
supportingFiles.add(new SupportingFile("auth/OAuth.kt.mustache", authFolder, "OAuth.kt"));
}

private void processJVMOkHttpLibrary(final String infrastructureFolder) {
commonJvmMultiplatformSupportingFiles(infrastructureFolder);
addSupportingSerializerAdapters(infrastructureFolder);
Expand Down Expand Up @@ -840,8 +871,8 @@ public Map<String, Object> postProcessOperationsWithModels(Map<String, Object> o
});
}

// modify the data type of binary form parameters to a more friendly type for multiplatform builds
if (MULTIPLATFORM.equals(getLibrary()) && operation.allParams != null) {
// modify the data type of binary form parameters to a more friendly type for ktor builds
if ((JVM_KTOR.equals(getLibrary()) || MULTIPLATFORM.equals(getLibrary())) && operation.allParams != null) {
for (CodegenParameter param : operation.allParams) {
if (param.dataFormat != null && param.dataFormat.equals("binary")) {
param.baseType = param.dataType = "io.ktor.client.request.forms.InputProvider";
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,9 @@ wrapper {

buildscript {
ext.kotlin_version = '1.5.10'
{{#jvm-ktor}}
ext.ktor_version = '1.6.7'
{{/jvm-ktor}}
{{#jvm-retrofit2}}
ext.retrofitVersion = '2.9.0'
{{/jvm-retrofit2}}
Expand Down Expand Up @@ -81,6 +84,15 @@ dependencies {
{{#kotlinx_serialization}}
implementation "org.jetbrains.kotlinx:kotlinx-serialization-json:1.2.1"
{{/kotlinx_serialization}}
{{#jvm-ktor}}
implementation "io.ktor:ktor-client-core:$ktor_version"
{{#gson}}
implementation "io.ktor:ktor-client-gson:$ktor_version"
{{/gson}}
{{#jackson}}
implementation "io.ktor:ktor-client-jackson:$ktor_version"
{{/jackson}}
{{/jvm-ktor}}
{{#jvm-okhttp3}}
implementation "com.squareup.okhttp3:okhttp:3.12.13"
{{/jvm-okhttp3}}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,91 @@
{{>licenseInfo}}
package {{apiPackage}}

{{#imports}}import {{import}}
{{/imports}}

import {{packageName}}.infrastructure.*
import io.ktor.client.HttpClientConfig
import io.ktor.client.request.forms.formData
import io.ktor.client.engine.HttpClientEngine
import io.ktor.http.ParametersBuilder

{{#gson}}
import com.google.gson.Gson
{{/gson}}
{{#jackson}}
import com.fasterxml.jackson.databind.ObjectMapper
{{/jackson}}

{{#operations}}
{{#nonPublicApi}}internal {{/nonPublicApi}}open class {{classname}}(
baseUrl: String = ApiClient.BASE_URL,
httpClientEngine: HttpClientEngine? = null,
httpClientConfig: ((HttpClientConfig<*>) -> Unit)? = null,
json: {{#gson}}Gson{{/gson}}{{#jackson}}ObjectMapper{{/jackson}} = ApiClient.JSON_DEFAULT,
) : ApiClient(baseUrl, httpClientEngine, httpClientConfig, json) {

{{#operation}}
/**
* {{summary}}
* {{notes}}
{{#allParams}} * @param {{{paramName}}} {{description}} {{^required}}(optional{{#defaultValue}}, default to {{{.}}}{{/defaultValue}}){{/required}}
{{/allParams}} * @return {{{returnType}}}{{^returnType}}void{{/returnType}}
*/
{{#returnType}}
@Suppress("UNCHECKED_CAST")
{{/returnType}}
open suspend fun {{operationId}}({{#allParams}}{{{paramName}}}: {{{dataType}}}{{^required}}?{{/required}}{{^-last}}, {{/-last}}{{/allParams}}): HttpResponse<{{{returnType}}}{{^returnType}}Unit{{/returnType}}> {

val localVariableAuthNames = listOf<String>({{#authMethods}}"{{name}}"{{^-last}}, {{/-last}}{{/authMethods}})

val localVariableBody = {{#hasBodyParam}}{{#bodyParam}}{{{paramName}}}{{/bodyParam}}{{/hasBodyParam}}
{{^hasBodyParam}}
{{#hasFormParams}}
{{#isMultipart}}
formData {
{{#formParams}}
{{{paramName}}}?.apply { append("{{{baseName}}}", {{{paramName}}}) }
{{/formParams}}
}
{{/isMultipart}}
{{^isMultipart}}
ParametersBuilder().also {
{{#formParams}}
{{{paramName}}}?.apply { it.append("{{{baseName}}}", {{{paramName}}}.toString()) }
{{/formParams}}
}.build()
{{/isMultipart}}
{{/hasFormParams}}
{{^hasFormParams}}
io.ktor.client.utils.EmptyContent
{{/hasFormParams}}
{{/hasBodyParam}}

val localVariableQuery = mutableMapOf<String, List<String>>()
{{#queryParams}}
{{{paramName}}}?.apply { localVariableQuery["{{baseName}}"] = {{#isContainer}}toMultiValue(this, "{{collectionFormat}}"){{/isContainer}}{{^isContainer}}listOf("${{{paramName}}}"){{/isContainer}} }
{{/queryParams}}

val localVariableHeaders = mutableMapOf<String, String>()
{{#headerParams}}
{{{paramName}}}?.apply { localVariableHeaders["{{baseName}}"] = {{#isContainer}}this.joinToString(separator = collectionDelimiter("{{collectionFormat}}")){{/isContainer}}{{^isContainer}}this.toString(){{/isContainer}} }
{{/headerParams}}

val localVariableConfig = RequestConfig<kotlin.Any?>(
RequestMethod.{{httpMethod}},
"{{path}}"{{#pathParams}}.replace("{" + "{{baseName}}" + "}", "${{{paramName}}}"){{/pathParams}},
query = localVariableQuery,
headers = localVariableHeaders
)

return {{#hasBodyParam}}jsonRequest{{/hasBodyParam}}{{^hasBodyParam}}{{#hasFormParams}}{{#isMultipart}}multipartFormRequest{{/isMultipart}}{{^isMultipart}}urlEncodedFormRequest{{/isMultipart}}{{/hasFormParams}}{{^hasFormParams}}request{{/hasFormParams}}{{/hasBodyParam}}(
localVariableConfig,
localVariableBody,
localVariableAuthNames
).wrap()
}

{{/operation}}
}
{{/operations}}
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
package {{packageName}}.auth

class ApiKeyAuth(private val location: String, val paramName: String) : Authentication {
var apiKey: String? = null
var apiKeyPrefix: String? = null

override fun apply(query: MutableMap<String, List<String>>, headers: MutableMap<String, String>) {
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
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
package {{packageName}}.auth

interface Authentication {

/**
* Apply authentication settings to header and query params.
*
* @param query Query parameters.
* @param headers Header parameters.
*/
fun apply(query: MutableMap<String, List<String>>, headers: MutableMap<String, String>)

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
package {{packageName}}.auth

import io.ktor.util.InternalAPI
import io.ktor.util.encodeBase64

class HttpBasicAuth : Authentication {
var username: String? = null
var password: String? = null

@OptIn(InternalAPI::class)
override fun apply(query: MutableMap<String, List<String>>, headers: MutableMap<String, String>) {
if (username == null && password == null) return
val str = (username ?: "") + ":" + (password ?: "")
val auth = str.encodeBase64()
headers["Authorization"] = "Basic $auth"
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
package {{packageName}}.auth

class HttpBearerAuth(private val scheme: String?) : Authentication {
var bearerToken: String? = null

override fun apply(query: MutableMap<String, List<String>>, headers: MutableMap<String, String>) {
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
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
package {{packageName}}.auth

class OAuth : Authentication {
var accessToken: String? = null

override fun apply(query: MutableMap<String, List<String>>, headers: MutableMap<String, String>) {
val token: String = accessToken ?: return
headers["Authorization"] = "Bearer $token"
}
}
Loading