[Kotlin] Use mutable container types when 'modelMutable' is enabled (#11154)

* [Kotlin] Use Mutable container types when 'modelMutable' is enabled

* Generate sample 'kotlin' project with mutable models

* Generate sample 'kotlin-server' project with mutable models

* Generate sample 'kotlin-vertx' project with mutable models

* Generate sample 'ktorm-schema' project with mutable models

Co-authored-by: Bruno Coelho <4brunu@users.noreply.github.com>
This commit is contained in:
Armel Soro
2022-01-30 13:06:03 +01:00
committed by GitHub
parent f79ac98bc3
commit ed14ce4dec
128 changed files with 7665 additions and 12 deletions

View File

@@ -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

View File

@@ -0,0 +1,20 @@
Dockerfile
README.md
build.gradle
gradle.properties
settings.gradle
src/main/kotlin/org/openapitools/server/AppMain.kt
src/main/kotlin/org/openapitools/server/Configuration.kt
src/main/kotlin/org/openapitools/server/Paths.kt
src/main/kotlin/org/openapitools/server/apis/PetApi.kt
src/main/kotlin/org/openapitools/server/apis/StoreApi.kt
src/main/kotlin/org/openapitools/server/apis/UserApi.kt
src/main/kotlin/org/openapitools/server/infrastructure/ApiKeyAuth.kt
src/main/kotlin/org/openapitools/server/models/Category.kt
src/main/kotlin/org/openapitools/server/models/ModelApiResponse.kt
src/main/kotlin/org/openapitools/server/models/Order.kt
src/main/kotlin/org/openapitools/server/models/Pet.kt
src/main/kotlin/org/openapitools/server/models/Tag.kt
src/main/kotlin/org/openapitools/server/models/User.kt
src/main/resources/application.conf
src/main/resources/logback.xml

View File

@@ -0,0 +1 @@
5.4.0-SNAPSHOT

View File

@@ -0,0 +1,7 @@
FROM openjdk:8-jre-alpine
COPY ./build/libs/kotlin-server.jar /root/kotlin-server.jar
WORKDIR /root
CMD ["java", "-server", "-Xms4g", "-Xmx4g", "-XX:+UseG1GC", "-XX:MaxGCPauseMillis=100", "-XX:+UseStringDeduplication", "-jar", "kotlin-server.jar"]

View File

@@ -0,0 +1,104 @@
# org.openapitools.server - Kotlin Server library for OpenAPI Petstore
This is a sample server Petstore server. For this sample, you can use the api key &#x60;special-key&#x60; to test the authorization filters.
Generated by OpenAPI Generator 5.4.0-SNAPSHOT.
## Requires
* Kotlin 1.4.32
* Gradle 6.9
## Build
First, create the gradle wrapper script:
```
gradle wrapper
```
Then, run:
```
./gradlew check assemble
```
This runs all tests and packages the library.
## Running
The server builds as a fat jar with a main entrypoint. To start the service, run `java -jar ./build/libs/kotlin-server.jar`.
You may also run in docker:
```
docker build -t kotlin-server .
docker run -p 8080:8080 kotlin-server
```
## Features/Implementation Notes
* Supports JSON inputs/outputs, File inputs, and Form inputs (see ktor documentation for more info).
* ~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.
<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.server.models.Category](docs/Category.md)
- [org.openapitools.server.models.ModelApiResponse](docs/ModelApiResponse.md)
- [org.openapitools.server.models.Order](docs/Order.md)
- [org.openapitools.server.models.Pet](docs/Pet.md)
- [org.openapitools.server.models.Tag](docs/Tag.md)
- [org.openapitools.server.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

View File

@@ -0,0 +1,69 @@
group "org.openapitools"
version "1.0.0"
wrapper {
gradleVersion = "6.9"
distributionUrl = "https://services.gradle.org/distributions/gradle-$gradleVersion-all.zip"
}
buildscript {
ext.kotlin_version = "1.4.32"
ext.ktor_version = "1.5.4"
ext.shadow_version = "6.1.0"
repositories {
maven { url "https://repo1.maven.org/maven2" }
maven { url "https://plugins.gradle.org/m2/" }
}
dependencies {
classpath("org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version")
classpath("com.github.jengelman.gradle.plugins:shadow:$shadow_version")
}
}
apply plugin: "java"
apply plugin: "kotlin"
apply plugin: "application"
mainClassName = "io.ktor.server.netty.DevelopmentEngine"
// Initialization order with shadow 2.0.1 and Gradle 6.9 is weird.
// See https://github.com/johnrengelman/shadow/issues/336#issuecomment-355402508
apply plugin: "com.github.johnrengelman.shadow"
sourceCompatibility = 1.8
compileKotlin {
kotlinOptions.jvmTarget = "1.8"
}
compileTestKotlin {
kotlinOptions.jvmTarget = "1.8"
}
shadowJar {
baseName = "kotlin-server"
classifier = null
version = null
}
repositories {
maven { setUrl("https://repo1.maven.org/maven2") }
maven { setUrl("https://dl.bintray.com/kotlin/ktor") }
maven { setUrl("https://dl.bintray.com/kotlin/kotlinx") }
}
dependencies {
implementation("org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version")
implementation("ch.qos.logback:logback-classic:1.2.1")
implementation("com.typesafe:config:1.4.1")
implementation("io.ktor:ktor-auth:$ktor_version")
implementation("io.ktor:ktor-client-apache:$ktor_version")
implementation("io.ktor:ktor-gson:$ktor_version")
implementation("io.ktor:ktor-locations:$ktor_version")
implementation("io.dropwizard.metrics:metrics-core:4.1.18")
implementation("io.ktor:ktor-metrics:$ktor_version")
implementation("io.ktor:ktor-server-netty:$ktor_version")
testImplementation("junit:junit:4.13.2")
}

View File

@@ -0,0 +1 @@
org.gradle.caching=true

View File

@@ -0,0 +1 @@
rootProject.name = 'kotlin-server'

View File

@@ -0,0 +1,74 @@
package org.openapitools.server
import com.codahale.metrics.Slf4jReporter
import io.ktor.application.*
import io.ktor.features.*
import io.ktor.gson.*
import io.ktor.http.*
import io.ktor.locations.*
import io.ktor.metrics.dropwizard.*
import java.util.concurrent.TimeUnit
import io.ktor.routing.*
import io.ktor.util.*
import com.typesafe.config.ConfigFactory
import io.ktor.auth.*
import io.ktor.client.HttpClient
import io.ktor.client.engine.apache.Apache
import io.ktor.config.HoconApplicationConfig
import org.openapitools.server.infrastructure.*
import org.openapitools.server.apis.PetApi
import org.openapitools.server.apis.StoreApi
import org.openapitools.server.apis.UserApi
internal val settings = HoconApplicationConfig(ConfigFactory.defaultApplication(HTTP::class.java.classLoader))
object HTTP {
val client = HttpClient(Apache)
}
@KtorExperimentalAPI
@KtorExperimentalLocationsAPI
fun Application.main() {
install(DefaultHeaders)
install(DropwizardMetrics) {
val reporter = Slf4jReporter.forRegistry(registry)
.outputTo(log)
.convertRatesTo(TimeUnit.SECONDS)
.convertDurationsTo(TimeUnit.MILLISECONDS)
.build()
reporter.start(10, TimeUnit.SECONDS)
}
install(ContentNegotiation) {
register(ContentType.Application.Json, GsonConverter())
}
install(AutoHeadResponse) // see https://ktor.io/docs/autoheadresponse.html
install(Compression, ApplicationCompressionConfiguration()) // see https://ktor.io/docs/compression.html
install(HSTS, ApplicationHstsConfiguration()) // see https://ktor.io/docs/hsts.html
install(Locations) // see https://ktor.io/docs/features-locations.html
install(Authentication) {
// "Implement API key auth (api_key) for parameter name 'api_key'."
apiKeyAuth("api_key") {
validate { apikeyCredential: ApiKeyCredential ->
when {
apikeyCredential.value == "keyboardcat" -> ApiPrincipal(apikeyCredential)
else -> null
}
}
}
oauth("petstore_auth") {
client = HttpClient(Apache)
providerLookup = { ApplicationAuthProviders["petstore_auth"] }
urlProvider = { _ ->
// TODO: define a callback url here.
"/"
}
}
}
install(Routing) {
PetApi()
StoreApi()
UserApi()
}
}

View File

@@ -0,0 +1,71 @@
package org.openapitools.server
// Use this file to hold package-level internal functions that return receiver object passed to the `install` method.
import io.ktor.auth.*
import io.ktor.features.*
import io.ktor.http.*
import io.ktor.util.*
import java.time.Duration
import java.util.concurrent.TimeUnit
/**
* Application block for [HSTS] configuration.
*
* This file may be excluded in .openapi-generator-ignore,
* and application specific configuration can be applied in this function.
*
* See http://ktor.io/features/hsts.html
*/
internal fun ApplicationHstsConfiguration(): HSTS.Configuration.() -> Unit {
return {
maxAgeInSeconds = TimeUnit.DAYS.toSeconds(365)
includeSubDomains = true
preload = false
// You may also apply any custom directives supported by specific user-agent. For example:
// customDirectives.put("redirectHttpToHttps", "false")
}
}
/**
* Application block for [Compression] configuration.
*
* This file may be excluded in .openapi-generator-ignore,
* and application specific configuration can be applied in this function.
*
* See http://ktor.io/features/compression.html
*/
internal fun ApplicationCompressionConfiguration(): Compression.Configuration.() -> Unit {
return {
gzip {
priority = 1.0
}
deflate {
priority = 10.0
minimumSize(1024) // condition
}
}
}
// Defines authentication mechanisms used throughout the application.
val ApplicationAuthProviders: Map<String, OAuthServerSettings> = listOf<OAuthServerSettings>(
OAuthServerSettings.OAuth2ServerSettings(
name = "petstore_auth",
authorizeUrl = "http://petstore.swagger.io/api/oauth/dialog",
accessTokenUrl = "",
requestMethod = HttpMethod.Get,
clientId = settings.property("auth.oauth.petstore_auth.clientId").getString(),
clientSecret = settings.property("auth.oauth.petstore_auth.clientSecret").getString(),
defaultScopes = listOf("write:pets", "read:pets")
)
// OAuthServerSettings.OAuth2ServerSettings(
// name = "facebook",
// authorizeUrl = "https://graph.facebook.com/oauth/authorize",
// accessTokenUrl = "https://graph.facebook.com/oauth/access_token",
// requestMethod = HttpMethod.Post,
//
// clientId = settings.property("auth.oauth.facebook.clientId").getString(),
// clientSecret = settings.property("auth.oauth.facebook.clientSecret").getString(),
// defaultScopes = listOf("public_profile")
// )
).associateBy { it.name }

View File

@@ -0,0 +1,164 @@
/**
* OpenAPI Petstore
* This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters.
*
* The version of the OpenAPI document: 1.0.0
*
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
package org.openapitools.server
import io.ktor.locations.*
import org.openapitools.server.models.*
@KtorExperimentalLocationsAPI
object Paths {
/**
* Add a new pet to the store
*
* @param body Pet object that needs to be added to the store
*/
@Location("/pet") class addPet(val body: Pet)
/**
* Deletes a pet
*
* @param petId Pet id to delete
* @param apiKey (optional)
*/
@Location("/pet/{petId}") class deletePet(val petId: kotlin.Long, val apiKey: kotlin.String? = null)
/**
* Finds Pets by status
* Multiple status values can be provided with comma separated strings
* @param status Status values that need to be considered for filter
*/
@Location("/pet/findByStatus") class findPetsByStatus(val status: kotlin.collections.MutableList<kotlin.String>)
/**
* Finds Pets by tags
* Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing.
* @param tags Tags to filter by
*/
@Location("/pet/findByTags") class findPetsByTags(val tags: kotlin.collections.MutableList<kotlin.String>)
/**
* Find pet by ID
* Returns a single pet
* @param petId ID of pet to return
*/
@Location("/pet/{petId}") class getPetById(val petId: kotlin.Long)
/**
* Update an existing pet
*
* @param body Pet object that needs to be added to the store
*/
@Location("/pet") class updatePet(val body: Pet)
/**
* Updates a pet in the store with form data
*
* @param petId ID of pet that needs to be updated
* @param name Updated name of the pet (optional)
* @param status Updated status of the pet (optional)
*/
@Location("/pet/{petId}") class updatePetWithForm(val petId: kotlin.Long, val name: kotlin.String? = null, val status: kotlin.String? = null)
/**
* uploads an image
*
* @param petId ID of pet to update
* @param additionalMetadata Additional data to pass to server (optional)
* @param file file to upload (optional)
*/
@Location("/pet/{petId}/uploadImage") class uploadFile(val petId: kotlin.Long, val additionalMetadata: kotlin.String? = null, val file: java.io.File? = null)
/**
* Delete purchase order by ID
* For valid response try integer IDs with value &lt; 1000. Anything above 1000 or nonintegers will generate API errors
* @param orderId ID of the order that needs to be deleted
*/
@Location("/store/order/{orderId}") class deleteOrder(val orderId: kotlin.String)
/**
* Returns pet inventories by status
* Returns a map of status codes to quantities
*/
@Location("/store/inventory") object getInventory
/**
* Find purchase order by ID
* For valid response try integer IDs with value &lt;&#x3D; 5 or &gt; 10. Other values will generated exceptions
* @param orderId ID of pet that needs to be fetched
*/
@Location("/store/order/{orderId}") class getOrderById(val orderId: kotlin.Long)
/**
* Place an order for a pet
*
* @param body order placed for purchasing the pet
*/
@Location("/store/order") class placeOrder(val body: Order)
/**
* Create user
* This can only be done by the logged in user.
* @param body Created user object
*/
@Location("/user") class createUser(val body: User)
/**
* Creates list of users with given input array
*
* @param body List of user object
*/
@Location("/user/createWithArray") class createUsersWithArrayInput(val body: kotlin.collections.MutableList<User>)
/**
* Creates list of users with given input array
*
* @param body List of user object
*/
@Location("/user/createWithList") class createUsersWithListInput(val body: kotlin.collections.MutableList<User>)
/**
* Delete user
* This can only be done by the logged in user.
* @param username The name that needs to be deleted
*/
@Location("/user/{username}") class deleteUser(val username: kotlin.String)
/**
* Get user by user name
*
* @param username The name that needs to be fetched. Use user1 for testing.
*/
@Location("/user/{username}") class getUserByName(val username: kotlin.String)
/**
* Logs user into the system
*
* @param username The user name for login
* @param password The password for login in clear text
*/
@Location("/user/login") class loginUser(val username: kotlin.String, val password: kotlin.String)
/**
* Logs out current logged in user session
*
*/
@Location("/user/logout") object logoutUser
/**
* Updated user
* This can only be done by the logged in user.
* @param username name that need to be deleted
* @param body Updated user object
*/
@Location("/user/{username}") class updateUser(val username: kotlin.String, val body: User)
}

