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
7 changes: 7 additions & 0 deletions bin/kotlin-client-all.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
#!/bin/sh

./bin/kotlin-client-okhttp3.sh
./bin/kotlin-client-petstore-multiplatform.sh
./bin/kotlin-client-petstore.sh
./bin/kotlin-client-string.sh
./bin/kotlin-client-threetenbp.sh
34 changes: 34 additions & 0 deletions bin/kotlin-client-okhttp3.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
#!/bin/sh

SCRIPT="$0"
echo "# START SCRIPT: $SCRIPT"

while [ -h "$SCRIPT" ] ; do
ls=$(ls -ld "$SCRIPT")
link=$(expr "$ls" : '.*-> \(.*\)$')
if expr "$link" : '/.*' > /dev/null; then
SCRIPT="$link"
else
SCRIPT=$(dirname "$SCRIPT")/"$link"
fi
done

if [ ! -d "${APP_DIR}" ]; then
APP_DIR=$(dirname "$SCRIPT")/..
APP_DIR=$(cd "${APP_DIR}"; pwd)
fi

executable="./modules/openapi-generator-cli/target/openapi-generator-cli.jar"

if [ ! -f "$executable" ]
then
mvn -B clean package
fi

# if you've executed sbt assembly previously it will use that instead.
export JAVA_OPTS="${JAVA_OPTS} -Xmx1024M -DloggerPath=conf/log4j.properties"
ags="generate -t modules/openapi-generator/src/main/resources/kotlin-client -i modules/openapi-generator/src/test/resources/2_0/petstore.yaml -g kotlin --artifact-id kotlin-petstore-okhttp3 --library jvm-okhttp3 --additional-properties parcelizeModels=true -o samples/client/petstore/kotlin-okhttp3 $@"

java ${JAVA_OPTS} -jar ${executable} ${ags}