View File

@@ -0,0 +1,175 @@
/**
* OpenAPI Petstore
* This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters.
*
* The version of the OpenAPI document: 1.0.0
*
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
package org.openapitools.server.apis
import com.google.gson.Gson
import io.ktor.application.*
import io.ktor.auth.*
import io.ktor.http.*
import io.ktor.response.*
import org.openapitools.server.Paths
import io.ktor.locations.*
import io.ktor.routing.*
import org.openapitools.server.infrastructure.ApiPrincipal
import org.openapitools.server.models.ModelApiResponse
import org.openapitools.server.models.Pet
@KtorExperimentalLocationsAPI
fun Route.PetApi() {
val gson = Gson()
val empty = mutableMapOf<String, Any?>()
authenticate("petstore_auth") {
post<Paths.addPet> {
val principal = call.authentication.principal<OAuthAccessTokenResponse>()!!
call.respond(HttpStatusCode.NotImplemented)
}
}
authenticate("petstore_auth") {
delete<Paths.deletePet> {
val principal = call.authentication.principal<OAuthAccessTokenResponse>()!!
call.respond(HttpStatusCode.NotImplemented)
}
}
authenticate("petstore_auth") {
get<Paths.findPetsByStatus> {
val principal = call.authentication.principal<OAuthAccessTokenResponse>()!!
val exampleContentType = "application/json"
val exampleContentString = """{
"photoUrls" : [ "photoUrls", "photoUrls" ],
"name" : "doggie",
"id" : 0,
"category" : {
"name" : "name",
"id" : 6
},
"tags" : [ {
"name" : "name",
"id" : 1
}, {
"name" : "name",
"id" : 1
} ],
"status" : "available"
}"""
when (exampleContentType) {
"application/json" -> call.respond(gson.fromJson(exampleContentString, empty::class.java))
"application/xml" -> call.respondText(exampleContentString, ContentType.Text.Xml)
else -> call.respondText(exampleContentString)
}
}
}
authenticate("petstore_auth") {
get<Paths.findPetsByTags> {
val principal = call.authentication.principal<OAuthAccessTokenResponse>()!!
val exampleContentType = "application/json"
val exampleContentString = """{
"photoUrls" : [ "photoUrls", "photoUrls" ],
"name" : "doggie",
"id" : 0,
"category" : {
"name" : "name",
"id" : 6
},
"tags" : [ {
"name" : "name",
"id" : 1
}, {
"name" : "name",
"id" : 1
} ],
"status" : "available"
}"""
when (exampleContentType) {
"application/json" -> call.respond(gson.fromJson(exampleContentString, empty::class.java))
"application/xml" -> call.respondText(exampleContentString, ContentType.Text.Xml)
else -> call.respondText(exampleContentString)
}
}
}
authenticate("api_key") {
get<Paths.getPetById> {
val principal = call.authentication.principal<ApiPrincipal>()!!
val exampleContentType = "application/json"
val exampleContentString = """{
"photoUrls" : [ "photoUrls", "photoUrls" ],
"name" : "doggie",
"id" : 0,
"category" : {
"name" : "name",
"id" : 6
},
"tags" : [ {
"name" : "name",
"id" : 1
}, {
"name" : "name",
"id" : 1
} ],
"status" : "available"
}"""
when (exampleContentType) {
"application/json" -> call.respond(gson.fromJson(exampleContentString, empty::class.java))
"application/xml" -> call.respondText(exampleContentString, ContentType.Text.Xml)
else -> call.respondText(exampleContentString)
}
}
}
authenticate("petstore_auth") {
put<Paths.updatePet> {
val principal = call.authentication.principal<OAuthAccessTokenResponse>()!!
call.respond(HttpStatusCode.NotImplemented)
}
}
authenticate("petstore_auth") {
post<Paths.updatePetWithForm> {
val principal = call.authentication.principal<OAuthAccessTokenResponse>()!!
call.respond(HttpStatusCode.NotImplemented)
}
}
authenticate("petstore_auth") {
post<Paths.uploadFile> {
val principal = call.authentication.principal<OAuthAccessTokenResponse>()!!
val exampleContentType = "application/json"
val exampleContentString = """{
"code" : 0,
"type" : "type",
"message" : "message"
}"""
when (exampleContentType) {
"application/json" -> call.respond(gson.fromJson(exampleContentString, empty::class.java))
"application/xml" -> call.respondText(exampleContentString, ContentType.Text.Xml)
else -> call.respondText(exampleContentString)
}
}
}
}

View File

@@ -0,0 +1,78 @@
/**
* OpenAPI Petstore
* This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters.
*
* The version of the OpenAPI document: 1.0.0
*
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
package org.openapitools.server.apis
import com.google.gson.Gson
import io.ktor.application.*
import io.ktor.auth.*
import io.ktor.http.*
import io.ktor.response.*
import org.openapitools.server.Paths
import io.ktor.locations.*
import io.ktor.routing.*
import org.openapitools.server.infrastructure.ApiPrincipal
import org.openapitools.server.models.Order
@KtorExperimentalLocationsAPI
fun Route.StoreApi() {
val gson = Gson()
val empty = mutableMapOf<String, Any?>()
delete<Paths.deleteOrder> {
call.respond(HttpStatusCode.NotImplemented)
}
authenticate("api_key") {
get<Paths.getInventory> {
val principal = call.authentication.principal<ApiPrincipal>()!!
call.respond(HttpStatusCode.NotImplemented)
}
}
get<Paths.getOrderById> {
val exampleContentType = "application/json"
val exampleContentString = """{
"petId" : 6,
"quantity" : 1,
"id" : 0,
"shipDate" : "2000-01-23T04:56:07.000+00:00",
"complete" : false,
"status" : "placed"
}"""
when (exampleContentType) {
"application/json" -> call.respond(gson.fromJson(exampleContentString, empty::class.java))
"application/xml" -> call.respondText(exampleContentString, ContentType.Text.Xml)
else -> call.respondText(exampleContentString)
}
}
post<Paths.placeOrder> {
val exampleContentType = "application/json"
val exampleContentString = """{
"petId" : 6,
"quantity" : 1,
"id" : 0,
"shipDate" : "2000-01-23T04:56:07.000+00:00",
"complete" : false,
"status" : "placed"
}"""
when (exampleContentType) {
"application/json" -> call.respond(gson.fromJson(exampleContentString, empty::class.java))
"application/xml" -> call.respondText(exampleContentString, ContentType.Text.Xml)
else -> call.respondText(exampleContentString)
}
}
}

View File

@@ -0,0 +1,78 @@
/**
* OpenAPI Petstore
* This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters.
*
* The version of the OpenAPI document: 1.0.0
*
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
package org.openapitools.server.apis
import com.google.gson.Gson
import io.ktor.application.*
import io.ktor.auth.*
import io.ktor.http.*
import io.ktor.response.*
import org.openapitools.server.Paths
import io.ktor.locations.*
import io.ktor.routing.*
import org.openapitools.server.infrastructure.ApiPrincipal
import org.openapitools.server.models.User
@KtorExperimentalLocationsAPI
fun Route.UserApi() {
val gson = Gson()
val empty = mutableMapOf<String, Any?>()
post<Paths.createUser> {
call.respond(HttpStatusCode.NotImplemented)
}
post<Paths.createUsersWithArrayInput> {
call.respond(HttpStatusCode.NotImplemented)
}
post<Paths.createUsersWithListInput> {
call.respond(HttpStatusCode.NotImplemented)
}
delete<Paths.deleteUser> {
call.respond(HttpStatusCode.NotImplemented)
}
get<Paths.getUserByName> {
val exampleContentType = "application/json"
val exampleContentString = """{
"firstName" : "firstName",
"lastName" : "lastName",
"password" : "password",
"userStatus" : 6,
"phone" : "phone",
"id" : 0,
"email" : "email",
"username" : "username"
}"""
when (exampleContentType) {
"application/json" -> call.respond(gson.fromJson(exampleContentString, empty::class.java))
"application/xml" -> call.respondText(exampleContentString, ContentType.Text.Xml)
else -> call.respondText(exampleContentString)
}
}
get<Paths.loginUser> {
call.respond(HttpStatusCode.NotImplemented)
}
get<Paths.logoutUser> {
call.respond(HttpStatusCode.NotImplemented)
}
put<Paths.updateUser> {
call.respond(HttpStatusCode.NotImplemented)
}
}

View File

@@ -0,0 +1,105 @@
package org.openapitools.server.infrastructure
import io.ktor.application.*
import io.ktor.auth.*
import io.ktor.http.auth.*
import io.ktor.request.*
import io.ktor.response.*
enum class ApiKeyLocation(val location: String) {
QUERY("query"),
HEADER("header")
}
data class ApiKeyCredential(val value: String) : Credential
data class ApiPrincipal(val apiKeyCredential: ApiKeyCredential?) : Principal
/**
* Represents a Api Key authentication provider
* @param name is the name of the provider, or `null` for a default provider
*/
class ApiKeyAuthenticationProvider(configuration: Configuration) : AuthenticationProvider(configuration) {
private val authenticationFunction = configuration.authenticationFunction
private val apiKeyName: String = configuration.apiKeyName
private val apiKeyLocation: ApiKeyLocation = configuration.apiKeyLocation
internal fun install() {
pipeline.intercept(AuthenticationPipeline.RequestAuthentication) { context ->
val credentials = call.request.apiKeyAuthenticationCredentials(apiKeyName, apiKeyLocation)
val principal = credentials?.let { authenticationFunction(call, it) }
val cause = when {
credentials == null -> AuthenticationFailedCause.NoCredentials
principal == null -> AuthenticationFailedCause.InvalidCredentials
else -> null
}
if (cause != null) {
context.challenge(apiKeyName, cause) {
call.respond(
UnauthorizedResponse(
HttpAuthHeader.Parameterized(
"API_KEY",
mapOf("key" to apiKeyName),
HeaderValueEncoding.QUOTED_ALWAYS
)
)
)
it.complete()
}
}
if (principal != null) {
context.principal(principal)
}
}
}
class Configuration internal constructor(name: String?) : AuthenticationProvider.Configuration(name) {
internal var authenticationFunction: suspend ApplicationCall.(ApiKeyCredential) -> Principal? = {
throw NotImplementedError(
"Api Key auth validate function is not specified. Use apiKeyAuth { validate { ... } } to fix."
)
}
var apiKeyName: String = ""
var apiKeyLocation: ApiKeyLocation = ApiKeyLocation.QUERY
/**
* Sets a validation function that will check given [ApiKeyCredential] instance and return [Principal],
* or null if credential does not correspond to an authenticated principal
*/
fun validate(body: suspend ApplicationCall.(ApiKeyCredential) -> Principal?) {
authenticationFunction = body
}
}
}
fun Authentication.Configuration.apiKeyAuth(
name: String? = null,
configure: ApiKeyAuthenticationProvider.Configuration.() -> Unit
) {
val configuration = ApiKeyAuthenticationProvider.Configuration(name).apply(configure)
val provider = ApiKeyAuthenticationProvider(configuration)
provider.install()
register(provider)
}
fun ApplicationRequest.apiKeyAuthenticationCredentials(
apiKeyName: String,
apiKeyLocation: ApiKeyLocation
): ApiKeyCredential? {
val value: String? = when (apiKeyLocation) {
ApiKeyLocation.QUERY -> this.queryParameters[apiKeyName]
ApiKeyLocation.HEADER -> this.headers[apiKeyName]
}
return when (value) {
null -> null
else -> ApiKeyCredential(value)
}
}

View File

@@ -0,0 +1,24 @@
/**
* OpenAPI Petstore
* This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters.
*
* The version of the OpenAPI document: 1.0.0
*
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
package org.openapitools.server.models
/**
* A category for a pet
* @param id
* @param name
*/
data class Category(
var id: kotlin.Long? = null,
var name: kotlin.String? = null
)

View File

@@ -0,0 +1,26 @@
/**
* OpenAPI Petstore
* This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters.
*
* The version of the OpenAPI document: 1.0.0
*
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
package org.openapitools.server.models
/**
* Describes the result of uploading an image resource
* @param code
* @param type
* @param message
*/
data class ModelApiResponse(
var code: kotlin.Int? = null,
var type: kotlin.String? = null,
var message: kotlin.String? = null
)

View File

@@ -0,0 +1,44 @@
/**
* OpenAPI Petstore
* This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters.
*
* The version of the OpenAPI document: 1.0.0
*
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
package org.openapitools.server.models
/**
* An order for a pets from the pet store
* @param id
* @param petId
* @param quantity
* @param shipDate
* @param status Order Status
* @param complete
*/
data class Order(
var id: kotlin.Long? = null,
var petId: kotlin.Long? = null,
var quantity: kotlin.Int? = null,
var shipDate: java.time.OffsetDateTime? = null,
/* Order Status */
var status: Order.Status? = null,
var complete: kotlin.Boolean? = false
)
{
/**
* Order Status
* Values: placed,approved,delivered
*/
enum class Status(val value: kotlin.String){
placed("placed"),
approved("approved"),
delivered("delivered");
}
}