cp CI/samples.ci/client/petstore/kotlin-okhttp3/pom.xml samples/client/petstore/kotlin-okhttp3/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,8 @@ public class KotlinClientCodegen extends AbstractKotlinCodegen {
protected static final String VENDOR_EXTENSION_ESCAPED_NAME = "x-escapedName";

protected static final String JVM = "jvm";
protected static final String JVM_OKHTTP4 = "jvm-okhttp4";
protected static final String JVM_OKHTTP3 = "jvm-okhttp3";
protected static final String MULTIPLATFORM = "multiplatform";

public static final String DATE_LIBRARY = "dateLibrary";
Expand Down Expand Up @@ -117,14 +119,15 @@ public KotlinClientCodegen() {
collectionType.setDefault(this.collectionType);
cliOptions.add(collectionType);

supportedLibraries.put(JVM, "Platform: Java Virtual Machine. HTTP client: OkHttp 2.7.5. JSON processing: Gson 2.8.1.");
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(MULTIPLATFORM, "Platform: Kotlin multiplatform. HTTP client: Ktor 1.2.4. JSON processing: Kotlinx Serialization: 0.12.0.");

CliOption libraryOption = new CliOption(CodegenConstants.LIBRARY, "Library template (sub-template) to use");
libraryOption.setEnum(supportedLibraries);
libraryOption.setDefault(JVM);
libraryOption.setDefault(JVM_OKHTTP4);
cliOptions.add(libraryOption);
setLibrary(JVM);
setLibrary(JVM_OKHTTP4);
}

public CodegenType getTag() {
Expand Down Expand Up @@ -172,8 +175,17 @@ public void processOpts() {
supportingFiles.add(new SupportingFile("infrastructure/RequestConfig.kt.mustache", infrastructureFolder, "RequestConfig.kt"));
supportingFiles.add(new SupportingFile("infrastructure/RequestMethod.kt.mustache", infrastructureFolder, "RequestMethod.kt"));

if (JVM.equals(getLibrary())) {
if (isJVMLibrary()) {
additionalProperties.put(JVM, true);

if (JVM_OKHTTP4.equals(getLibrary())) {
additionalProperties.put(JVM_OKHTTP4, true);
} else if (JVM_OKHTTP3.equals(getLibrary())) {
additionalProperties.put(JVM_OKHTTP3, true);
}

supportedLibraries.put(JVM, "A workaround to use the same template folder for both 'jvm-okhttp3' and 'jvm-okhttp4'.");
setLibrary(JVM);

// jvm specific supporting files
supportingFiles.add(new SupportingFile("infrastructure/ApplicationDelegates.kt.mustache", infrastructureFolder, "ApplicationDelegates.kt"));
Expand Down Expand Up @@ -251,6 +263,11 @@ public void processOpts() {
typeMapping.put("list", "kotlin.collections.List");
additionalProperties.put("isList", true);
}

}

private boolean isJVMLibrary() {
return getLibrary() != null && (getLibrary().contains(JVM_OKHTTP4) || getLibrary().contains(JVM_OKHTTP3));
}

@Override
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,12 @@ dependencies {
{{#gson}}
implementation "com.google.code.gson:gson:2.8.5"
{{/gson}}
compile "com.squareup.okhttp3:okhttp:4.0.1"
{{#jvm-okhttp3}}
compile "com.squareup.okhttp3:okhttp:3.12.4"
{{/jvm-okhttp3}}
{{#jvm-okhttp4}}
compile "com.squareup.okhttp3:okhttp:4.2.0"
{{/jvm-okhttp4}}
{{#threetenbp}}
compile "org.threeten:threetenbp:1.3.8"
{{/threetenbp}}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,24 @@ package {{packageName}}.infrastructure

import okhttp3.OkHttpClient
import okhttp3.RequestBody
{{#jvm-okhttp3}}
import okhttp3.MediaType
{{/jvm-okhttp3}}
{{#jvm-okhttp4}}
import okhttp3.RequestBody.Companion.asRequestBody
import okhttp3.RequestBody.Companion.toRequestBody
{{/jvm-okhttp4}}
import okhttp3.FormBody
{{#jvm-okhttp3}}
import okhttp3.HttpUrl
{{/jvm-okhttp3}}
{{#jvm-okhttp4}}
import okhttp3.HttpUrl.Companion.toHttpUrlOrNull
{{/jvm-okhttp4}}
import okhttp3.ResponseBody
{{#jvm-okhttp4}}
import okhttp3.MediaType.Companion.toMediaTypeOrNull
{{/jvm-okhttp4}}
import okhttp3.Request
import java.io.File

Expand Down Expand Up @@ -38,9 +50,16 @@ open class ApiClient(val baseUrl: String) {

protected inline fun <reified T> requestBody(content: T, mediaType: String = JsonMediaType): RequestBody =
when {
{{#jvm-okhttp3}}
content is File -> RequestBody.create(
MediaType.parse(mediaType), content
)
{{/jvm-okhttp3}}
{{#jvm-okhttp4}}
content is File -> content.asRequestBody(
mediaType.toMediaTypeOrNull()
)
{{/jvm-okhttp4}}
mediaType == FormDataMediaType || mediaType == FormUrlEncMediaType -> {
FormBody.Builder().apply {
// content's type *must* be Map<String, Any>
Expand All @@ -50,9 +69,16 @@ open class ApiClient(val baseUrl: String) {
}
}.build()
}
{{#jvm-okhttp3}}
mediaType == JsonMediaType -> RequestBody.create(
MediaType.parse(mediaType), Serializer.moshi.adapter(T::class.java).toJson(content)
)
{{/jvm-okhttp3}}
{{#jvm-okhttp4}}
mediaType == JsonMediaType -> Serializer.moshi.adapter(T::class.java).toJson(content).toRequestBody(
mediaType.toMediaTypeOrNull()
)
{{/jvm-okhttp4}}
mediaType == XmlMediaType -> throw UnsupportedOperationException("xml not currently supported.")
// TODO: this should be extended with other serializers
else -> throw UnsupportedOperationException("requestBody currently only supports JSON body and File body.")
Expand Down Expand Up @@ -123,7 +149,12 @@ open class ApiClient(val baseUrl: String) {
{{/hasAuthMethods}}

protected inline fun <reified T: Any?> request(requestConfig: RequestConfig, body : Any? = null): ApiInfrastructureResponse<T?> {
{{#jvm-okhttp3}}
val httpUrl = HttpUrl.parse(baseUrl) ?: throw IllegalStateException("baseUrl is invalid.")
{{/jvm-okhttp3}}
{{#jvm-okhttp4}}
val httpUrl = baseUrl.toHttpUrlOrNull() ?: throw IllegalStateException("baseUrl is invalid.")
{{/jvm-okhttp4}}
{{#hasAuthMethods}}

// take authMethod from operation
Expand Down Expand Up @@ -178,29 +209,29 @@ open class ApiClient(val baseUrl: String) {
// TODO: handle specific mapping types. e.g. Map<int, Class<?>>
when {
response.isRedirect -> return Redirection(
response.code,
response.headers.toMultimap()
response.code{{#jvm-okhttp3}}(){{/jvm-okhttp3}},
response.headers{{#jvm-okhttp3}}(){{/jvm-okhttp3}}.toMultimap()
)
response.isInformational -> return Informational(
response.message,
response.code,
response.headers.toMultimap()
response.message{{#jvm-okhttp3}}(){{/jvm-okhttp3}},
response.code{{#jvm-okhttp3}}(){{/jvm-okhttp3}},
response.headers{{#jvm-okhttp3}}(){{/jvm-okhttp3}}.toMultimap()
)
response.isSuccessful -> return Success(
responseBody(response.body, accept),
response.code,
response.headers.toMultimap()
responseBody(response.body{{#jvm-okhttp3}}(){{/jvm-okhttp3}}, accept),
response.code{{#jvm-okhttp3}}(){{/jvm-okhttp3}},
response.headers{{#jvm-okhttp3}}(){{/jvm-okhttp3}}.toMultimap()
)
response.isClientError -> return ClientError(
response.body?.string(),
response.code,
response.headers.toMultimap()
response.body{{#jvm-okhttp3}}(){{/jvm-okhttp3}}?.string(),
response.code{{#jvm-okhttp3}}(){{/jvm-okhttp3}},
response.headers{{#jvm-okhttp3}}(){{/jvm-okhttp3}}.toMultimap()
)
else -> return ServerError(
null,
response.body?.string(),
response.code,
response.headers.toMultimap()
response.body{{#jvm-okhttp3}}(){{/jvm-okhttp3}}?.string(),
response.code{{#jvm-okhttp3}}(){{/jvm-okhttp3}},
response.headers{{#jvm-okhttp3}}(){{/jvm-okhttp3}}.toMultimap()
)
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,19 +5,19 @@ import okhttp3.Response
/**
* Provides an extension to evaluation whether the response is a 1xx code
*/
val Response.isInformational : Boolean get() = this.code in 100..199
val Response.isInformational : Boolean get() = this.code{{#jvm-okhttp3}}(){{/jvm-okhttp3}} in 100..199

/**
* Provides an extension to evaluation whether the response is a 3xx code
*/
val Response.isRedirect : Boolean get() = this.code in 300..399
val Response.isRedirect : Boolean get() = this.code{{#jvm-okhttp3}}(){{/jvm-okhttp3}} in 300..399

/**
* Provides an extension to evaluation whether the response is a 4xx code
*/
val Response.isClientError : Boolean get() = this.code in 400..499
val Response.isClientError : Boolean get() = this.code{{#jvm-okhttp3}}(){{/jvm-okhttp3}} in 400..499

/**
* Provides an extension to evaluation whether the response is a 5xx (Standard) through 999 (non-standard) code
*/
val Response.isServerError : Boolean get() = this.code in 500..999
val Response.isServerError : Boolean get() = this.code{{#jvm-okhttp3}}(){{/jvm-okhttp3}} in 500..999
23 changes: 23 additions & 0 deletions samples/client/petstore/kotlin-okhttp3/.openapi-generator-ignore
Original file line number Diff line number Diff line change
@@ -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
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
4.1.3-SNAPSHOT
90 changes: 90 additions & 0 deletions samples/client/petstore/kotlin-okhttp3/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,90 @@
# org.openapitools.client - Kotlin client library for OpenAPI Petstore

## Requires

* Kotlin 1.3.41
* Gradle 4.9

## Build

First, create the gradle wrapper script:

```
gradle wrapper
```

Then, run:

```
./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.
* Implementation of ApiClient is intended to reduce method counts, specifically to benefit Android targets.

<a name="documentation-for-api-endpoints"></a>
## Documentation for API Endpoints

All URIs are relative to *http://petstore.swagger.io/v2*

Class | Method | HTTP request | Description
------------ | ------------- | ------------- | -------------
*PetApi* | [**addPet**](docs/PetApi.md#addpet) | **POST** /pet | Add a new pet to the store
*PetApi* | [**deletePet**](docs/PetApi.md#deletepet) | **DELETE** /pet/{petId} | Deletes a pet
*PetApi* | [**findPetsByStatus**](docs/PetApi.md#findpetsbystatus) | **GET** /pet/findByStatus | Finds Pets by status
*PetApi* | [**findPetsByTags**](docs/PetApi.md#findpetsbytags) | **GET** /pet/findByTags | Finds Pets by tags
*PetApi* | [**getPetById**](docs/PetApi.md#getpetbyid) | **GET** /pet/{petId} | Find pet by ID
*PetApi* | [**updatePet**](docs/PetApi.md#updatepet) | **PUT** /pet | Update an existing pet
*PetApi* | [**updatePetWithForm**](docs/PetApi.md#updatepetwithform) | **POST** /pet/{petId} | Updates a pet in the store with form data
*PetApi* | [**uploadFile**](docs/PetApi.md#uploadfile) | **POST** /pet/{petId}/uploadImage | uploads an image
*StoreApi* | [**deleteOrder**](docs/StoreApi.md#deleteorder) | **DELETE** /store/order/{orderId} | Delete purchase order by ID
*StoreApi* | [**getInventory**](docs/StoreApi.md#getinventory) | **GET** /store/inventory | Returns pet inventories by status
*StoreApi* | [**getOrderById**](docs/StoreApi.md#getorderbyid) | **GET** /store/order/{orderId} | Find purchase order by ID
*StoreApi* | [**placeOrder**](docs/StoreApi.md#placeorder) | **POST** /store/order | Place an order for a pet
*UserApi* | [**createUser**](docs/UserApi.md#createuser) | **POST** /user | Create user
*UserApi* | [**createUsersWithArrayInput**](docs/UserApi.md#createuserswitharrayinput) | **POST** /user/createWithArray | Creates list of users with given input array
*UserApi* | [**createUsersWithListInput**](docs/UserApi.md#createuserswithlistinput) | **POST** /user/createWithList | Creates list of users with given input array
*UserApi* | [**deleteUser**](docs/UserApi.md#deleteuser) | **DELETE** /user/{username} | Delete user
*UserApi* | [**getUserByName**](docs/UserApi.md#getuserbyname) | **GET** /user/{username} | Get user by user name
*UserApi* | [**loginUser**](docs/UserApi.md#loginuser) | **GET** /user/login | Logs user into the system
*UserApi* | [**logoutUser**](docs/UserApi.md#logoutuser) | **GET** /user/logout | Logs out current logged in user session
*UserApi* | [**updateUser**](docs/UserApi.md#updateuser) | **PUT** /user/{username} | Updated user


<a name="documentation-for-models"></a>
## Documentation for Models

- [org.openapitools.client.models.ApiResponse](docs/ApiResponse.md)
- [org.openapitools.client.models.Category](docs/Category.md)
- [org.openapitools.client.models.Order](docs/Order.md)
- [org.openapitools.client.models.Pet](docs/Pet.md)
- [org.openapitools.client.models.Tag](docs/Tag.md)
- [org.openapitools.client.models.User](docs/User.md)


<a name="documentation-for-authorization"></a>
## Documentation for Authorization

<a name="api_key"></a>
### api_key

- **Type**: API key
- **API key parameter name**: api_key
- **Location**: HTTP header

<a name="petstore_auth"></a>
### petstore_auth

- **Type**: OAuth
- **Flow**: implicit
- **Authorization URL**: http://petstore.swagger.io/api/oauth/dialog
- **Scopes**:
- write:pets: modify pets in your account
- read:pets: read your pets

Loading