View File

@@ -0,0 +1,46 @@
/**
* OpenAPI Petstore
* This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters.
*
* The version of the OpenAPI document: 1.0.0
*
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
package org.openapitools.server.models
import org.openapitools.server.models.Category
import org.openapitools.server.models.Tag
/**
* A pet for sale in the pet store
* @param name
* @param photoUrls
* @param id
* @param category
* @param tags
* @param status pet status in the store
*/
data class Pet(
var name: kotlin.String,
var photoUrls: kotlin.collections.MutableList<kotlin.String>,
var id: kotlin.Long? = null,
var category: Category? = null,
var tags: kotlin.collections.MutableList<Tag>? = null,
/* pet status in the store */
var status: Pet.Status? = null
)
{
/**
* pet status in the store
* Values: available,pending,sold
*/
enum class Status(val value: kotlin.String){
available("available"),
pending("pending"),
sold("sold");
}
}

View File

@@ -0,0 +1,24 @@
/**
* OpenAPI Petstore
* This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters.
*
* The version of the OpenAPI document: 1.0.0
*
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
package org.openapitools.server.models
/**
* A tag for a pet
* @param id
* @param name
*/
data class Tag(
var id: kotlin.Long? = null,
var name: kotlin.String? = null
)

View File

@@ -0,0 +1,37 @@
/**
* OpenAPI Petstore
* This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters.
*
* The version of the OpenAPI document: 1.0.0
*
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
package org.openapitools.server.models
/**
* A User who is purchasing from the pet store
* @param id
* @param username
* @param firstName
* @param lastName
* @param email
* @param password
* @param phone
* @param userStatus User Status
*/
data class User(
var id: kotlin.Long? = null,
var username: kotlin.String? = null,
var firstName: kotlin.String? = null,
var lastName: kotlin.String? = null,
var email: kotlin.String? = null,
var password: kotlin.String? = null,
var phone: kotlin.String? = null,
/* User Status */
var userStatus: kotlin.Int? = null
)

View File

@@ -0,0 +1,23 @@
ktor {
deployment {
environment = development
port = 8080
autoreload = true
watch = [ org.openapitools.server ]
}
application {
modules = [ org.openapitools.server.AppMainKt.main ]
}
}
# Typesafe config allows multiple ways to provide configuration values without hard-coding them here.
# Please see https://github.com/lightbend/config for details.
auth {
oauth {
petstore_auth {
clientId = ""
clientSecret = ""
}
}
}

View File

@@ -0,0 +1,15 @@
<configuration>
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>%d{YYYY-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n</pattern>
</encoder>
</appender>
<root level="trace">
<appender-ref ref="STDOUT"/>
</root>
<logger name="org.eclipse.jetty" level="INFO"/>
<logger name="io.netty" level="INFO"/>
</configuration>