Add Ktorm schema generator (#7759)

* [ktorm] added support for ktorm

* [ktorm] fixed type mapping

* [ktorm] fixed foreign key

* [ktorm] added variable for the missing package import

* [ktorm] added correct templates

* [ktorm] added relationship metadata

* [ktorm] also support relationships 1:m

* [ktorm] relation to primitive naming fix

* [ktorm] updated mustache templates

* [ktorm] small fixes on templates, assigmentbuilder, docs, sql script syntax.

* fix issue, rename to ktorm-schema

* replace tabs with 4 spaces

* [ktorm] added primarykey automatic generation

* [ktorm] added tests

* [ktorm] added gradle to samples

* [ktorm] fix datatime type

* [ktorm] template fixes array and primarykey

* [ktorm][sample] regenerate

* [ktorm][sample] added manually files from kotlin-client

We inherit from baseTable, so we need those for now

* [ktorm] fix: relation column types hardcoded

* update samples

* update doc

Co-authored-by: William Cheng <wing328hk@gmail.com>
This commit is contained in:
Luiz Felipe Stangarlin 2021-01-06 03:04:49 -06:00 committed by GitHub
parent ae563bcf91
commit 319bd7eaa8
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
307 changed files with 21819 additions and 0 deletions

View File

@ -0,0 +1,7 @@
generatorName: ktorm-schema
outputDir: samples/schema/petstore/ktorm
inputSpec: modules/openapi-generator/src/test/resources/2_0/petstore.yaml
templateDir: modules/openapi-generator/src/main/resources/ktorm-schema
additionalProperties:
hideGenerationTimestamp: true
importModelPackageName: org.openapitools.client.models

View File

@ -141,6 +141,7 @@ The following generators are available:
## SCHEMA generators
* [avro-schema (beta)](generators/avro-schema.md)
* [graphql-schema](generators/graphql-schema.md)
* [ktorm-schema (beta)](generators/ktorm-schema.md)
* [mysql-schema](generators/mysql-schema.md)
* [protobuf-schema (beta)](generators/protobuf-schema.md)

View File

@ -0,0 +1,355 @@
---
title: Config Options for ktorm-schema
sidebar_label: ktorm-schema
---
These options may be applied as additional-properties (cli) or configOptions (plugins). Refer to [configuration docs](https://openapi-generator.tech/docs/configuration) for more details.
| Option | Description | Values | Default |
| ------ | ----------- | ------ | ------- |
|addSurrogateKey|Adds the surrogate key for all models that don't already have a primary key (named by the above convention)| |false|
|artifactId|Generated artifact id (name of jar).| |ktorm|
|artifactVersion|Generated artifact's package version.| |1.0.0|
|defaultDatabaseName|Default database name for all queries| |sqlite.db|
|enumPropertyNaming|Naming convention for enum properties: 'camelCase', 'PascalCase', 'snake_case', 'UPPERCASE', and 'original'| |camelCase|
|groupId|Generated artifact package's organization (i.e. maven groupId).| |org.openapitools|
|identifierNamingConvention|Naming convention of Ktorm identifiers(table names and column names). This is not related to database name which is defined by defaultDatabaseName option|<dl><dt>**original**</dt><dd>Do not transform original names</dd><dt>**snake_case**</dt><dd>Use snake_case names</dd></dl>|original|
|importModelPackageName|Package name of the imported models| |org.openapitools.database.models|
|modelMutable|Create mutable models| |false|
|packageName|Generated artifact package name.| |org.openapitools.database|
|primaryKeyConvention|Primary key naming convention| |id|
|sortModelPropertiesByRequiredFlag|Sort model properties to place required parameters before optional parameters.| |null|
|sortParamsByRequiredFlag|Sort method arguments to place required parameters before optional parameters.| |null|
|sourceFolder|source folder for generated code| |src/main/kotlin|
## IMPORT MAPPING
| Type/Alias | Imports |
| ---------- | ------- |
|BigDecimal|java.math.BigDecimal|
|Date|java.util.Date|
|DateTime|java.time.LocalDateTime|
|File|java.io.File|
|LocalDate|java.time.LocalDate|
|LocalDateTime|java.time.LocalDateTime|
|LocalTime|java.time.LocalTime|
|Timestamp|java.sql.Timestamp|
|URI|java.net.URI|
|UUID|java.util.UUID|
## INSTANTIATION TYPES
| Type/Alias | Instantiated By |
| ---------- | --------------- |
|array|kotlin.collections.ArrayList|
|list|kotlin.collections.ArrayList|
|map|kotlin.collections.HashMap|
## LANGUAGE PRIMITIVES
<ul class="column-ul">
<li>kotlin.Array</li>
<li>kotlin.Boolean</li>
<li>kotlin.Byte</li>
<li>kotlin.ByteArray</li>
<li>kotlin.Char</li>
<li>kotlin.Double</li>
<li>kotlin.Float</li>
<li>kotlin.Int</li>
<li>kotlin.Long</li>
<li>kotlin.Short</li>
<li>kotlin.String</li>
<li>kotlin.collections.List</li>
<li>kotlin.collections.Map</li>
<li>kotlin.collections.Set</li>
</ul>
## RESERVED WORDS
<ul class="column-ul">
<li>abort</li>
<li>action</li>
<li>add</li>
<li>after</li>
<li>all</li>
<li>alter</li>
<li>always</li>
<li>analyze</li>
<li>and</li>
<li>any</li>
<li>as</li>
<li>asc</li>
<li>attach</li>
<li>autoincr</li>
<li>autoincrement</li>
<li>before</li>
<li>begin</li>
<li>between</li>
<li>bitand</li>
<li>bitnot</li>
<li>bitor</li>
<li>blob</li>
<li>by</li>
<li>cascade</li>
<li>case</li>
<li>cast</li>
<li>check</li>
<li>collate</li>
<li>column</li>
<li>comma</li>
<li>commit</li>
<li>concat</li>
<li>conflict</li>
<li>constraint</li>
<li>create</li>
<li>cross</li>
<li>current</li>
<li>current_date</li>
<li>current_time</li>
<li>current_timestamp</li>
<li>database</li>
<li>default</li>
<li>deferrable</li>
<li>deferred</li>
<li>delete</li>
<li>desc</li>
<li>detach</li>
<li>distinct</li>
<li>do</li>
<li>dot</li>
<li>drop</li>
<li>each</li>
<li>else</li>
<li>end</li>
<li>eq</li>
<li>escape</li>
<li>except</li>
<li>exclude</li>
<li>exclusive</li>
<li>exists</li>
<li>explain</li>
<li>fail</li>
<li>filter</li>
<li>first</li>
<li>float</li>
<li>following</li>
<li>for</li>
<li>foreign</li>
<li>from</li>
<li>full</li>
<li>ge</li>
<li>generated</li>
<li>glob</li>
<li>group</li>
<li>groups</li>
<li>gt</li>
<li>having</li>
<li>id</li>
<li>if</li>
<li>ignore</li>
<li>immediate</li>
<li>in</li>
<li>index</li>
<li>indexed</li>
<li>initially</li>
<li>inner</li>
<li>insert</li>
<li>instead</li>
<li>integer</li>
<li>intersect</li>
<li>into</li>
<li>is</li>
<li>isnull</li>
<li>join</li>
<li>key</li>
<li>last</li>
<li>le</li>
<li>left</li>
<li>like</li>
<li>limit</li>
<li>lp</li>
<li>lshift</li>
<li>lt</li>
<li>match</li>
<li>minus</li>
<li>natural</li>
<li>ne</li>
<li>no</li>
<li>not</li>
<li>nothing</li>
<li>notnull</li>
<li>null</li>
<li>nulls</li>
<li>of</li>
<li>offset</li>
<li>on</li>
<li>or</li>
<li>order</li>
<li>others</li>
<li>outer</li>
<li>over</li>
<li>partition</li>
<li>plan</li>
<li>plus</li>
<li>pragma</li>
<li>preceding</li>
<li>primary</li>
<li>query</li>
<li>raise</li>
<li>range</li>
<li>recursive</li>
<li>references</li>
<li>regexp</li>
<li>reindex</li>
<li>release</li>
<li>rem</li>
<li>rename</li>
<li>replace</li>
<li>restrict</li>
<li>right</li>
<li>rollback</li>
<li>row</li>
<li>rows</li>
<li>rp</li>
<li>rshift</li>
<li>savepoint</li>
<li>select</li>
<li>set</li>
<li>slash</li>
<li>star</li>
<li>string</li>
<li>table</li>
<li>temp</li>
<li>temporary</li>
<li>then</li>
<li>ties</li>
<li>to</li>
<li>transaction</li>
<li>trigger</li>
<li>unbounded</li>
<li>union</li>
<li>unique</li>
<li>update</li>
<li>using</li>
<li>vacuum</li>
<li>values</li>
<li>variable</li>
<li>view</li>
<li>virtual</li>
<li>when</li>
<li>where</li>
<li>window</li>
<li>with</li>
<li>without</li>
</ul>
## FEATURE SET
### Client Modification Feature
| Name | Supported | Defined By |
| ---- | --------- | ---------- |
|BasePath|✗|ToolingExtension
|Authorizations|✗|ToolingExtension
|UserAgent|✗|ToolingExtension
|MockServer|✗|ToolingExtension
### Data Type Feature
| Name | Supported | Defined By |
| ---- | --------- | ---------- |
|Custom|✗|OAS2,OAS3
|Int32|✓|OAS2,OAS3
|Int64|✓|OAS2,OAS3
|Float|✓|OAS2,OAS3
|Double|✓|OAS2,OAS3
|Decimal|✓|ToolingExtension
|String|✓|OAS2,OAS3
|Byte|✓|OAS2,OAS3
|Binary|✓|OAS2,OAS3
|Boolean|✓|OAS2,OAS3
|Date|✓|OAS2,OAS3
|DateTime|✓|OAS2,OAS3
|Password|✓|OAS2,OAS3
|File|✓|OAS2
|Array|✓|OAS2,OAS3
|Maps|✓|ToolingExtension
|CollectionFormat|✓|OAS2
|CollectionFormatMulti|✓|OAS2
|Enum|✓|OAS2,OAS3
|ArrayOfEnum|✓|ToolingExtension
|ArrayOfModel|✓|ToolingExtension
|ArrayOfCollectionOfPrimitives|✓|ToolingExtension
|ArrayOfCollectionOfModel|✓|ToolingExtension
|ArrayOfCollectionOfEnum|✓|ToolingExtension
|MapOfEnum|✓|ToolingExtension
|MapOfModel|✓|ToolingExtension
|MapOfCollectionOfPrimitives|✓|ToolingExtension
|MapOfCollectionOfModel|✓|ToolingExtension
|MapOfCollectionOfEnum|✓|ToolingExtension
### Documentation Feature
| Name | Supported | Defined By |
| ---- | --------- | ---------- |
|Readme|✓|ToolingExtension
|Model|✓|ToolingExtension
|Api|✓|ToolingExtension
### Global Feature
| Name | Supported | Defined By |
| ---- | --------- | ---------- |
|Host|✓|OAS2,OAS3
|BasePath|✓|OAS2,OAS3
|Info|✓|OAS2,OAS3
|Schemes|✗|OAS2,OAS3
|PartialSchemes|✓|OAS2,OAS3
|Consumes|✓|OAS2
|Produces|✓|OAS2
|ExternalDocumentation|✓|OAS2,OAS3
|Examples|✓|OAS2,OAS3
|XMLStructureDefinitions|✗|OAS2,OAS3
|MultiServer|✗|OAS3
|ParameterizedServer|✗|OAS3
|ParameterStyling|✗|OAS3
|Callbacks|✗|OAS3
|LinkObjects|✗|OAS3
### Parameter Feature
| Name | Supported | Defined By |
| ---- | --------- | ---------- |
|Path|✓|OAS2,OAS3
|Query|✓|OAS2,OAS3
|Header|✓|OAS2,OAS3
|Body|✓|OAS2
|FormUnencoded|✓|OAS2
|FormMultipart|✓|OAS2
|Cookie|✓|OAS3
### Schema Support Feature
| Name | Supported | Defined By |
| ---- | --------- | ---------- |
|Simple|✓|OAS2,OAS3
|Composite|✓|OAS2,OAS3
|Polymorphism|✗|OAS2,OAS3
|Union|✗|OAS3
### Security Feature
| Name | Supported | Defined By |
| ---- | --------- | ---------- |
|BasicAuth|✗|OAS2,OAS3
|ApiKey|✗|OAS2,OAS3
|OpenIDConnect|✗|OAS3
|BearerToken|✗|OAS3
|OAuth2_Implicit|✗|OAS2,OAS3
|OAuth2_Password|✗|OAS2,OAS3
|OAuth2_ClientCredentials|✗|OAS2,OAS3
|OAuth2_AuthorizationCode|✗|OAS2,OAS3
### Wire Format Feature
| Name | Supported | Defined By |
| ---- | --------- | ---------- |
|JSON|✗|OAS2,OAS3
|XML|✗|OAS2,OAS3
|PROTOBUF|✗|ToolingExtension
|Custom|✗|OAS2,OAS3

View File

@ -44,6 +44,7 @@ org.openapitools.codegen.languages.KotlinClientCodegen
org.openapitools.codegen.languages.KotlinServerCodegen
org.openapitools.codegen.languages.KotlinSpringServerCodegen
org.openapitools.codegen.languages.KotlinVertxServerCodegen
org.openapitools.codegen.languages.KtormSchemaCodegen
org.openapitools.codegen.languages.HaskellHttpClientCodegen
org.openapitools.codegen.languages.HaskellServantCodegen
org.openapitools.codegen.languages.JavaClientCodegen

View File

@ -0,0 +1,48 @@
# {{packageName}} - Kotlin database library for {{appName}}
## Requires
{{#jvm}}
* Kotlin 1.3.61
* Gradle 4.9
{{/jvm}}
{{#multiplatform}}
* Kotlin 1.3.50
{{/multiplatform}}
## Build
{{#jvm}}
First, create the gradle wrapper script:
```
gradle wrapper
```
Then, run:
{{/jvm}}
```
./gradlew check assemble
```
This runs all tests and packages the library.
## Features/Implementation Notes
* Some Kotlin and Java types are fully qualified to avoid conflicts with types defined in OpenAPI definitions.
* Supports Mapper using API model classes.
* Supports SQLite types.
{{#generateModelDocs}}
<a name="documentation-for-models"></a>
## Documentation for Models
{{#modelPackage}}
{{#models}}{{#model}} - [{{{modelPackage}}}.{{{classname}}}]({{modelDocPath}}{{{classname}}}.md)
{{/model}}{{/models}}
{{/modelPackage}}
{{^modelPackage}}
No model defined in this package
{{/modelPackage}}
{{/generateModelDocs}}

View File

@ -0,0 +1,35 @@
group '{{groupId}}'
version '{{artifactVersion}}'
wrapper {
gradleVersion = '4.9'
distributionUrl = "https://services.gradle.org/distributions/gradle-$gradleVersion-all.zip"
}
buildscript {
ext.kotlin_version = '1.3.72'
ext.ktorm_version = '3.2.0'
repositories {
maven { url "https://repo1.maven.org/maven2" }
}
dependencies {
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
}
}
apply plugin: 'kotlin'
repositories {
maven { url "https://repo1.maven.org/maven2" }
}
test {
useJUnitPlatform()
}
dependencies {
implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk8:$kotlin_version"
implementation "org.ktorm:ktorm-core:$ktorm_version"
testImplementation "io.kotlintest:kotlintest-runner-junit5:3.1.0"
}

View File

@ -0,0 +1,102 @@
{{#vendorExtensions}}{{#x-ktorm-schema}}{{^discriminator}}
/**
* {{{description}}}
{{#allVars}}
* @param {{{name}}} {{{description}}}
{{/allVars}}
*/
{{#isDeprecated}}
@Deprecated(message = "This schema is deprecated.")
{{/isDeprecated}}
{{#nonPublicApi}}internal {{/nonPublicApi}}object {{{classname}}}s : BaseTable<{{{classname}}}>("{{#tableDefinition}}{{{tblName}}}{{/tableDefinition}}") {
{{#allVars}}
{{^isArray}}
{{#isEnum}}
{{#required}}{{>data_class_enum_req}}{{/required}}{{^required}}{{>data_class_enum_opt}}{{/required}}
{{/isEnum}}
{{^isEnum}}
{{#required}}{{>data_class_field_req}}{{/required}}{{^required}}{{>data_class_field_opt}}{{/required}}
{{/isEnum}}
{{/isArray}}
{{/allVars}}
/**
* Create an entity of type {{{classname}}} from the model
*/
override fun doCreateEntity(row: QueryRowSet, withReferences: Boolean) = {{{classname}}}(
{{#allVars}}
{{#vendorExtensions}}
{{#x-ktorm-schema}}
{{^isArray}}
{{#relation}}
{{#required}}{{>data_class_bind_ref_req}}{{/required}}{{^required}}{{>data_class_bind_ref_opt}}{{/required}}{{^-last}},{{/-last}}
{{/relation}}
{{^relation}}
{{#required}}{{>data_class_bind_field_req}}{{/required}}{{^required}}{{>data_class_bind_field_opt}}{{/required}}{{^-last}},{{/-last}}
{{/relation}}
{{/isArray}}
{{#isArray}}
{{#required}}{{>data_class_bind_list_req}}{{/required}}{{^required}}{{>data_class_bind_list_opt}}{{/required}}{{^-last}},{{/-last}}
{{/isArray}}
{{/x-ktorm-schema}}
{{/vendorExtensions}}
{{/allVars}}
)
/**
* Assign all the columns from the entity of type {{{classname}}} to the DML expression.
*
* Usage:
*
* ```kotlin
* let entity = {{{classname}}}()
* database.update({{{classname}}}s, {
* assignFrom(entity)
* })
* ```
* @return the builder with the columns for the update or insert.
*/
fun AssignmentsBuilder.assignFrom(entity: {{{classname}}}) {
this.apply {
{{#allVars}}
{{^isArray}}
{{>data_class_set}}
{{/isArray}}
{{/allVars}}
}
}
}
{{#allVars}}
{{#isArray}}
{{#vendorExtensions}}
{{#x-ktorm-schema}}
{{#isDeprecated}}
@Deprecated(message = "This schema is deprecated.")
{{/isDeprecated}}
{{#relationDefinition}}
{{#nonPublicApi}}internal {{/nonPublicApi}}object {{{relName}}} : BaseTable<Pair<{{{pkColKotlinType}}}, {{{fkColKotlinType}}}>>("{{{relTblName}}}") {
val {{{pkName}}} = {{{pkColType}}}("{{{pkColName}}}")
val {{{fkName}}} = {{{fkColType}}}("{{{fkColName}}}")
override fun doCreateEntity(row: QueryRowSet, withReferences: Boolean): Pair<{{{pkColKotlinType}}}, {{{fkColKotlinType}}}> =
Pair(row[{{{pkName}}}] ?: {{#pkIsString}}""{{/pkIsString}}{{#pkIsNumeric}}0{{/pkIsNumeric}}, row[{{{fkName}}}] ?: {{#fkIsString}}""{{/fkIsString}}{{#fkIsNumeric}}0{{/fkIsNumeric}})
fun AssignmentsBuilder.assignFrom(entity: Pair<{{{pkColKotlinType}}}, {{{fkColKotlinType}}}>) {
this.apply {
set({{{relName}}}.{{{pkName}}}, entity.first)
set({{{relName}}}.{{{fkName}}}, entity.second)
}
}
}
{{/relationDefinition}}
{{/x-ktorm-schema}}
{{/vendorExtensions}}
{{/isArray}}
{{/allVars}}
{{/discriminator}}
{{/x-ktorm-schema}}
{{/vendorExtensions}}

View File

@ -0,0 +1 @@
{{#vendorExtensions}}{{#x-ktorm-schema}}{{#columnDefinition}} {{{name}}} = row[{{{name}}}] {{#defaultvalue}}?: {{{defaultvalue}}}{{/defaultvalue}} /* {{{colKotlinType}}}? */{{/columnDefinition}}{{/x-ktorm-schema}}{{/vendorExtensions}}{{#description}} /* {{{description}}} */{{/description}}

View File

@ -0,0 +1 @@
{{#vendorExtensions}}{{#x-ktorm-schema}}{{#columnDefinition}} {{{name}}} = row[{{{name}}}]{{#isEnum}} ?: {{{classname}}}.{{{nameInCamelCase}}}.valueOf({{#isString}}""{{/isString}}{{#isNumeric}}0{{/isNumeric}}){{/isEnum}}{{^isEnum}}{{#isString}} ?: ""{{/isString}}{{#isNumeric}} ?: 0{{/isNumeric}}{{#isBoolean}} ?: false{{/isBoolean}}{{/isEnum}} /* {{{colKotlinType}}} */{{/columnDefinition}}{{/x-ktorm-schema}}{{/vendorExtensions}}{{#description}} /* {{{description}}} */{{/description}}

View File

@ -0,0 +1 @@
{{#vendorExtensions}}{{#x-ktorm-schema}}{{#columnDefinition}} {{{name}}} = emptyList() /* {{{colKotlinType}}}? */{{/columnDefinition}}{{/x-ktorm-schema}}{{/vendorExtensions}}{{#description}} /* {{{description}}} */{{/description}}

View File

@ -0,0 +1 @@
{{#vendorExtensions}}{{#x-ktorm-schema}}{{#columnDefinition}} {{{name}}} = emptyList() /* {{{colKotlinType}}} */{{/columnDefinition}}{{/x-ktorm-schema}}{{/vendorExtensions}}{{#description}} /* {{{description}}} */{{/description}}

View File

@ -0,0 +1 @@
{{#vendorExtensions}}{{#x-ktorm-schema}}{{#columnDefinition}} {{{name}}} = {{{colKotlinType}}}s.createEntity(row, withReferences) /* {{{colKotlinType}}}? */{{/columnDefinition}}{{/x-ktorm-schema}}{{/vendorExtensions}}{{#description}} /* {{{description}}} */{{/description}}

View File

@ -0,0 +1 @@
{{#vendorExtensions}}{{#x-ktorm-schema}}{{#columnDefinition}} {{{name}}} = {{{colKotlinType}}}s.createEntity(row, withReferences) /* {{{colKotlinType}}} */{{/columnDefinition}}{{/x-ktorm-schema}}{{/vendorExtensions}}{{#description}} /* {{{description}}} */{{/description}}

View File

@ -0,0 +1,20 @@
# Table {{#vendorExtensions}}{{#x-ktorm-schema}}{{#tableDefinition}}`{{tblName}}`{{/tableDefinition}}{{/x-ktorm-schema}}{{/vendorExtensions}}
(mapped from: {{classname}})
## Properties
Name | Mapping | SQL Type | Default | Type | Description | Notes
---- | ------- | -------- | ------- | ---- | ----------- | -----
{{#allVars}}**{{name}}** | {{^isArray}}{{#vendorExtensions}}{{#x-ktorm-schema}}{{#columnDefinition}}{{colName}} | {{colType}}{{#colTypeArgs}}{{#-first}}({{/-first}}{{#isString}}'{{/isString}}{{argVal}}{{#isString}}'{{/isString}}{{^-last}}, {{/-last}}{{#-last}}){{/-last}}{{/colTypeArgs}}{{#colUnsigned}} UNSIGNED{{/colUnsigned}}{{#colNotNull}} NOT NULL{{/colNotNull}}{{#colPrimaryKey}} PRIMARY KEY{{#isNumeric}} AUTOINCREMENT{{/isNumeric}}{{/colPrimaryKey}} | {{#colDefault}}{{#isString}}'{{defaultValue}}'{{/isString}}{{^isString}}{{defaultValue}}{{/isString}}{{/colDefault}}{{/columnDefinition}}{{/x-ktorm-schema}}{{/vendorExtensions}}{{/isArray}}{{#isArray}}`One-To-Many` | `----` | `----` {{/isArray}} | {{#isEnum}}[**{{baseName}}**](#{{datatypeWithEnum}}){{/isEnum}}{{^isEnum}}{{#isPrimitiveType}}**{{dataType}}**{{/isPrimitiveType}}{{^isPrimitiveType}}[**{{dataType}}**]({{complexType}}.md){{/isPrimitiveType}}{{/isEnum}} | {{description}} | {{^required}} [optional]{{/required}}{{#isReadOnly}} [readonly]{{/isReadOnly}}{{#vendorExtensions}}{{#x-ktorm-schema}}{{^isArray}}{{#relation}} [foreignkey]{{/relation}}{{/isArray}}{{/x-ktorm-schema}}{{/vendorExtensions}}
{{/allVars}}
{{#allVars}}{{#isArray}}{{#vendorExtensions}}{{#x-ktorm-schema}}{{#relationDefinition}}
# **Table `{{{relTblName}}}`**
(mapped from: {{relName}})
## Properties
Name | Mapping | SQL Type | Default | Type | Description | Notes
---- | ------- | -------- | ------- | ---- | ----------- | -----
{{{pkName}}} | {{{pkColName}}} | {{{pkColType}}} | | {{{pkColKotlinType}}} | Primary Key | *one*
{{{fkName}}} | {{{fkColName}}} | {{{fkColType}}} | | {{{fkColKotlinType}}} | Foreign Key | *many*
{{/relationDefinition}}{{/x-ktorm-schema}}{{/vendorExtensions}}{{/isArray}}
{{/allVars}}

View File

@ -0,0 +1,2 @@
{{#deprecated}} @Deprecated(message = "This property is deprecated.")
{{/deprecated}}{{#vendorExtensions}}{{#x-ktorm-schema}}{{#columnDefinition}} val {{{name}}} = {{{colType}}}("{{{colName}}}").transform({ {{{classname}}}.{{{nameInCamelCase}}}.valueOf(it ?: {{#allowableValues}}{{#enumVars}}{{#-first}}{{{value}}}{{/-first}}{{/enumVars}}{{/allowableValues}}) }, { it.value }) /* null */{{/columnDefinition}}{{/x-ktorm-schema}}{{/vendorExtensions}}{{#description}} /* {{{description}}} */{{/description}}

View File

@ -0,0 +1,2 @@
{{#deprecated}} @Deprecated(message = "This property is deprecated.")
{{/deprecated}}{{#vendorExtensions}}{{#x-ktorm-schema}}{{#columnDefinition}} val {{{name}}} = {{{colType}}}("{{{colName}}}").transform({ {{{classname}}}.{{{nameInCamelCase}}}.valueOf(it) }, { it.value }){{/columnDefinition}}{{/x-ktorm-schema}}{{/vendorExtensions}}{{#description}} /* {{{description}}} */{{/description}}

View File

@ -0,0 +1,2 @@
{{#deprecated}} @Deprecated(message = "This property is deprecated.")
{{/deprecated}}{{#vendorExtensions}}{{#x-ktorm-schema}}{{#columnDefinition}} val {{{name}}} = {{{colType}}}("{{{colName}}}") /* null */{{/columnDefinition}}{{/x-ktorm-schema}}{{/vendorExtensions}}{{#description}} /* {{{description}}} */{{/description}}

View File

@ -0,0 +1,2 @@
{{#deprecated}} @Deprecated(message = "This property is deprecated.")
{{/deprecated}}{{#vendorExtensions}}{{#x-ktorm-schema}}{{#columnDefinition}} val {{{name}}} = {{{colType}}}("{{{colName}}}"){{/columnDefinition}}{{/x-ktorm-schema}}{{/vendorExtensions}}{{#description}} /* {{{description}}} */{{/description}}

View File

@ -0,0 +1 @@
set({{{classname}}}s.{{{name}}}, entity.{{{name}}})

View File

@ -0,0 +1,61 @@
{{^multiplatform}}
{{#gson}}
import com.google.gson.annotations.SerializedName
{{/gson}}
{{#moshi}}
import com.squareup.moshi.Json
{{/moshi}}
{{#jackson}}
import com.fasterxml.jackson.annotation.JsonProperty
{{/jackson}}
{{/multiplatform}}
{{#multiplatform}}
import kotlinx.serialization.*
import kotlinx.serialization.internal.CommonEnumSerializer
{{/multiplatform}}
/**
* {{{description}}}
* Values: {{#allowableValues}}{{#enumVars}}{{&name}}{{^-last}},{{/-last}}{{/enumVars}}{{/allowableValues}}
*/
{{#multiplatform}}@Serializable(with = {{classname}}.Serializer::class){{/multiplatform}}
{{#nonPublicApi}}internal {{/nonPublicApi}}enum class {{classname}}(val value: {{{dataType}}}){
{{#allowableValues}}{{#enumVars}}
{{^multiplatform}}
{{#moshi}}
@Json(name = {{^isString}}"{{/isString}}{{{value}}}{{^isString}}"{{/isString}})
{{/moshi}}
{{#gson}}
@SerializedName(value = {{^isString}}"{{/isString}}{{{value}}}{{^isString}}"{{/isString}})
{{/gson}}
{{#jackson}}
@JsonProperty(value = {{^isString}}"{{/isString}}{{{value}}}{{^isString}}"{{/isString}})
{{/jackson}}
{{/multiplatform}}
{{#isArray}}
{{#isList}}
{{&name}}(listOf({{{value}}})){{^-last}},{{/-last}}{{#-last}};{{/-last}}
{{/isList}}
{{^isList}}
{{&name}}(arrayOf({{{value}}})){{^-last}},{{/-last}}{{#-last}};{{/-last}}
{{/isList}}
{{/isArray}}
{{^isArray}}
{{&name}}({{{value}}}){{^-last}},{{/-last}}{{#-last}};{{/-last}}
{{/isArray}}
{{/enumVars}}{{/allowableValues}}
/**
This override toString avoids using the enum var name and uses the actual api value instead.
In cases the var name and value are different, the client would send incorrect enums to the server.
**/
override fun toString(): String {
return value{{^isString}}.toString(){{/isString}}
}
{{#multiplatform}}
{{#nonPublicApi}}internal {{/nonPublicApi}}object Serializer : CommonEnumSerializer<{{classname}}>("{{classname}}", values(), values().map { it.value.toString() }.toTypedArray())
{{/multiplatform}}
}

View File

@ -0,0 +1,7 @@
# {{classname}}
## Enum
{{#allowableValues}}{{#enumVars}}
* `{{name}}` (value: `{{{value}}}`)
{{/enumVars}}{{/allowableValues}}

View File

@ -0,0 +1,179 @@
{{#defaultDatabaseName}}
--
-- Database: `{{{defaultDatabaseName}}}`
--
CREATE DATABASE IF NOT EXISTS `{{{defaultDatabaseName}}}` DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
{{/defaultDatabaseName}}
{{#models}}{{#model}}{{#hasVars}}{{^isArrayModel}}
-- --------------------------------------------------------------------------
-- Table structure{{#vendorExtensions}}{{#x-ktorm-schema}}{{#tableDefinition}} for table `{{tblName}}`{{/tableDefinition}}{{/x-ktorm-schema}}{{/vendorExtensions}} generated from model '{{classVarName}}'
{{#description}}
-- {{description}}
{{/description}}
--
{{#vendorExtensions}}
{{#x-ktorm-schema}}
{{#tableDefinition}}
CREATE TABLE IF NOT EXISTS {{#defaultDatabaseName}}`{{{defaultDatabaseName}}}`.{{/defaultDatabaseName}}`{{tblName}}` (
{{/tableDefinition}}
{{/x-ktorm-schema}}
{{/vendorExtensions}}
{{#allVars}}
{{#vendorExtensions}}
{{#x-ktorm-schema}}
{{#columnDefinition}}
{{^isArray}}
`{{colName}}` {{colType}}{{#colTypeArgs}}{{#-first}}({{/-first}}{{#isString}}'{{/isString}}{{argVal}}{{#isString}}'{{/isString}}{{^-last}}, {{/-last}}{{#-last}}){{/-last}}{{/colTypeArgs}}{{#colUnsigned}} UNSIGNED{{/colUnsigned}}{{#colNotNull}} NOT NULL{{/colNotNull}}{{#colPrimaryKey}} PRIMARY KEY{{#isNumeric}} AUTOINCREMENT{{/isNumeric}}{{/colPrimaryKey}}{{#colDefault}} DEFAULT {{#isString}}'{{defaultValue}}'{{/isString}}{{^isString}}{{defaultValue}}{{/isString}}{{/colDefault}}{{#colComment}} /*{{colComment}}*/{{/colComment}}{{^-last}},{{/-last}}
{{/isArray}}
{{/columnDefinition}}
{{/x-ktorm-schema}}
{{/vendorExtensions}}
{{/allVars}}
{{#vendorExtensions}}
{{#x-ktorm-schema}}
{{#tableDefinition}}
); {{#tblComment}} /*{{tblComment}}*/{{/tblComment}}
{{/tableDefinition}}
{{/x-ktorm-schema}}
{{/vendorExtensions}}
{{#allVars}}
{{#isArray}}
{{#vendorExtensions}}
{{#x-ktorm-schema}}
{{#relationDefinition}}
-- --------------------------------------------------------------------------
-- Table structure for table `{{relTblName}}` generated from model '{{relName}}'
{{#colComment}}
-- {{colComment}}
{{/colComment}}
CREATE TABLE IF NOT EXISTS {{#defaultDatabaseName}}`{{{defaultDatabaseName}}}`.{{/defaultDatabaseName}}`{{relTblName}}` (
`{{{pkColName}}}` {{{pkColType}}} NOT NULL
`{{{fkColName}}}` {{{fkColType}}} NOT NULL
);
{{/relationDefinition}}
{{/x-ktorm-schema}}
{{/vendorExtensions}}
{{/isArray}}
{{/allVars}}
{{/isArrayModel}}{{/hasVars}}{{/model}}{{/models}}
{{#hasOAuthMethods}}
--
-- OAuth2 framework tables
-- Thanks to https://github.com/dsquier/oauth2-server-php-mysql repo
--
--
-- Table structure for table `oauth_clients`
--
CREATE TABLE IF NOT EXISTS `oauth_clients` (
`client_id` VARCHAR(80) NOT NULL,
`client_secret` VARCHAR(80) DEFAULT NULL,
`redirect_uri` VARCHAR(2000) DEFAULT NULL,
`grant_types` VARCHAR(80) DEFAULT NULL,
`scope` VARCHAR(4000) DEFAULT NULL,
`user_id` VARCHAR(80) DEFAULT NULL,
PRIMARY KEY (`client_id`)
);
--
-- Table structure for table `oauth_access_tokens`
--
CREATE TABLE IF NOT EXISTS `oauth_access_tokens` (
`access_token` VARCHAR(40) NOT NULL,
`client_id` VARCHAR(80) DEFAULT NULL,
`user_id` VARCHAR(80) DEFAULT NULL,
`expires` TIMESTAMP NOT NULL,
`scope` VARCHAR(4000) DEFAULT NULL,
PRIMARY KEY (`access_token`)
);
--
-- Table structure for table `oauth_authorization_codes`
--
CREATE TABLE IF NOT EXISTS `oauth_authorization_codes` (
`authorization_code` VARCHAR(40) NOT NULL,
`client_id` VARCHAR(80) DEFAULT NULL,
`user_id` VARCHAR(80) DEFAULT NULL,
`redirect_uri` VARCHAR(2000) NOT NULL,
`expires` TIMESTAMP NOT NULL,
`scope` VARCHAR(4000) DEFAULT NULL,
`id_token` VARCHAR(1000) DEFAULT NULL,
PRIMARY KEY (`authorization_code`)
);
--
-- Table structure for table `oauth_refresh_tokens`
--
CREATE TABLE IF NOT EXISTS `oauth_refresh_tokens` (
`refresh_token` VARCHAR(40) NOT NULL,
`client_id` VARCHAR(80) DEFAULT NULL,
`user_id` VARCHAR(80) DEFAULT NULL,
`expires` TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
`scope` VARCHAR(4000) DEFAULT NULL,
PRIMARY KEY (`refresh_token`)
);
--
-- Table structure for table `oauth_users`
--
CREATE TABLE IF NOT EXISTS `oauth_users` (
`username` VARCHAR(80) DEFAULT NULL,
`password` VARCHAR(255) DEFAULT NULL,
`first_name` VARCHAR(80) DEFAULT NULL,
`last_name` VARCHAR(80) DEFAULT NULL,
`email` VARCHAR(2000) DEFAULT NULL,
`email_verified` TINYINT(1) DEFAULT NULL,
`scope` VARCHAR(4000) DEFAULT NULL
);
--
-- Table structure for table `oauth_scopes`
--
CREATE TABLE IF NOT EXISTS `oauth_scopes` (
`scope` VARCHAR(80) NOT NULL,
`is_default` TINYINT(1) DEFAULT NULL,
PRIMARY KEY (`scope`)
);
--
-- Table structure for table `oauth_jwt`
--
CREATE TABLE IF NOT EXISTS `oauth_jwt` (
`client_id` VARCHAR(80) NOT NULL,
`subject` VARCHAR(80) DEFAULT NULL,
`public_key` VARCHAR(2000) NOT NULL
);
--
-- Table structure for table `oauth_jti`
--
CREATE TABLE IF NOT EXISTS `oauth_jti` (
`issuer` VARCHAR(80) NOT NULL,
`subject` VARCHAR(80) DEFAULT NULL,
`audiance` VARCHAR(80) DEFAULT NULL,
`expires` TIMESTAMP NOT NULL,
`jti` VARCHAR(2000) NOT NULL
);
--
-- Table structure for table `oauth_public_keys`
--
CREATE TABLE IF NOT EXISTS `oauth_public_keys` (
`client_id` VARCHAR(80) DEFAULT NULL,
`public_key` VARCHAR(2000) DEFAULT NULL,
`private_key` VARCHAR(2000) DEFAULT NULL,
`encryption_algorithm` VARCHAR(100) DEFAULT 'RS256'
);
{{/hasOAuthMethods}}
--
-- Table structure for table `_db_version`
--
CREATE TABLE IF NOT EXISTS `_db_version` (
`version` LONG DEFAULT 1
);

View File

@ -0,0 +1,11 @@
/**
* {{{appName}}}
* {{{appDescription}}}
*
* {{#version}}The version of the OpenAPI document: {{{version}}}{{/version}}
* {{#infoEmail}}Contact: {{{infoEmail}}}{{/infoEmail}}
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/

View File

@ -0,0 +1,13 @@
{{>licenseInfo}}
package {{modelPackage}}
import org.ktorm.dsl.*
import org.ktorm.schema.*
import org.ktorm.database.Database
import {{{importModelPackageName}}}.*
{{#models}}
{{#model}}
{{#isEnum}}{{>enum_class}}{{/isEnum}}{{^isEnum}}{{#isAlias}}typealias {{classname}} = {{{dataType}}}{{/isAlias}}{{^isAlias}}{{>data_class}}{{/isAlias}}{{/isEnum}}
{{/model}}
{{/models}}

View File

@ -0,0 +1,3 @@
{{#models}}{{#model}}
{{#isEnum}}{{>enum_doc}}{{/isEnum}}{{^isEnum}}{{>data_class_doc}}{{/isEnum}}
{{/model}}{{/models}}

View File

@ -0,0 +1,2 @@
{{#multiplatform}}enableFeaturePreview('GRADLE_METADATA')
{{/multiplatform}}rootProject.name = '{{artifactId}}'

View File

@ -0,0 +1,316 @@
/*
* Copyright 2018 OpenAPI-Generator Contributors (https://openapi-generator.tech)
*
* 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.
*/
package org.openapitools.codegen.ktorm;
import org.openapitools.codegen.CodegenModel;
import org.openapitools.codegen.CodegenProperty;
import org.openapitools.codegen.DefaultCodegen;
import org.openapitools.codegen.TestUtils;
import org.openapitools.codegen.languages.KtormSchemaCodegen;
import org.testng.Assert;
import org.testng.annotations.Test;
import io.swagger.v3.oas.models.OpenAPI;
import io.swagger.v3.oas.models.media.*;
import io.swagger.v3.parser.util.SchemaTypeUtil;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class KtormSchemaCodegenTest {
private Map<String, Object> toObjs(CodegenModel cm) {
Map<String, Object> objs = new HashMap<String, Object>();
List<Object> models = new ArrayList<Object>();
Map<String, Object> model = new HashMap<>();
model.put("model", cm);
models.add(model);
objs.put("models", models);
return objs;
}
private CodegenModel getModel(Schema schema, String pkName, Boolean surrogateKey) {
final KtormSchemaCodegen codegen = new KtormSchemaCodegen();
OpenAPI openAPI = TestUtils.createOpenAPIWithOneSchema("sample", schema);
codegen.setAddSurrogateKey(surrogateKey);
codegen.setPrimaryKeyConvention(pkName);
codegen.setOpenAPI(openAPI);
CodegenModel cm = codegen.fromModel("sample", schema);
codegen.postProcessModels(toObjs(cm));
return cm;
}
private Map<String, Object> getExtension(CodegenProperty property) {
return (Map<String, Object>)
property.vendorExtensions.get(KtormSchemaCodegen.VENDOR_EXTENSION_SCHEMA);
}
private Map<String, Object> getColumnDefinition(Map<String, Object> schema) {
return (Map<String, Object>)
schema.get("columnDefinition");
}
private Map<String, Object> getRelationDefinition(Map<String, Object> schema) {
return (Map<String, Object>)
schema.get("relationDefinition");
}
private Map<String, Object> getKtormSchema(Schema propertySchema) {
final Schema schema = new Schema()
.description("a sample model")
.addProperties("key", propertySchema)
.addRequiredItem("key");
final CodegenModel cm = getModel(schema, "id", false);
final CodegenProperty prop = cm.vars.get(0);
return getExtension(prop);
}
private String getMatchedColType(Schema propertySchema) {
Map<String, Object> ktormSchema = getColumnDefinition(getKtormSchema(propertySchema));
return (String) ktormSchema.get("colType");
}
private String getMatchedKotlinType(Schema propertySchema) {
Map<String, Object> ktormSchema = getColumnDefinition(getKtormSchema(propertySchema));
return (String) ktormSchema.get("colKotlinType");
}
private String getMatchedRelation(Schema propertySchema) {
Map<String, Object> ktormSchema = getRelationDefinition(getKtormSchema(propertySchema));
if (ktormSchema == null) return null;
return (String) ktormSchema.get("fkName");
}
@Test
public void testMatchedColType() {
Assert.assertEquals(getMatchedColType(new StringSchema()), "text");
Assert.assertEquals(getMatchedColType(new StringSchema().type("char")), "text");
Assert.assertEquals(getMatchedColType(new StringSchema().format("char")), "text");
Assert.assertEquals(getMatchedColType(new BooleanSchema()), "boolean");
Assert.assertEquals(getMatchedColType(new IntegerSchema().type(SchemaTypeUtil.BYTE_FORMAT)), "int");
Assert.assertEquals(getMatchedColType(new IntegerSchema().format(SchemaTypeUtil.BYTE_FORMAT)), "int");
Assert.assertEquals(getMatchedColType(new IntegerSchema().type("short")), "int");
Assert.assertEquals(getMatchedColType(new IntegerSchema().format("short")), "int");
Assert.assertEquals(getMatchedColType(new IntegerSchema()), "int");
Assert.assertEquals(getMatchedColType(new IntegerSchema().type("integer")), "int");
Assert.assertEquals(getMatchedColType(new IntegerSchema().format("integer")), "int");
Assert.assertEquals(getMatchedColType(new IntegerSchema().format(SchemaTypeUtil.INTEGER32_FORMAT)), "int");
Assert.assertEquals(getMatchedColType(new IntegerSchema().type("long")), "long");
Assert.assertEquals(getMatchedColType(new IntegerSchema().format(SchemaTypeUtil.INTEGER64_FORMAT)), "long");
Assert.assertEquals(getMatchedColType(new ObjectSchema().type(SchemaTypeUtil.FLOAT_FORMAT)), "float");
Assert.assertEquals(getMatchedColType(new NumberSchema().format(SchemaTypeUtil.FLOAT_FORMAT)), "float");
Assert.assertEquals(getMatchedColType(new ObjectSchema().type(SchemaTypeUtil.DOUBLE_FORMAT)), "double");
Assert.assertEquals(getMatchedColType(new NumberSchema().format(SchemaTypeUtil.DOUBLE_FORMAT)), "double");
Assert.assertEquals(getMatchedColType(new ObjectSchema().type(SchemaTypeUtil.FLOAT_FORMAT).format(SchemaTypeUtil.DOUBLE_FORMAT)), "float");
Assert.assertEquals(getMatchedColType(new ObjectSchema().type(SchemaTypeUtil.DOUBLE_FORMAT).format(SchemaTypeUtil.FLOAT_FORMAT)), "double");
Assert.assertEquals(getMatchedColType(new ObjectSchema().type("real")), "double");
Assert.assertEquals(getMatchedColType(new NumberSchema().format("real")), "decimal");
Assert.assertEquals(getMatchedColType(new NumberSchema().type(SchemaTypeUtil.NUMBER_TYPE)), "decimal");
Assert.assertEquals(getMatchedColType(new NumberSchema().type("decimal")), "decimal");
Assert.assertEquals(getMatchedColType(new NumberSchema().type("BigDecimal")), "decimal");
Assert.assertEquals(getMatchedColType(new ByteArraySchema()), "blob");
Assert.assertEquals(getMatchedColType(new ArraySchema().items(new IntegerSchema().type(SchemaTypeUtil.BYTE_FORMAT))), "blob");
Assert.assertEquals(getMatchedColType(new ArraySchema().items(new IntegerSchema().format(SchemaTypeUtil.BYTE_FORMAT))), "blob");
Assert.assertEquals(getMatchedColType(new ArraySchema()), "blob");
Assert.assertEquals(getMatchedColType(new ObjectSchema().type("list")), "blob");
Assert.assertEquals(getMatchedColType(new ObjectSchema().type("set")), "blob");
Assert.assertEquals(getMatchedColType(new ObjectSchema().type("map")), "blob");
Assert.assertEquals(getMatchedColType(new ObjectSchema()), "blob");
Assert.assertEquals(getMatchedColType(new ObjectSchema().type("binary")), "blob");
Assert.assertEquals(getMatchedColType(new ObjectSchema().type("AnyType")), "blob");
Assert.assertEquals(getMatchedColType(new BinarySchema()), "blob");
Assert.assertEquals(getMatchedColType(new FileSchema()), "blob");
Assert.assertEquals(getMatchedColType(new DateSchema()), "date");
Assert.assertEquals(getMatchedColType(new DateTimeSchema()), "datetime");
Assert.assertEquals(getMatchedColType(new UUIDSchema()), "text");
Assert.assertEquals(getMatchedColType(new ObjectSchema().type("UUID")), "text");
Assert.assertEquals(getMatchedColType(new StringSchema().format("URI")), "text");
Assert.assertEquals(getMatchedColType(new ObjectSchema().type("URI")), "text");
Assert.assertEquals(getMatchedColType(new StringSchema().format("password")), "text");
Assert.assertEquals(getMatchedColType(new StringSchema().type("password")), "text");
}
@Test
public void testMatchedColKotlinType() {
// *1 - format specifiers aren't used
Assert.assertEquals(getMatchedKotlinType(new StringSchema()), "kotlin.String");
Assert.assertEquals(getMatchedKotlinType(new StringSchema().type("char")), "kotlin.String");
Assert.assertEquals(getMatchedKotlinType(new StringSchema().format("char")), "kotlin.String");
Assert.assertEquals(getMatchedKotlinType(new BooleanSchema()), "kotlin.Boolean");
Assert.assertEquals(getMatchedKotlinType(new IntegerSchema().type(SchemaTypeUtil.BYTE_FORMAT)), "kotlin.Byte");
Assert.assertEquals(getMatchedKotlinType(new IntegerSchema().format(SchemaTypeUtil.BYTE_FORMAT)), "kotlin.Int"); //*1
Assert.assertEquals(getMatchedKotlinType(new IntegerSchema().type("short")), "kotlin.Short");
Assert.assertEquals(getMatchedKotlinType(new IntegerSchema().format("short")), "kotlin.Int"); //*1
Assert.assertEquals(getMatchedKotlinType(new IntegerSchema()), "kotlin.Int");
Assert.assertEquals(getMatchedKotlinType(new IntegerSchema().type("integer")), "kotlin.Int");
Assert.assertEquals(getMatchedKotlinType(new IntegerSchema().format("integer")), "kotlin.Int"); //*1
Assert.assertEquals(getMatchedKotlinType(new IntegerSchema().format(SchemaTypeUtil.INTEGER32_FORMAT)), "kotlin.Int");
Assert.assertEquals(getMatchedKotlinType(new IntegerSchema().type("long")), "kotlin.Long");
Assert.assertEquals(getMatchedKotlinType(new IntegerSchema().format(SchemaTypeUtil.INTEGER64_FORMAT)), "kotlin.Long");
Assert.assertEquals(getMatchedKotlinType(new ObjectSchema().type(SchemaTypeUtil.FLOAT_FORMAT)), "kotlin.Float");
Assert.assertEquals(getMatchedKotlinType(new NumberSchema().format(SchemaTypeUtil.FLOAT_FORMAT)), "kotlin.Float");
Assert.assertEquals(getMatchedKotlinType(new ObjectSchema().type(SchemaTypeUtil.DOUBLE_FORMAT)), "kotlin.Double");
Assert.assertEquals(getMatchedKotlinType(new NumberSchema().format(SchemaTypeUtil.DOUBLE_FORMAT)), "kotlin.Double");
Assert.assertEquals(getMatchedKotlinType(new ObjectSchema().type(SchemaTypeUtil.FLOAT_FORMAT).format(SchemaTypeUtil.DOUBLE_FORMAT)), "kotlin.Float"); //*1
Assert.assertEquals(getMatchedKotlinType(new ObjectSchema().type(SchemaTypeUtil.DOUBLE_FORMAT).format(SchemaTypeUtil.FLOAT_FORMAT)), "kotlin.Double"); //*1
Assert.assertEquals(getMatchedKotlinType(new ObjectSchema().type("real")), "kotlin.Double");
Assert.assertEquals(getMatchedKotlinType(new NumberSchema().format("real")), "java.math.BigDecimal"); //*1
Assert.assertEquals(getMatchedKotlinType(new NumberSchema().type(SchemaTypeUtil.NUMBER_TYPE)), "java.math.BigDecimal");
Assert.assertEquals(getMatchedKotlinType(new NumberSchema().type("decimal")), "java.math.BigDecimal");
Assert.assertEquals(getMatchedKotlinType(new NumberSchema().type("BigDecimal")), "java.math.BigDecimal");
Assert.assertEquals(getMatchedKotlinType(new ByteArraySchema()), "kotlin.ByteArray");
Assert.assertEquals(getMatchedKotlinType(new ArraySchema().items(new IntegerSchema().type(SchemaTypeUtil.BYTE_FORMAT))), "kotlin.Array<kotlin.Byte>");
Assert.assertEquals(getMatchedKotlinType(new ArraySchema().items(new IntegerSchema().format(SchemaTypeUtil.BYTE_FORMAT))), "kotlin.Array<kotlin.Int>"); //*1
Assert.assertEquals(getMatchedKotlinType(new ArraySchema()), "kotlin.Array<kotlin.String>");
Assert.assertEquals(getMatchedKotlinType(new ObjectSchema().type("list")), "kotlin.collections.List");
Assert.assertEquals(getMatchedKotlinType(new ObjectSchema().type("set")), "kotlin.collections.Set");
Assert.assertEquals(getMatchedKotlinType(new ObjectSchema().type("map")), "kotlin.collections.Map");
Assert.assertEquals(getMatchedKotlinType(new ObjectSchema()), "kotlin.Any");
Assert.assertEquals(getMatchedKotlinType(new ObjectSchema().type("binary")), "kotlin.ByteArray");
Assert.assertEquals(getMatchedKotlinType(new ObjectSchema().type("AnyType")), "kotlin.Any");
Assert.assertEquals(getMatchedKotlinType(new BinarySchema()), "java.io.File"); //looks like a bug
Assert.assertEquals(getMatchedKotlinType(new FileSchema()), "java.io.File");
Assert.assertEquals(getMatchedKotlinType(new DateSchema()), "java.time.LocalDate");
Assert.assertEquals(getMatchedKotlinType(new DateTimeSchema()), "java.time.LocalDateTime");
Assert.assertEquals(getMatchedKotlinType(new UUIDSchema()), "java.util.UUID");
Assert.assertEquals(getMatchedKotlinType(new ObjectSchema().type("UUID")), "java.util.UUID");
Assert.assertEquals(getMatchedKotlinType(new StringSchema().format("URI")), "java.net.URI");
Assert.assertEquals(getMatchedKotlinType(new ObjectSchema().type("URI")), "java.net.URI");
Assert.assertEquals(getMatchedKotlinType(new StringSchema().format("password")), "kotlin.String");
Assert.assertEquals(getMatchedKotlinType(new StringSchema().type("password")), "kotlin.String");
}
@Test
public void testNonMatchedRelation() {
Assert.assertEquals(getMatchedRelation(new StringSchema()), null);
Assert.assertEquals(getMatchedRelation(new StringSchema().type("char")), null);
Assert.assertEquals(getMatchedRelation(new StringSchema().format("char")), null);
Assert.assertEquals(getMatchedRelation(new BooleanSchema()), null);
Assert.assertEquals(getMatchedRelation(new IntegerSchema().type(SchemaTypeUtil.BYTE_FORMAT)), null);
Assert.assertEquals(getMatchedRelation(new IntegerSchema().format(SchemaTypeUtil.BYTE_FORMAT)), null);
Assert.assertEquals(getMatchedRelation(new IntegerSchema().type("short")), null);
Assert.assertEquals(getMatchedRelation(new IntegerSchema().format("short")), null);
Assert.assertEquals(getMatchedRelation(new IntegerSchema()), null);
Assert.assertEquals(getMatchedRelation(new IntegerSchema().type("integer")), null);
Assert.assertEquals(getMatchedRelation(new IntegerSchema().format("integer")), null);
Assert.assertEquals(getMatchedRelation(new IntegerSchema().format(SchemaTypeUtil.INTEGER32_FORMAT)), null);
Assert.assertEquals(getMatchedRelation(new IntegerSchema().type("long")), null);
Assert.assertEquals(getMatchedRelation(new IntegerSchema().format(SchemaTypeUtil.INTEGER64_FORMAT)), null);
Assert.assertEquals(getMatchedRelation(new ObjectSchema().type(SchemaTypeUtil.FLOAT_FORMAT)), null);
Assert.assertEquals(getMatchedRelation(new NumberSchema().format(SchemaTypeUtil.FLOAT_FORMAT)), null);
Assert.assertEquals(getMatchedRelation(new ObjectSchema().type(SchemaTypeUtil.DOUBLE_FORMAT)), null);
Assert.assertEquals(getMatchedRelation(new NumberSchema().format(SchemaTypeUtil.DOUBLE_FORMAT)), null);
Assert.assertEquals(getMatchedRelation(new ObjectSchema().type(SchemaTypeUtil.FLOAT_FORMAT).format(SchemaTypeUtil.DOUBLE_FORMAT)), null);
Assert.assertEquals(getMatchedRelation(new ObjectSchema().type(SchemaTypeUtil.DOUBLE_FORMAT).format(SchemaTypeUtil.FLOAT_FORMAT)), null);
Assert.assertEquals(getMatchedRelation(new ObjectSchema().type("real")), null);
Assert.assertEquals(getMatchedRelation(new NumberSchema().format("real")), null);
Assert.assertEquals(getMatchedRelation(new NumberSchema().type(SchemaTypeUtil.NUMBER_TYPE)), null);
Assert.assertEquals(getMatchedRelation(new NumberSchema().type("decimal")), null);
Assert.assertEquals(getMatchedRelation(new NumberSchema().type("BigDecimal")), null);
Assert.assertEquals(getMatchedRelation(new ByteArraySchema()), null);
Assert.assertEquals(getMatchedRelation(new ObjectSchema().type("list")), null);
Assert.assertEquals(getMatchedRelation(new ObjectSchema().type("set")), null);
Assert.assertEquals(getMatchedRelation(new ObjectSchema().type("map")), null);
Assert.assertEquals(getMatchedRelation(new ObjectSchema()), null);
Assert.assertEquals(getMatchedRelation(new ObjectSchema().type("binary")), null);
Assert.assertEquals(getMatchedRelation(new ObjectSchema().type("AnyType")), null);
Assert.assertEquals(getMatchedRelation(new BinarySchema()), null);
Assert.assertEquals(getMatchedRelation(new FileSchema()), null);
Assert.assertEquals(getMatchedRelation(new DateSchema()), null);
Assert.assertEquals(getMatchedRelation(new DateTimeSchema()), null);
Assert.assertEquals(getMatchedRelation(new UUIDSchema()), null);
Assert.assertEquals(getMatchedRelation(new ObjectSchema().type("UUID")), null);
Assert.assertEquals(getMatchedRelation(new StringSchema().format("URI")), null);
Assert.assertEquals(getMatchedRelation(new ObjectSchema().type("URI")), null);
Assert.assertEquals(getMatchedRelation(new StringSchema().format("password")), null);
Assert.assertEquals(getMatchedRelation(new StringSchema().type("password")), null);
}
@Test
public void testMatchedRelation() {
//foreign keys
Assert.assertEquals(getMatchedRelation(new ObjectSchema().type("Something")), "something");
Assert.assertEquals(getMatchedColType(new ObjectSchema().type("Something")), "long");
Assert.assertEquals(getMatchedRelation(new ObjectSchema().type("UserNamespace.UserClass")), "userNamespaceUserClass");
Assert.assertEquals(getMatchedColType(new ObjectSchema().type("UserNamespace.UserClass")), "long");
//arrays are special case, we convert them to 1:N relations
Assert.assertEquals(getMatchedRelation(new ArraySchema()), "key");
Assert.assertEquals(getMatchedRelation(new ArraySchema().items(new ObjectSchema().type("Something"))), "something");
Assert.assertEquals(getMatchedRelation(new ArraySchema().items(new ObjectSchema().type("UserNamespace.UserClass"))), "userNamespaceUserClass");
Assert.assertEquals(getMatchedRelation(new ArraySchema().items(new IntegerSchema().type(SchemaTypeUtil.BYTE_FORMAT))), "key");
Assert.assertEquals(getMatchedRelation(new ArraySchema().items(new StringSchema())), "key");
//blob will be the default type, the template shouldn't include those fields
Assert.assertEquals(getMatchedColType(new ArraySchema()), "blob");
Assert.assertEquals(getMatchedColType(new ArraySchema().items(new ObjectSchema().type("Something"))), "blob");
Assert.assertEquals(getMatchedColType(new ArraySchema().items(new ObjectSchema().type("UserNamespace.UserClass"))), "blob");
Assert.assertEquals(getMatchedColType(new ArraySchema().items(new IntegerSchema().type(SchemaTypeUtil.BYTE_FORMAT))), "blob");
Assert.assertEquals(getMatchedColType(new ArraySchema().items(new StringSchema())), "blob");
}
@Test
public void testDefinePrimaryKey() {
final Schema schema = new Schema()
.description("a sample model")
.addProperties("key" , new IntegerSchema())
.addRequiredItem("key");
CodegenModel cm = getModel(schema, "key", false);
Assert.assertEquals(cm.vars.size(), 1);
CodegenProperty prop = cm.vars.get(0);
Map<String, Object> propSchema = getColumnDefinition(getExtension(prop));
Assert.assertEquals(propSchema.get("colPrimaryKey"), true);
Assert.assertEquals(propSchema.get("colType"), "int");
}
@Test
public void testDontAddSorrogateKey() {
final Schema schema = new Schema()
.description("a sample model")
.addProperties("key" , new IntegerSchema())
.addRequiredItem("key");
CodegenModel cm = getModel(schema, "id", false);
Assert.assertEquals(cm.vars.size(), 1);
CodegenProperty prop = cm.vars.get(0);
Map<String, Object> propSchema = getColumnDefinition(getExtension(prop));
Assert.assertEquals(propSchema.get("colPrimaryKey"), false);
Assert.assertEquals(propSchema.get("colType"), "int");
}
@Test
public void testAddSorrogateKey() {
final Schema schema = new Schema()
.description("a sample model")
.addProperties("key", new IntegerSchema());
CodegenModel cm = getModel(schema, "id", true);
Assert.assertEquals(cm.vars.size(), 2);
CodegenProperty prop = cm.vars.get(0);
Map<String, Object> propSchema = getColumnDefinition(getExtension(prop));
Assert.assertEquals(propSchema.get("colNotNull"), true);
Assert.assertEquals(propSchema.get("colPrimaryKey"), true);
Assert.assertEquals(propSchema.get("colName"), "id");
Assert.assertEquals(propSchema.get("colType"), "long"); //by default
CodegenProperty prop2 = cm.vars.get(1);
Map<String, Object> propSchema2 = getColumnDefinition(getExtension(prop2));
Assert.assertEquals(propSchema2.get("colNotNull"), false);
Assert.assertEquals(propSchema2.get("colPrimaryKey"), false);
Assert.assertEquals(propSchema2.get("colName"), "key");
Assert.assertEquals(propSchema2.get("colType"), "int");
}
}

View File

@ -0,0 +1,374 @@
/**
* 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.client.apis
import org.openapitools.client.models.ApiResponse
import org.openapitools.client.models.Pet
import org.openapitools.client.infrastructure.ApiClient
import org.openapitools.client.infrastructure.ClientException
import org.openapitools.client.infrastructure.ClientError
import org.openapitools.client.infrastructure.ServerException
import org.openapitools.client.infrastructure.ServerError
import org.openapitools.client.infrastructure.MultiValueMap
import org.openapitools.client.infrastructure.RequestConfig
import org.openapitools.client.infrastructure.RequestMethod
import org.openapitools.client.infrastructure.ResponseType
import org.openapitools.client.infrastructure.Success
import org.openapitools.client.infrastructure.toMultiValue
class PetApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) {
companion object {
@JvmStatic
val defaultBasePath: String by lazy {
System.getProperties().getProperty("org.openapitools.client.baseUrl", "http://petstore.swagger.io/v2")
}
}
/**
* Add a new pet to the store
*
* @param body Pet object that needs to be added to the store
* @return void
* @throws UnsupportedOperationException If the API returns an informational or redirection response
* @throws ClientException If the API returns a client error response
* @throws ServerException If the API returns a server error response
*/
@Throws(UnsupportedOperationException::class, ClientException::class, ServerException::class)
fun addPet(body: Pet) : Unit {
val localVariableBody: kotlin.Any? = body
val localVariableQuery: MultiValueMap = mutableMapOf()
val localVariableHeaders: MutableMap<String, String> = mutableMapOf()
val localVariableConfig = RequestConfig(
RequestMethod.POST,
"/pet",
query = localVariableQuery,
headers = localVariableHeaders
)
val localVarResponse = request<Any?>(
localVariableConfig,
localVariableBody
)
return when (localVarResponse.responseType) {
ResponseType.Success -> Unit
ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.")
ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.")
ResponseType.ClientError -> {
val localVarError = localVarResponse as ClientError<*>
throw ClientException("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse)
}
ResponseType.ServerError -> {
val localVarError = localVarResponse as ServerError<*>
throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse)
}
}
}
/**
* Deletes a pet
*
* @param petId Pet id to delete
* @param apiKey (optional)
* @return void
* @throws UnsupportedOperationException If the API returns an informational or redirection response
* @throws ClientException If the API returns a client error response
* @throws ServerException If the API returns a server error response
*/
@Throws(UnsupportedOperationException::class, ClientException::class, ServerException::class)
fun deletePet(petId: kotlin.Long, apiKey: kotlin.String?) : Unit {
val localVariableBody: kotlin.Any? = null
val localVariableQuery: MultiValueMap = mutableMapOf()
val localVariableHeaders: MutableMap<String, String> = mutableMapOf()
apiKey?.apply { localVariableHeaders["api_key"] = this.toString() }
val localVariableConfig = RequestConfig(
RequestMethod.DELETE,
"/pet/{petId}".replace("{"+"petId"+"}", "$petId"),
query = localVariableQuery,
headers = localVariableHeaders
)
val localVarResponse = request<Any?>(
localVariableConfig,
localVariableBody
)
return when (localVarResponse.responseType) {
ResponseType.Success -> Unit
ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.")
ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.")
ResponseType.ClientError -> {
val localVarError = localVarResponse as ClientError<*>
throw ClientException("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse)
}
ResponseType.ServerError -> {
val localVarError = localVarResponse as ServerError<*>
throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse)
}
}
}
/**
* 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
* @return kotlin.collections.List<Pet>
* @throws UnsupportedOperationException If the API returns an informational or redirection response
* @throws ClientException If the API returns a client error response
* @throws ServerException If the API returns a server error response
*/
@Suppress("UNCHECKED_CAST")
@Throws(UnsupportedOperationException::class, ClientException::class, ServerException::class)
fun findPetsByStatus(status: kotlin.collections.List<kotlin.String>) : kotlin.collections.List<Pet> {
val localVariableBody: kotlin.Any? = null
val localVariableQuery: MultiValueMap = mutableMapOf<kotlin.String, List<kotlin.String>>()
.apply {
put("status", toMultiValue(status.toList(), "csv"))
}
val localVariableHeaders: MutableMap<String, String> = mutableMapOf()
val localVariableConfig = RequestConfig(
RequestMethod.GET,
"/pet/findByStatus",
query = localVariableQuery,
headers = localVariableHeaders
)
val localVarResponse = request<kotlin.collections.List<Pet>>(
localVariableConfig,
localVariableBody
)
return when (localVarResponse.responseType) {
ResponseType.Success -> (localVarResponse as Success<*>).data as kotlin.collections.List<Pet>
ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.")
ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.")
ResponseType.ClientError -> {
val localVarError = localVarResponse as ClientError<*>
throw ClientException("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse)
}
ResponseType.ServerError -> {
val localVarError = localVarResponse as ServerError<*>
throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse)
}
}
}
/**
* 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
* @return kotlin.collections.List<Pet>
* @throws UnsupportedOperationException If the API returns an informational or redirection response
* @throws ClientException If the API returns a client error response
* @throws ServerException If the API returns a server error response
*/
@Suppress("UNCHECKED_CAST")
@Throws(UnsupportedOperationException::class, ClientException::class, ServerException::class)
@Deprecated(message = "This operation is deprecated.")
fun findPetsByTags(tags: kotlin.collections.List<kotlin.String>) : kotlin.collections.List<Pet> {
val localVariableBody: kotlin.Any? = null
val localVariableQuery: MultiValueMap = mutableMapOf<kotlin.String, List<kotlin.String>>()
.apply {
put("tags", toMultiValue(tags.toList(), "csv"))
}
val localVariableHeaders: MutableMap<String, String> = mutableMapOf()
val localVariableConfig = RequestConfig(
RequestMethod.GET,
"/pet/findByTags",
query = localVariableQuery,
headers = localVariableHeaders
)
val localVarResponse = request<kotlin.collections.List<Pet>>(
localVariableConfig,
localVariableBody
)
return when (localVarResponse.responseType) {
ResponseType.Success -> (localVarResponse as Success<*>).data as kotlin.collections.List<Pet>
ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.")
ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.")
ResponseType.ClientError -> {
val localVarError = localVarResponse as ClientError<*>
throw ClientException("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse)
}
ResponseType.ServerError -> {
val localVarError = localVarResponse as ServerError<*>
throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse)
}
}
}
/**
* Find pet by ID
* Returns a single pet
* @param petId ID of pet to return
* @return Pet
* @throws UnsupportedOperationException If the API returns an informational or redirection response
* @throws ClientException If the API returns a client error response
* @throws ServerException If the API returns a server error response
*/
@Suppress("UNCHECKED_CAST")
@Throws(UnsupportedOperationException::class, ClientException::class, ServerException::class)
fun getPetById(petId: kotlin.Long) : Pet {
val localVariableBody: kotlin.Any? = null
val localVariableQuery: MultiValueMap = mutableMapOf()
val localVariableHeaders: MutableMap<String, String> = mutableMapOf()
val localVariableConfig = RequestConfig(
RequestMethod.GET,
"/pet/{petId}".replace("{"+"petId"+"}", "$petId"),
query = localVariableQuery,
headers = localVariableHeaders
)
val localVarResponse = request<Pet>(
localVariableConfig,
localVariableBody
)
return when (localVarResponse.responseType) {
ResponseType.Success -> (localVarResponse as Success<*>).data as Pet
ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.")
ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.")
ResponseType.ClientError -> {
val localVarError = localVarResponse as ClientError<*>
throw ClientException("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse)
}
ResponseType.ServerError -> {
val localVarError = localVarResponse as ServerError<*>
throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse)
}
}
}
/**
* Update an existing pet
*
* @param body Pet object that needs to be added to the store
* @return void
* @throws UnsupportedOperationException If the API returns an informational or redirection response
* @throws ClientException If the API returns a client error response
* @throws ServerException If the API returns a server error response
*/
@Throws(UnsupportedOperationException::class, ClientException::class, ServerException::class)
fun updatePet(body: Pet) : Unit {
val localVariableBody: kotlin.Any? = body
val localVariableQuery: MultiValueMap = mutableMapOf()
val localVariableHeaders: MutableMap<String, String> = mutableMapOf()
val localVariableConfig = RequestConfig(
RequestMethod.PUT,
"/pet",
query = localVariableQuery,
headers = localVariableHeaders
)
val localVarResponse = request<Any?>(
localVariableConfig,
localVariableBody
)
return when (localVarResponse.responseType) {
ResponseType.Success -> Unit
ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.")
ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.")
ResponseType.ClientError -> {
val localVarError = localVarResponse as ClientError<*>
throw ClientException("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse)
}
ResponseType.ServerError -> {
val localVarError = localVarResponse as ServerError<*>
throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse)
}
}
}
/**
* 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)
* @return void
* @throws UnsupportedOperationException If the API returns an informational or redirection response
* @throws ClientException If the API returns a client error response
* @throws ServerException If the API returns a server error response
*/
@Throws(UnsupportedOperationException::class, ClientException::class, ServerException::class)
fun updatePetWithForm(petId: kotlin.Long, name: kotlin.String?, status: kotlin.String?) : Unit {
val localVariableBody: kotlin.Any? = mapOf("name" to name, "status" to status)
val localVariableQuery: MultiValueMap = mutableMapOf()
val localVariableHeaders: MutableMap<String, String> = mutableMapOf("Content-Type" to "application/x-www-form-urlencoded")
val localVariableConfig = RequestConfig(
RequestMethod.POST,
"/pet/{petId}".replace("{"+"petId"+"}", "$petId"),
query = localVariableQuery,
headers = localVariableHeaders
)
val localVarResponse = request<Any?>(
localVariableConfig,
localVariableBody
)
return when (localVarResponse.responseType) {
ResponseType.Success -> Unit
ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.")
ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.")
ResponseType.ClientError -> {
val localVarError = localVarResponse as ClientError<*>
throw ClientException("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse)
}
ResponseType.ServerError -> {
val localVarError = localVarResponse as ServerError<*>
throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse)
}
}
}
/**
* 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)
* @return ApiResponse
* @throws UnsupportedOperationException If the API returns an informational or redirection response
* @throws ClientException If the API returns a client error response
* @throws ServerException If the API returns a server error response
*/
@Suppress("UNCHECKED_CAST")
@Throws(UnsupportedOperationException::class, ClientException::class, ServerException::class)
fun uploadFile(petId: kotlin.Long, additionalMetadata: kotlin.String?, file: java.io.File?) : ApiResponse {
val localVariableBody: kotlin.Any? = mapOf("additionalMetadata" to additionalMetadata, "file" to file)
val localVariableQuery: MultiValueMap = mutableMapOf()
val localVariableHeaders: MutableMap<String, String> = mutableMapOf("Content-Type" to "multipart/form-data")
val localVariableConfig = RequestConfig(
RequestMethod.POST,
"/pet/{petId}/uploadImage".replace("{"+"petId"+"}", "$petId"),
query = localVariableQuery,
headers = localVariableHeaders
)
val localVarResponse = request<ApiResponse>(
localVariableConfig,
localVariableBody
)
return when (localVarResponse.responseType) {
ResponseType.Success -> (localVarResponse as Success<*>).data as ApiResponse
ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.")
ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.")
ResponseType.ClientError -> {
val localVarError = localVarResponse as ClientError<*>
throw ClientException("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse)
}
ResponseType.ServerError -> {
val localVarError = localVarResponse as ServerError<*>
throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse)
}
}
}
}

View File

@ -0,0 +1,198 @@
/**
* 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.client.apis
import org.openapitools.client.models.Order
import org.openapitools.client.infrastructure.ApiClient
import org.openapitools.client.infrastructure.ClientException
import org.openapitools.client.infrastructure.ClientError
import org.openapitools.client.infrastructure.ServerException
import org.openapitools.client.infrastructure.ServerError
import org.openapitools.client.infrastructure.MultiValueMap
import org.openapitools.client.infrastructure.RequestConfig
import org.openapitools.client.infrastructure.RequestMethod
import org.openapitools.client.infrastructure.ResponseType
import org.openapitools.client.infrastructure.Success
import org.openapitools.client.infrastructure.toMultiValue
class StoreApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) {
companion object {
@JvmStatic
val defaultBasePath: String by lazy {
System.getProperties().getProperty("org.openapitools.client.baseUrl", "http://petstore.swagger.io/v2")
}
}
/**
* 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
* @return void
* @throws UnsupportedOperationException If the API returns an informational or redirection response
* @throws ClientException If the API returns a client error response
* @throws ServerException If the API returns a server error response
*/
@Throws(UnsupportedOperationException::class, ClientException::class, ServerException::class)
fun deleteOrder(orderId: kotlin.String) : Unit {
val localVariableBody: kotlin.Any? = null
val localVariableQuery: MultiValueMap = mutableMapOf()
val localVariableHeaders: MutableMap<String, String> = mutableMapOf()
val localVariableConfig = RequestConfig(
RequestMethod.DELETE,
"/store/order/{orderId}".replace("{"+"orderId"+"}", "$orderId"),
query = localVariableQuery,
headers = localVariableHeaders
)
val localVarResponse = request<Any?>(
localVariableConfig,
localVariableBody
)
return when (localVarResponse.responseType) {
ResponseType.Success -> Unit
ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.")
ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.")
ResponseType.ClientError -> {
val localVarError = localVarResponse as ClientError<*>
throw ClientException("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse)
}
ResponseType.ServerError -> {
val localVarError = localVarResponse as ServerError<*>
throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse)
}
}
}
/**
* Returns pet inventories by status
* Returns a map of status codes to quantities
* @return kotlin.collections.Map<kotlin.String, kotlin.Int>
* @throws UnsupportedOperationException If the API returns an informational or redirection response
* @throws ClientException If the API returns a client error response
* @throws ServerException If the API returns a server error response
*/
@Suppress("UNCHECKED_CAST")
@Throws(UnsupportedOperationException::class, ClientException::class, ServerException::class)
fun getInventory() : kotlin.collections.Map<kotlin.String, kotlin.Int> {
val localVariableBody: kotlin.Any? = null
val localVariableQuery: MultiValueMap = mutableMapOf()
val localVariableHeaders: MutableMap<String, String> = mutableMapOf()
val localVariableConfig = RequestConfig(
RequestMethod.GET,
"/store/inventory",
query = localVariableQuery,
headers = localVariableHeaders
)
val localVarResponse = request<kotlin.collections.Map<kotlin.String, kotlin.Int>>(
localVariableConfig,
localVariableBody
)
return when (localVarResponse.responseType) {
ResponseType.Success -> (localVarResponse as Success<*>).data as kotlin.collections.Map<kotlin.String, kotlin.Int>
ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.")
ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.")
ResponseType.ClientError -> {
val localVarError = localVarResponse as ClientError<*>
throw ClientException("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse)
}
ResponseType.ServerError -> {
val localVarError = localVarResponse as ServerError<*>
throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse)
}
}
}
/**
* 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
* @return Order
* @throws UnsupportedOperationException If the API returns an informational or redirection response
* @throws ClientException If the API returns a client error response
* @throws ServerException If the API returns a server error response
*/
@Suppress("UNCHECKED_CAST")
@Throws(UnsupportedOperationException::class, ClientException::class, ServerException::class)
fun getOrderById(orderId: kotlin.Long) : Order {
val localVariableBody: kotlin.Any? = null
val localVariableQuery: MultiValueMap = mutableMapOf()
val localVariableHeaders: MutableMap<String, String> = mutableMapOf()
val localVariableConfig = RequestConfig(
RequestMethod.GET,
"/store/order/{orderId}".replace("{"+"orderId"+"}", "$orderId"),
query = localVariableQuery,
headers = localVariableHeaders
)
val localVarResponse = request<Order>(
localVariableConfig,
localVariableBody
)
return when (localVarResponse.responseType) {
ResponseType.Success -> (localVarResponse as Success<*>).data as Order
ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.")
ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.")
ResponseType.ClientError -> {
val localVarError = localVarResponse as ClientError<*>
throw ClientException("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse)
}
ResponseType.ServerError -> {
val localVarError = localVarResponse as ServerError<*>
throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse)
}
}
}
/**
* Place an order for a pet
*
* @param body order placed for purchasing the pet
* @return Order
* @throws UnsupportedOperationException If the API returns an informational or redirection response
* @throws ClientException If the API returns a client error response
* @throws ServerException If the API returns a server error response
*/
@Suppress("UNCHECKED_CAST")
@Throws(UnsupportedOperationException::class, ClientException::class, ServerException::class)
fun placeOrder(body: Order) : Order {
val localVariableBody: kotlin.Any? = body
val localVariableQuery: MultiValueMap = mutableMapOf()
val localVariableHeaders: MutableMap<String, String> = mutableMapOf()
val localVariableConfig = RequestConfig(
RequestMethod.POST,
"/store/order",
query = localVariableQuery,
headers = localVariableHeaders
)
val localVarResponse = request<Order>(
localVariableConfig,
localVariableBody
)
return when (localVarResponse.responseType) {
ResponseType.Success -> (localVarResponse as Success<*>).data as Order
ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.")
ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.")
ResponseType.ClientError -> {
val localVarError = localVarResponse as ClientError<*>
throw ClientException("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse)
}
ResponseType.ServerError -> {
val localVarError = localVarResponse as ServerError<*>
throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse)
}
}
}
}

View File

@ -0,0 +1,363 @@
/**
* 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.client.apis
import org.openapitools.client.models.User
import org.openapitools.client.infrastructure.ApiClient
import org.openapitools.client.infrastructure.ClientException
import org.openapitools.client.infrastructure.ClientError
import org.openapitools.client.infrastructure.ServerException
import org.openapitools.client.infrastructure.ServerError
import org.openapitools.client.infrastructure.MultiValueMap
import org.openapitools.client.infrastructure.RequestConfig
import org.openapitools.client.infrastructure.RequestMethod
import org.openapitools.client.infrastructure.ResponseType
import org.openapitools.client.infrastructure.Success
import org.openapitools.client.infrastructure.toMultiValue
class UserApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) {
companion object {
@JvmStatic
val defaultBasePath: String by lazy {
System.getProperties().getProperty("org.openapitools.client.baseUrl", "http://petstore.swagger.io/v2")
}
}
/**
* Create user
* This can only be done by the logged in user.
* @param body Created user object
* @return void
* @throws UnsupportedOperationException If the API returns an informational or redirection response
* @throws ClientException If the API returns a client error response
* @throws ServerException If the API returns a server error response
*/
@Throws(UnsupportedOperationException::class, ClientException::class, ServerException::class)
fun createUser(body: User) : Unit {
val localVariableBody: kotlin.Any? = body
val localVariableQuery: MultiValueMap = mutableMapOf()
val localVariableHeaders: MutableMap<String, String> = mutableMapOf()
val localVariableConfig = RequestConfig(
RequestMethod.POST,
"/user",
query = localVariableQuery,
headers = localVariableHeaders
)
val localVarResponse = request<Any?>(
localVariableConfig,
localVariableBody
)
return when (localVarResponse.responseType) {
ResponseType.Success -> Unit
ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.")
ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.")
ResponseType.ClientError -> {
val localVarError = localVarResponse as ClientError<*>
throw ClientException("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse)
}
ResponseType.ServerError -> {
val localVarError = localVarResponse as ServerError<*>
throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse)
}
}
}
/**
* Creates list of users with given input array
*
* @param body List of user object
* @return void
* @throws UnsupportedOperationException If the API returns an informational or redirection response
* @throws ClientException If the API returns a client error response
* @throws ServerException If the API returns a server error response
*/
@Throws(UnsupportedOperationException::class, ClientException::class, ServerException::class)
fun createUsersWithArrayInput(body: kotlin.collections.List<User>) : Unit {
val localVariableBody: kotlin.Any? = body
val localVariableQuery: MultiValueMap = mutableMapOf()
val localVariableHeaders: MutableMap<String, String> = mutableMapOf()
val localVariableConfig = RequestConfig(
RequestMethod.POST,
"/user/createWithArray",
query = localVariableQuery,
headers = localVariableHeaders
)
val localVarResponse = request<Any?>(
localVariableConfig,
localVariableBody
)
return when (localVarResponse.responseType) {
ResponseType.Success -> Unit
ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.")
ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.")
ResponseType.ClientError -> {
val localVarError = localVarResponse as ClientError<*>
throw ClientException("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse)
}
ResponseType.ServerError -> {
val localVarError = localVarResponse as ServerError<*>
throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse)
}
}
}
/**
* Creates list of users with given input array
*
* @param body List of user object
* @return void
* @throws UnsupportedOperationException If the API returns an informational or redirection response
* @throws ClientException If the API returns a client error response
* @throws ServerException If the API returns a server error response
*/
@Throws(UnsupportedOperationException::class, ClientException::class, ServerException::class)
fun createUsersWithListInput(body: kotlin.collections.List<User>) : Unit {
val localVariableBody: kotlin.Any? = body
val localVariableQuery: MultiValueMap = mutableMapOf()
val localVariableHeaders: MutableMap<String, String> = mutableMapOf()
val localVariableConfig = RequestConfig(
RequestMethod.POST,
"/user/createWithList",
query = localVariableQuery,
headers = localVariableHeaders
)
val localVarResponse = request<Any?>(
localVariableConfig,
localVariableBody
)
return when (localVarResponse.responseType) {
ResponseType.Success -> Unit
ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.")
ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.")
ResponseType.ClientError -> {
val localVarError = localVarResponse as ClientError<*>
throw ClientException("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse)
}
ResponseType.ServerError -> {
val localVarError = localVarResponse as ServerError<*>
throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse)
}
}
}
/**
* Delete user
* This can only be done by the logged in user.
* @param username The name that needs to be deleted
* @return void
* @throws UnsupportedOperationException If the API returns an informational or redirection response
* @throws ClientException If the API returns a client error response
* @throws ServerException If the API returns a server error response
*/
@Throws(UnsupportedOperationException::class, ClientException::class, ServerException::class)
fun deleteUser(username: kotlin.String) : Unit {
val localVariableBody: kotlin.Any? = null
val localVariableQuery: MultiValueMap = mutableMapOf()
val localVariableHeaders: MutableMap<String, String> = mutableMapOf()
val localVariableConfig = RequestConfig(
RequestMethod.DELETE,
"/user/{username}".replace("{"+"username"+"}", "$username"),
query = localVariableQuery,
headers = localVariableHeaders
)
val localVarResponse = request<Any?>(
localVariableConfig,
localVariableBody
)
return when (localVarResponse.responseType) {
ResponseType.Success -> Unit
ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.")
ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.")
ResponseType.ClientError -> {
val localVarError = localVarResponse as ClientError<*>
throw ClientException("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse)
}
ResponseType.ServerError -> {
val localVarError = localVarResponse as ServerError<*>
throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse)
}
}
}
/**
* Get user by user name
*
* @param username The name that needs to be fetched. Use user1 for testing.
* @return User
* @throws UnsupportedOperationException If the API returns an informational or redirection response
* @throws ClientException If the API returns a client error response
* @throws ServerException If the API returns a server error response
*/
@Suppress("UNCHECKED_CAST")
@Throws(UnsupportedOperationException::class, ClientException::class, ServerException::class)
fun getUserByName(username: kotlin.String) : User {
val localVariableBody: kotlin.Any? = null
val localVariableQuery: MultiValueMap = mutableMapOf()
val localVariableHeaders: MutableMap<String, String> = mutableMapOf()
val localVariableConfig = RequestConfig(
RequestMethod.GET,
"/user/{username}".replace("{"+"username"+"}", "$username"),
query = localVariableQuery,
headers = localVariableHeaders
)
val localVarResponse = request<User>(
localVariableConfig,
localVariableBody
)
return when (localVarResponse.responseType) {
ResponseType.Success -> (localVarResponse as Success<*>).data as User
ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.")
ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.")
ResponseType.ClientError -> {
val localVarError = localVarResponse as ClientError<*>
throw ClientException("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse)
}
ResponseType.ServerError -> {
val localVarError = localVarResponse as ServerError<*>
throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse)
}
}
}
/**
* Logs user into the system
*
* @param username The user name for login
* @param password The password for login in clear text
* @return kotlin.String
* @throws UnsupportedOperationException If the API returns an informational or redirection response
* @throws ClientException If the API returns a client error response
* @throws ServerException If the API returns a server error response
*/
@Suppress("UNCHECKED_CAST")
@Throws(UnsupportedOperationException::class, ClientException::class, ServerException::class)
fun loginUser(username: kotlin.String, password: kotlin.String) : kotlin.String {
val localVariableBody: kotlin.Any? = null
val localVariableQuery: MultiValueMap = mutableMapOf<kotlin.String, List<kotlin.String>>()
.apply {
put("username", listOf(username.toString()))
put("password", listOf(password.toString()))
}
val localVariableHeaders: MutableMap<String, String> = mutableMapOf()
val localVariableConfig = RequestConfig(
RequestMethod.GET,
"/user/login",
query = localVariableQuery,
headers = localVariableHeaders
)
val localVarResponse = request<kotlin.String>(
localVariableConfig,
localVariableBody
)
return when (localVarResponse.responseType) {
ResponseType.Success -> (localVarResponse as Success<*>).data as kotlin.String
ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.")
ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.")
ResponseType.ClientError -> {
val localVarError = localVarResponse as ClientError<*>
throw ClientException("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse)
}
ResponseType.ServerError -> {
val localVarError = localVarResponse as ServerError<*>
throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse)
}
}
}
/**
* Logs out current logged in user session
*
* @return void
* @throws UnsupportedOperationException If the API returns an informational or redirection response
* @throws ClientException If the API returns a client error response
* @throws ServerException If the API returns a server error response
*/
@Throws(UnsupportedOperationException::class, ClientException::class, ServerException::class)
fun logoutUser() : Unit {
val localVariableBody: kotlin.Any? = null
val localVariableQuery: MultiValueMap = mutableMapOf()
val localVariableHeaders: MutableMap<String, String> = mutableMapOf()
val localVariableConfig = RequestConfig(
RequestMethod.GET,
"/user/logout",
query = localVariableQuery,
headers = localVariableHeaders
)
val localVarResponse = request<Any?>(
localVariableConfig,
localVariableBody
)
return when (localVarResponse.responseType) {
ResponseType.Success -> Unit
ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.")
ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.")
ResponseType.ClientError -> {
val localVarError = localVarResponse as ClientError<*>
throw ClientException("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse)
}
ResponseType.ServerError -> {
val localVarError = localVarResponse as ServerError<*>
throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse)
}
}
}
/**
* 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
* @return void
* @throws UnsupportedOperationException If the API returns an informational or redirection response
* @throws ClientException If the API returns a client error response
* @throws ServerException If the API returns a server error response
*/
@Throws(UnsupportedOperationException::class, ClientException::class, ServerException::class)
fun updateUser(username: kotlin.String, body: User) : Unit {
val localVariableBody: kotlin.Any? = body
val localVariableQuery: MultiValueMap = mutableMapOf()
val localVariableHeaders: MutableMap<String, String> = mutableMapOf()
val localVariableConfig = RequestConfig(
RequestMethod.PUT,
"/user/{username}".replace("{"+"username"+"}", "$username"),
query = localVariableQuery,
headers = localVariableHeaders
)
val localVarResponse = request<Any?>(
localVariableConfig,
localVariableBody
)
return when (localVarResponse.responseType) {
ResponseType.Success -> Unit
ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.")
ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.")
ResponseType.ClientError -> {
val localVarError = localVarResponse as ClientError<*>
throw ClientException("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse)
}
ResponseType.ServerError -> {
val localVarError = localVarResponse as ServerError<*>
throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse)
}
}
}
}

View File

@ -0,0 +1,23 @@
package org.openapitools.client.infrastructure
typealias MultiValueMap = MutableMap<String,List<String>>
fun collectionDelimiter(collectionFormat: String) = when(collectionFormat) {
"csv" -> ","
"tsv" -> "\t"
"pipe" -> "|"
"space" -> " "
else -> ""
}
val defaultMultiValueConverter: (item: Any?) -> String = { item -> "$item" }
fun <T : Any?> toMultiValue(items: Array<T>, collectionFormat: String, map: (item: T) -> String = defaultMultiValueConverter)
= toMultiValue(items.asIterable(), collectionFormat, map)
fun <T : Any?> toMultiValue(items: Iterable<T>, collectionFormat: String, map: (item: T) -> String = defaultMultiValueConverter): List<String> {
return when(collectionFormat) {
"multi" -> items.map(map)
else -> listOf(items.joinToString(separator = collectionDelimiter(collectionFormat), transform = map))
}
}

View File

@ -0,0 +1,251 @@
package org.openapitools.client.infrastructure
import okhttp3.Credentials
import okhttp3.OkHttpClient
import okhttp3.RequestBody
import okhttp3.RequestBody.Companion.asRequestBody
import okhttp3.RequestBody.Companion.toRequestBody
import okhttp3.FormBody
import okhttp3.HttpUrl.Companion.toHttpUrlOrNull
import okhttp3.ResponseBody
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.Request
import okhttp3.Headers
import okhttp3.MultipartBody
import java.io.File
import java.net.URLConnection
import java.util.Date
import java.time.LocalDate
import java.time.LocalDateTime
import java.time.LocalTime
import java.time.OffsetDateTime
import java.time.OffsetTime
open class ApiClient(val baseUrl: String) {
companion object {
protected const val ContentType = "Content-Type"
protected const val Accept = "Accept"
protected const val Authorization = "Authorization"
protected const val JsonMediaType = "application/json"
protected const val FormDataMediaType = "multipart/form-data"
protected const val FormUrlEncMediaType = "application/x-www-form-urlencoded"
protected const val XmlMediaType = "application/xml"
val apiKey: MutableMap<String, String> = mutableMapOf()
val apiKeyPrefix: MutableMap<String, String> = mutableMapOf()
var username: String? = null
var password: String? = null
var accessToken: String? = null
@JvmStatic
val client: OkHttpClient by lazy {
builder.build()
}
@JvmStatic
val builder: OkHttpClient.Builder = OkHttpClient.Builder()
}
/**
* Guess Content-Type header from the given file (defaults to "application/octet-stream").
*
* @param file The given file
* @return The guessed Content-Type
*/
protected fun guessContentTypeFromFile(file: File): String {
val contentType = URLConnection.guessContentTypeFromName(file.name)
return contentType ?: "application/octet-stream"
}
protected inline fun <reified T> requestBody(content: T, mediaType: String = JsonMediaType): RequestBody =
when {
content is File -> content.asRequestBody(
mediaType.toMediaTypeOrNull()
)
mediaType == FormDataMediaType -> {
MultipartBody.Builder()
.setType(MultipartBody.FORM)
.apply {
// content's type *must* be Map<String, Any?>
@Suppress("UNCHECKED_CAST")
(content as Map<String, Any?>).forEach { (key, value) ->
if (value is File) {
val partHeaders = Headers.headersOf(
"Content-Disposition",
"form-data; name=\"$key\"; filename=\"${value.name}\""
)
val fileMediaType = guessContentTypeFromFile(value).toMediaTypeOrNull()
addPart(partHeaders, value.asRequestBody(fileMediaType))
} else {
val partHeaders = Headers.headersOf(
"Content-Disposition",
"form-data; name=\"$key\""
)
addPart(
partHeaders,
parameterToString(value).toRequestBody(null)
)
}
}
}.build()
}
mediaType == FormUrlEncMediaType -> {
FormBody.Builder().apply {
// content's type *must* be Map<String, Any?>
@Suppress("UNCHECKED_CAST")
(content as Map<String, Any?>).forEach { (key, value) ->
add(key, parameterToString(value))
}
}.build()
}
mediaType == JsonMediaType -> Serializer.gson.toJson(content, T::class.java).toRequestBody(
mediaType.toMediaTypeOrNull()
)
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.")
}
protected inline fun <reified T: Any?> responseBody(body: ResponseBody?, mediaType: String? = JsonMediaType): T? {
if(body == null) {
return null
}
val bodyContent = body.string()
if (bodyContent.isEmpty()) {
return null
}
return when(mediaType) {
JsonMediaType -> Serializer.gson.fromJson(bodyContent, T::class.java)
else -> throw UnsupportedOperationException("responseBody currently only supports JSON body.")
}
}
protected fun updateAuthParams(requestConfig: RequestConfig) {
if (requestConfig.headers["api_key"].isNullOrEmpty()) {
if (apiKey["api_key"] != null) {
if (apiKeyPrefix["api_key"] != null) {
requestConfig.headers["api_key"] = apiKeyPrefix["api_key"]!! + " " + apiKey["api_key"]!!
} else {
requestConfig.headers["api_key"] = apiKey["api_key"]!!
}
}
}
if (requestConfig.headers[Authorization].isNullOrEmpty()) {
accessToken?.let { accessToken ->
requestConfig.headers[Authorization] = "Bearer $accessToken "
}
}
}
protected inline fun <reified T: Any?> request(requestConfig: RequestConfig, body : Any? = null): ApiInfrastructureResponse<T?> {
val httpUrl = baseUrl.toHttpUrlOrNull() ?: throw IllegalStateException("baseUrl is invalid.")
// take authMethod from operation
updateAuthParams(requestConfig)
val url = httpUrl.newBuilder()
.addPathSegments(requestConfig.path.trimStart('/'))
.apply {
requestConfig.query.forEach { query ->
query.value.forEach { queryValue ->
addQueryParameter(query.key, queryValue)
}
}
}.build()
// take content-type/accept from spec or set to default (application/json) if not defined
if (requestConfig.headers[ContentType].isNullOrEmpty()) {
requestConfig.headers[ContentType] = JsonMediaType
}
if (requestConfig.headers[Accept].isNullOrEmpty()) {
requestConfig.headers[Accept] = JsonMediaType
}
val headers = requestConfig.headers
if(headers[ContentType] ?: "" == "") {
throw kotlin.IllegalStateException("Missing Content-Type header. This is required.")
}
if(headers[Accept] ?: "" == "") {
throw kotlin.IllegalStateException("Missing Accept header. This is required.")
}
// TODO: support multiple contentType options here.
val contentType = (headers[ContentType] as String).substringBefore(";").toLowerCase()
val request = when (requestConfig.method) {
RequestMethod.DELETE -> Request.Builder().url(url).delete(requestBody(body, contentType))
RequestMethod.GET -> Request.Builder().url(url)
RequestMethod.HEAD -> Request.Builder().url(url).head()
RequestMethod.PATCH -> Request.Builder().url(url).patch(requestBody(body, contentType))
RequestMethod.PUT -> Request.Builder().url(url).put(requestBody(body, contentType))
RequestMethod.POST -> Request.Builder().url(url).post(requestBody(body, contentType))
RequestMethod.OPTIONS -> Request.Builder().url(url).method("OPTIONS", null)
}.apply {
headers.forEach { header -> addHeader(header.key, header.value) }
}.build()
val response = client.newCall(request).execute()
val accept = response.header(ContentType)?.substringBefore(";")?.toLowerCase()
// TODO: handle specific mapping types. e.g. Map<int, Class<?>>
when {
response.isRedirect -> return Redirection(
response.code,
response.headers.toMultimap()
)
response.isInformational -> return Informational(
response.message,
response.code,
response.headers.toMultimap()
)
response.isSuccessful -> return Success(
responseBody(response.body, accept),
response.code,
response.headers.toMultimap()
)
response.isClientError -> return ClientError(
response.message,
response.body?.string(),
response.code,
response.headers.toMultimap()
)
else -> return ServerError(
response.message,
response.body?.string(),
response.code,
response.headers.toMultimap()
)
}
}
protected fun parameterToString(value: Any?): String {
when (value) {
null -> {
return ""
}
is Array<*> -> {
return toMultiValue(value, "csv").toString()
}
is Iterable<*> -> {
return toMultiValue(value, "csv").toString()
}
is OffsetDateTime, is OffsetTime, is LocalDateTime, is LocalDate, is LocalTime, is Date -> {
return parseDateToQueryString<Any>(value)
}
else -> {
return value.toString()
}
}
}
protected inline fun <reified T: Any> parseDateToQueryString(value : T): String {
/*
.replace("\"", "") converts the json object string to an actual string for the query parameter.
The moshi or gson adapter allows a more generic solution instead of trying to use a native
formatter. It also easily allows to provide a simple way to define a custom date format pattern
inside a gson/moshi adapter.
*/
return Serializer.gson.toJson(value, T::class.java).replace("\"", "")
}
}

View File

@ -0,0 +1,43 @@
package org.openapitools.client.infrastructure
enum class ResponseType {
Success, Informational, Redirection, ClientError, ServerError
}
interface Response
abstract class ApiInfrastructureResponse<T>(val responseType: ResponseType): Response {
abstract val statusCode: Int
abstract val headers: Map<String,List<String>>
}
class Success<T>(
val data: T,
override val statusCode: Int = -1,
override val headers: Map<String, List<String>> = mapOf()
): ApiInfrastructureResponse<T>(ResponseType.Success)
class Informational<T>(
val statusText: String,
override val statusCode: Int = -1,
override val headers: Map<String, List<String>> = mapOf()
) : ApiInfrastructureResponse<T>(ResponseType.Informational)
class Redirection<T>(
override val statusCode: Int = -1,
override val headers: Map<String, List<String>> = mapOf()
) : ApiInfrastructureResponse<T>(ResponseType.Redirection)
class ClientError<T>(
val message: String? = null,
val body: Any? = null,
override val statusCode: Int = -1,
override val headers: Map<String, List<String>> = mapOf()
) : ApiInfrastructureResponse<T>(ResponseType.ClientError)
class ServerError<T>(
val message: String? = null,
val body: Any? = null,
override val statusCode: Int = -1,
override val headers: Map<String, List<String>>
): ApiInfrastructureResponse<T>(ResponseType.ServerError)

View File

@ -0,0 +1,29 @@
package org.openapitools.client.infrastructure
import kotlin.properties.ReadWriteProperty
import kotlin.reflect.KProperty
object ApplicationDelegates {
/**
* Provides a property delegate, allowing the property to be set once and only once.
*
* If unset (no default value), a get on the property will throw [IllegalStateException].
*/
fun <T> setOnce(defaultValue: T? = null) : ReadWriteProperty<Any?, T> = SetOnce(defaultValue)
private class SetOnce<T>(defaultValue: T? = null) : ReadWriteProperty<Any?, T> {
private var isSet = false
private var value: T? = defaultValue
override fun getValue(thisRef: Any?, property: KProperty<*>): T {
return value ?: throw IllegalStateException("${property.name} not initialized")
}
override fun setValue(thisRef: Any?, property: KProperty<*>, value: T) = synchronized(this) {
if (!isSet) {
this.value = value
isSet = true
}
}
}
}

View File

@ -0,0 +1,33 @@
package org.openapitools.client.infrastructure
import com.google.gson.TypeAdapter
import com.google.gson.stream.JsonReader
import com.google.gson.stream.JsonWriter
import com.google.gson.stream.JsonToken.NULL
import java.io.IOException
class ByteArrayAdapter : TypeAdapter<ByteArray>() {
@Throws(IOException::class)
override fun write(out: JsonWriter?, value: ByteArray?) {
if (value == null) {
out?.nullValue()
} else {
out?.value(String(value))
}
}
@Throws(IOException::class)
override fun read(out: JsonReader?): ByteArray? {
out ?: return null
when (out.peek()) {
NULL -> {
out.nextNull()
return null
}
else -> {
return out.nextString().toByteArray()
}
}
}
}

View File

@ -0,0 +1,37 @@
package org.openapitools.client.infrastructure
import com.google.gson.TypeAdapter
import com.google.gson.stream.JsonReader
import com.google.gson.stream.JsonWriter
import com.google.gson.stream.JsonToken.NULL
import java.io.IOException
import java.text.DateFormat
import java.text.SimpleDateFormat
import java.util.Date
import java.util.Locale
class DateAdapter(val formatter: DateFormat = SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ", Locale.getDefault())) : TypeAdapter<Date>() {
@Throws(IOException::class)
override fun write(out: JsonWriter?, value: Date?) {
if (value == null) {
out?.nullValue()
} else {
out?.value(formatter.format(value))
}
}
@Throws(IOException::class)
override fun read(out: JsonReader?): Date? {
out ?: return null
when (out.peek()) {
NULL -> {
out.nextNull()
return null
}
else -> {
return formatter.parse(out.nextString())
}
}
}
}

View File

@ -0,0 +1,18 @@
@file:Suppress("unused")
package org.openapitools.client.infrastructure
import java.lang.RuntimeException
open class ClientException(message: kotlin.String? = null, val statusCode: Int = -1, val response: Response? = null) : RuntimeException(message) {
companion object {
private const val serialVersionUID: Long = 123L
}
}
open class ServerException(message: kotlin.String? = null, val statusCode: Int = -1, val response: Response? = null) : RuntimeException(message) {
companion object {
private const val serialVersionUID: Long = 456L
}
}

View File

@ -0,0 +1,35 @@
package org.openapitools.client.infrastructure
import com.google.gson.TypeAdapter
import com.google.gson.stream.JsonReader
import com.google.gson.stream.JsonWriter
import com.google.gson.stream.JsonToken.NULL
import java.io.IOException
import java.time.LocalDate
import java.time.format.DateTimeFormatter
class LocalDateAdapter(private val formatter: DateTimeFormatter = DateTimeFormatter.ISO_LOCAL_DATE) : TypeAdapter<LocalDate>() {
@Throws(IOException::class)
override fun write(out: JsonWriter?, value: LocalDate?) {
if (value == null) {
out?.nullValue()
} else {
out?.value(formatter.format(value))
}
}
@Throws(IOException::class)
override fun read(out: JsonReader?): LocalDate? {
out ?: return null
when (out.peek()) {
NULL -> {
out.nextNull()
return null
}
else -> {
return LocalDate.parse(out.nextString(), formatter)
}
}
}
}

View File

@ -0,0 +1,35 @@
package org.openapitools.client.infrastructure
import com.google.gson.TypeAdapter
import com.google.gson.stream.JsonReader
import com.google.gson.stream.JsonWriter
import com.google.gson.stream.JsonToken.NULL
import java.io.IOException
import java.time.LocalDateTime
import java.time.format.DateTimeFormatter
class LocalDateTimeAdapter(private val formatter: DateTimeFormatter = DateTimeFormatter.ISO_LOCAL_DATE_TIME) : TypeAdapter<LocalDateTime>() {
@Throws(IOException::class)
override fun write(out: JsonWriter?, value: LocalDateTime?) {
if (value == null) {
out?.nullValue()
} else {
out?.value(formatter.format(value))
}
}
@Throws(IOException::class)
override fun read(out: JsonReader?): LocalDateTime? {
out ?: return null
when (out.peek()) {
NULL -> {
out.nextNull()
return null
}
else -> {
return LocalDateTime.parse(out.nextString(), formatter)
}
}
}
}

View File

@ -0,0 +1,35 @@
package org.openapitools.client.infrastructure
import com.google.gson.TypeAdapter
import com.google.gson.stream.JsonReader
import com.google.gson.stream.JsonWriter
import com.google.gson.stream.JsonToken.NULL
import java.io.IOException
import java.time.OffsetDateTime
import java.time.format.DateTimeFormatter
class OffsetDateTimeAdapter(private val formatter: DateTimeFormatter = DateTimeFormatter.ISO_OFFSET_DATE_TIME) : TypeAdapter<OffsetDateTime>() {
@Throws(IOException::class)
override fun write(out: JsonWriter?, value: OffsetDateTime?) {
if (value == null) {
out?.nullValue()
} else {
out?.value(formatter.format(value))
}
}
@Throws(IOException::class)
override fun read(out: JsonReader?): OffsetDateTime? {
out ?: return null
when (out.peek()) {
NULL -> {
out.nextNull()
return null
}
else -> {
return OffsetDateTime.parse(out.nextString(), formatter)
}
}
}
}

View File

@ -0,0 +1,16 @@
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<String,String> because rfc2616 defines
* multi-valued headers as csv-only.
*/
data class RequestConfig(
val method: RequestMethod,
val path: String,
val headers: MutableMap<String, String> = mutableMapOf(),
val query: MutableMap<String, List<String>> = mutableMapOf()
)

View File

@ -0,0 +1,8 @@
package org.openapitools.client.infrastructure
/**
* Provides enumerated HTTP verbs
*/
enum class RequestMethod {
GET, DELETE, HEAD, OPTIONS, PATCH, POST, PUT
}

View File

@ -0,0 +1,24 @@
package org.openapitools.client.infrastructure
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
/**
* Provides an extension to evaluation whether the response is a 3xx code
*/
@Suppress("EXTENSION_SHADOWED_BY_MEMBER")
val Response.isRedirect : Boolean get() = this.code 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
/**
* 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

View File

@ -0,0 +1,24 @@
package org.openapitools.client.infrastructure
import com.google.gson.Gson
import com.google.gson.GsonBuilder
import java.time.LocalDate
import java.time.LocalDateTime
import java.time.OffsetDateTime
import java.util.UUID
import java.util.Date
object Serializer {
@JvmStatic
val gsonBuilder: GsonBuilder = GsonBuilder()
.registerTypeAdapter(Date::class.java, DateAdapter())
.registerTypeAdapter(OffsetDateTime::class.java, OffsetDateTimeAdapter())
.registerTypeAdapter(LocalDateTime::class.java, LocalDateTimeAdapter())
.registerTypeAdapter(LocalDate::class.java, LocalDateAdapter())
.registerTypeAdapter(ByteArray::class.java, ByteArrayAdapter())
@JvmStatic
val gson: Gson by lazy {
gsonBuilder.create()
}
}

View File

@ -0,0 +1,32 @@
/**
* 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.client.models
import com.google.gson.annotations.SerializedName
/**
* Describes the result of uploading an image resource
* @param code
* @param type
* @param message
*/
data class ApiResponse (
@SerializedName("code")
val code: kotlin.Int? = null,
@SerializedName("type")
val type: kotlin.String? = null,
@SerializedName("message")
val message: kotlin.String? = null
)

View File

@ -0,0 +1,29 @@
/**
* 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.client.models
import com.google.gson.annotations.SerializedName
/**
* A category for a pet
* @param id
* @param name
*/
data class Category (
@SerializedName("id")
val id: kotlin.Long? = null,
@SerializedName("name")
val name: kotlin.String? = null
)

View File

@ -0,0 +1,54 @@
/**
* 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.client.models
import com.google.gson.annotations.SerializedName
/**
* 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 (
@SerializedName("id")
val id: kotlin.Long? = null,
@SerializedName("petId")
val petId: kotlin.Long? = null,
@SerializedName("quantity")
val quantity: kotlin.Int? = null,
@SerializedName("shipDate")
val shipDate: java.time.OffsetDateTime? = null,
/* Order Status */
@SerializedName("status")
val status: Order.Status? = null,
@SerializedName("complete")
val complete: kotlin.Boolean? = null
) {
/**
* Order Status
* Values: placed,approved,delivered
*/
enum class Status(val value: kotlin.String){
@SerializedName(value = "placed") placed("placed"),
@SerializedName(value = "approved") approved("approved"),
@SerializedName(value = "delivered") delivered("delivered");
}
}

View File

@ -0,0 +1,56 @@
/**
* 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.client.models
import org.openapitools.client.models.Category
import org.openapitools.client.models.Tag
import com.google.gson.annotations.SerializedName
/**
* 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 (
@SerializedName("name")
val name: kotlin.String,
@SerializedName("photoUrls")
val photoUrls: kotlin.collections.List<kotlin.String>,
@SerializedName("id")
val id: kotlin.Long? = null,
@SerializedName("category")
val category: Category? = null,
@SerializedName("tags")
val tags: kotlin.collections.List<Tag>? = null,
/* pet status in the store */
@SerializedName("status")
val status: Pet.Status? = null
) {
/**
* pet status in the store
* Values: available,pending,sold
*/
enum class Status(val value: kotlin.String){
@SerializedName(value = "available") available("available"),
@SerializedName(value = "pending") pending("pending"),
@SerializedName(value = "sold") sold("sold");
}
}

View File

@ -0,0 +1,29 @@
/**
* 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.client.models
import com.google.gson.annotations.SerializedName
/**
* A tag for a pet
* @param id
* @param name
*/
data class Tag (
@SerializedName("id")
val id: kotlin.Long? = null,
@SerializedName("name")
val name: kotlin.String? = null
)

View File

@ -0,0 +1,48 @@
/**
* 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.client.models
import com.google.gson.annotations.SerializedName
/**
* 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 (
@SerializedName("id")
val id: kotlin.Long? = null,
@SerializedName("username")
val username: kotlin.String? = null,
@SerializedName("firstName")
val firstName: kotlin.String? = null,
@SerializedName("lastName")
val lastName: kotlin.String? = null,
@SerializedName("email")
val email: kotlin.String? = null,
@SerializedName("password")
val password: kotlin.String? = null,
@SerializedName("phone")
val phone: kotlin.String? = null,
/* User Status */
@SerializedName("userStatus")
val userStatus: kotlin.Int? = null
)

View File

@ -0,0 +1,20 @@
package org.openapitools
import org.openapitools.client.apis.PetApi
import org.openapitools.client.apis.StoreApi
import org.openapitools.client.models.Category
import org.openapitools.client.models.Pet
import org.openapitools.client.models.Tag
fun main() {
println("<top>.main")
val inventory = StoreApi().getInventory()
println("Inventory : $inventory")
val pet = Pet(name = "Elliot", photoUrls = listOf<String>("https://jameshooverstudios.com/wp-content/uploads/2015/04/Majestic-Dog-Photography-Elliot-Nov-5-2014.jpg", "https://express-images.franklymedia.com/6616/sites/981/2020/01/22105725/Elliott.jpg"), id = 123456453, category = Category(id = 13259476, name = "dog"), tags = listOf<Tag>(Tag(id = 194093, name = "Elliot")), status = Pet.Status.AVAILABLE)
PetApi().addPet(pet)
val elliot = PetApi().getPetById(123456453)
println("Elliot : $elliot")
assert(pet == elliot)
println("<bottom>.main")
}

View File

@ -0,0 +1,374 @@
/**
* 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.client.apis
import org.openapitools.client.models.ApiResponse
import org.openapitools.client.models.Pet
import org.openapitools.client.infrastructure.ApiClient
import org.openapitools.client.infrastructure.ClientException
import org.openapitools.client.infrastructure.ClientError
import org.openapitools.client.infrastructure.ServerException
import org.openapitools.client.infrastructure.ServerError
import org.openapitools.client.infrastructure.MultiValueMap
import org.openapitools.client.infrastructure.RequestConfig
import org.openapitools.client.infrastructure.RequestMethod
import org.openapitools.client.infrastructure.ResponseType
import org.openapitools.client.infrastructure.Success
import org.openapitools.client.infrastructure.toMultiValue
class PetApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) {
companion object {
@JvmStatic
val defaultBasePath: String by lazy {
System.getProperties().getProperty("org.openapitools.client.baseUrl", "http://petstore.swagger.io/v2")
}
}
/**
* Add a new pet to the store
*
* @param body Pet object that needs to be added to the store
* @return void
* @throws UnsupportedOperationException If the API returns an informational or redirection response
* @throws ClientException If the API returns a client error response
* @throws ServerException If the API returns a server error response
*/
@Throws(UnsupportedOperationException::class, ClientException::class, ServerException::class)
fun addPet(body: Pet) : Unit {
val localVariableBody: kotlin.Any? = body
val localVariableQuery: MultiValueMap = mutableMapOf()
val localVariableHeaders: MutableMap<String, String> = mutableMapOf()
val localVariableConfig = RequestConfig(
RequestMethod.POST,
"/pet",
query = localVariableQuery,
headers = localVariableHeaders
)
val localVarResponse = request<Any?>(
localVariableConfig,
localVariableBody
)
return when (localVarResponse.responseType) {
ResponseType.Success -> Unit
ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.")
ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.")
ResponseType.ClientError -> {
val localVarError = localVarResponse as ClientError<*>
throw ClientException("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse)
}
ResponseType.ServerError -> {
val localVarError = localVarResponse as ServerError<*>
throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse)
}
}
}
/**
* Deletes a pet
*
* @param petId Pet id to delete
* @param apiKey (optional)
* @return void
* @throws UnsupportedOperationException If the API returns an informational or redirection response
* @throws ClientException If the API returns a client error response
* @throws ServerException If the API returns a server error response
*/
@Throws(UnsupportedOperationException::class, ClientException::class, ServerException::class)
fun deletePet(petId: kotlin.Long, apiKey: kotlin.String?) : Unit {
val localVariableBody: kotlin.Any? = null
val localVariableQuery: MultiValueMap = mutableMapOf()
val localVariableHeaders: MutableMap<String, String> = mutableMapOf()
apiKey?.apply { localVariableHeaders["api_key"] = this.toString() }
val localVariableConfig = RequestConfig(
RequestMethod.DELETE,
"/pet/{petId}".replace("{"+"petId"+"}", "$petId"),
query = localVariableQuery,
headers = localVariableHeaders
)
val localVarResponse = request<Any?>(
localVariableConfig,
localVariableBody
)
return when (localVarResponse.responseType) {
ResponseType.Success -> Unit
ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.")
ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.")
ResponseType.ClientError -> {
val localVarError = localVarResponse as ClientError<*>
throw ClientException("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse)
}
ResponseType.ServerError -> {
val localVarError = localVarResponse as ServerError<*>
throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse)
}
}
}
/**
* 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
* @return kotlin.collections.List<Pet>
* @throws UnsupportedOperationException If the API returns an informational or redirection response
* @throws ClientException If the API returns a client error response
* @throws ServerException If the API returns a server error response
*/
@Suppress("UNCHECKED_CAST")
@Throws(UnsupportedOperationException::class, ClientException::class, ServerException::class)
fun findPetsByStatus(status: kotlin.collections.List<kotlin.String>) : kotlin.collections.List<Pet> {
val localVariableBody: kotlin.Any? = null
val localVariableQuery: MultiValueMap = mutableMapOf<kotlin.String, List<kotlin.String>>()
.apply {
put("status", toMultiValue(status.toList(), "csv"))
}
val localVariableHeaders: MutableMap<String, String> = mutableMapOf()
val localVariableConfig = RequestConfig(
RequestMethod.GET,
"/pet/findByStatus",
query = localVariableQuery,
headers = localVariableHeaders
)
val localVarResponse = request<kotlin.collections.List<Pet>>(
localVariableConfig,
localVariableBody
)
return when (localVarResponse.responseType) {
ResponseType.Success -> (localVarResponse as Success<*>).data as kotlin.collections.List<Pet>
ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.")
ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.")
ResponseType.ClientError -> {
val localVarError = localVarResponse as ClientError<*>
throw ClientException("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse)
}
ResponseType.ServerError -> {
val localVarError = localVarResponse as ServerError<*>
throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse)
}
}
}
/**
* 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
* @return kotlin.collections.List<Pet>
* @throws UnsupportedOperationException If the API returns an informational or redirection response
* @throws ClientException If the API returns a client error response
* @throws ServerException If the API returns a server error response
*/
@Suppress("UNCHECKED_CAST")
@Throws(UnsupportedOperationException::class, ClientException::class, ServerException::class)
@Deprecated(message = "This operation is deprecated.")
fun findPetsByTags(tags: kotlin.collections.List<kotlin.String>) : kotlin.collections.List<Pet> {
val localVariableBody: kotlin.Any? = null
val localVariableQuery: MultiValueMap = mutableMapOf<kotlin.String, List<kotlin.String>>()
.apply {
put("tags", toMultiValue(tags.toList(), "csv"))
}
val localVariableHeaders: MutableMap<String, String> = mutableMapOf()
val localVariableConfig = RequestConfig(
RequestMethod.GET,
"/pet/findByTags",
query = localVariableQuery,
headers = localVariableHeaders
)
val localVarResponse = request<kotlin.collections.List<Pet>>(
localVariableConfig,
localVariableBody
)
return when (localVarResponse.responseType) {
ResponseType.Success -> (localVarResponse as Success<*>).data as kotlin.collections.List<Pet>
ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.")
ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.")
ResponseType.ClientError -> {
val localVarError = localVarResponse as ClientError<*>
throw ClientException("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse)
}
ResponseType.ServerError -> {
val localVarError = localVarResponse as ServerError<*>
throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse)
}
}
}
/**
* Find pet by ID
* Returns a single pet
* @param petId ID of pet to return
* @return Pet
* @throws UnsupportedOperationException If the API returns an informational or redirection response
* @throws ClientException If the API returns a client error response
* @throws ServerException If the API returns a server error response
*/
@Suppress("UNCHECKED_CAST")
@Throws(UnsupportedOperationException::class, ClientException::class, ServerException::class)
fun getPetById(petId: kotlin.Long) : Pet {
val localVariableBody: kotlin.Any? = null
val localVariableQuery: MultiValueMap = mutableMapOf()
val localVariableHeaders: MutableMap<String, String> = mutableMapOf()
val localVariableConfig = RequestConfig(
RequestMethod.GET,
"/pet/{petId}".replace("{"+"petId"+"}", "$petId"),
query = localVariableQuery,
headers = localVariableHeaders
)
val localVarResponse = request<Pet>(
localVariableConfig,
localVariableBody
)
return when (localVarResponse.responseType) {
ResponseType.Success -> (localVarResponse as Success<*>).data as Pet
ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.")
ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.")
ResponseType.ClientError -> {
val localVarError = localVarResponse as ClientError<*>
throw ClientException("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse)
}
ResponseType.ServerError -> {
val localVarError = localVarResponse as ServerError<*>
throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse)
}
}
}
/**
* Update an existing pet
*
* @param body Pet object that needs to be added to the store
* @return void
* @throws UnsupportedOperationException If the API returns an informational or redirection response
* @throws ClientException If the API returns a client error response
* @throws ServerException If the API returns a server error response
*/
@Throws(UnsupportedOperationException::class, ClientException::class, ServerException::class)
fun updatePet(body: Pet) : Unit {
val localVariableBody: kotlin.Any? = body
val localVariableQuery: MultiValueMap = mutableMapOf()
val localVariableHeaders: MutableMap<String, String> = mutableMapOf()
val localVariableConfig = RequestConfig(
RequestMethod.PUT,
"/pet",
query = localVariableQuery,
headers = localVariableHeaders
)
val localVarResponse = request<Any?>(
localVariableConfig,
localVariableBody
)
return when (localVarResponse.responseType) {
ResponseType.Success -> Unit
ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.")
ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.")
ResponseType.ClientError -> {
val localVarError = localVarResponse as ClientError<*>
throw ClientException("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse)
}
ResponseType.ServerError -> {
val localVarError = localVarResponse as ServerError<*>
throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse)
}
}
}
/**
* 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)
* @return void
* @throws UnsupportedOperationException If the API returns an informational or redirection response
* @throws ClientException If the API returns a client error response
* @throws ServerException If the API returns a server error response
*/
@Throws(UnsupportedOperationException::class, ClientException::class, ServerException::class)
fun updatePetWithForm(petId: kotlin.Long, name: kotlin.String?, status: kotlin.String?) : Unit {
val localVariableBody: kotlin.Any? = mapOf("name" to name, "status" to status)
val localVariableQuery: MultiValueMap = mutableMapOf()
val localVariableHeaders: MutableMap<String, String> = mutableMapOf("Content-Type" to "application/x-www-form-urlencoded")
val localVariableConfig = RequestConfig(
RequestMethod.POST,
"/pet/{petId}".replace("{"+"petId"+"}", "$petId"),
query = localVariableQuery,
headers = localVariableHeaders
)
val localVarResponse = request<Any?>(
localVariableConfig,
localVariableBody
)
return when (localVarResponse.responseType) {
ResponseType.Success -> Unit
ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.")
ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.")
ResponseType.ClientError -> {
val localVarError = localVarResponse as ClientError<*>
throw ClientException("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse)
}
ResponseType.ServerError -> {
val localVarError = localVarResponse as ServerError<*>
throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse)
}
}
}
/**
* 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)
* @return ApiResponse
* @throws UnsupportedOperationException If the API returns an informational or redirection response
* @throws ClientException If the API returns a client error response
* @throws ServerException If the API returns a server error response
*/
@Suppress("UNCHECKED_CAST")
@Throws(UnsupportedOperationException::class, ClientException::class, ServerException::class)
fun uploadFile(petId: kotlin.Long, additionalMetadata: kotlin.String?, file: java.io.File?) : ApiResponse {
val localVariableBody: kotlin.Any? = mapOf("additionalMetadata" to additionalMetadata, "file" to file)
val localVariableQuery: MultiValueMap = mutableMapOf()
val localVariableHeaders: MutableMap<String, String> = mutableMapOf("Content-Type" to "multipart/form-data")
val localVariableConfig = RequestConfig(
RequestMethod.POST,
"/pet/{petId}/uploadImage".replace("{"+"petId"+"}", "$petId"),
query = localVariableQuery,
headers = localVariableHeaders
)
val localVarResponse = request<ApiResponse>(
localVariableConfig,
localVariableBody
)
return when (localVarResponse.responseType) {
ResponseType.Success -> (localVarResponse as Success<*>).data as ApiResponse
ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.")
ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.")
ResponseType.ClientError -> {
val localVarError = localVarResponse as ClientError<*>
throw ClientException("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse)
}
ResponseType.ServerError -> {
val localVarError = localVarResponse as ServerError<*>
throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse)
}
}
}
}

View File

@ -0,0 +1,198 @@
/**
* 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.client.apis
import org.openapitools.client.models.Order
import org.openapitools.client.infrastructure.ApiClient
import org.openapitools.client.infrastructure.ClientException
import org.openapitools.client.infrastructure.ClientError
import org.openapitools.client.infrastructure.ServerException
import org.openapitools.client.infrastructure.ServerError
import org.openapitools.client.infrastructure.MultiValueMap
import org.openapitools.client.infrastructure.RequestConfig
import org.openapitools.client.infrastructure.RequestMethod
import org.openapitools.client.infrastructure.ResponseType
import org.openapitools.client.infrastructure.Success
import org.openapitools.client.infrastructure.toMultiValue
class StoreApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) {
companion object {
@JvmStatic
val defaultBasePath: String by lazy {
System.getProperties().getProperty("org.openapitools.client.baseUrl", "http://petstore.swagger.io/v2")
}
}
/**
* 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
* @return void
* @throws UnsupportedOperationException If the API returns an informational or redirection response
* @throws ClientException If the API returns a client error response
* @throws ServerException If the API returns a server error response
*/
@Throws(UnsupportedOperationException::class, ClientException::class, ServerException::class)
fun deleteOrder(orderId: kotlin.String) : Unit {
val localVariableBody: kotlin.Any? = null
val localVariableQuery: MultiValueMap = mutableMapOf()
val localVariableHeaders: MutableMap<String, String> = mutableMapOf()
val localVariableConfig = RequestConfig(
RequestMethod.DELETE,
"/store/order/{orderId}".replace("{"+"orderId"+"}", "$orderId"),
query = localVariableQuery,
headers = localVariableHeaders
)
val localVarResponse = request<Any?>(
localVariableConfig,
localVariableBody
)
return when (localVarResponse.responseType) {
ResponseType.Success -> Unit
ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.")
ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.")
ResponseType.ClientError -> {
val localVarError = localVarResponse as ClientError<*>
throw ClientException("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse)
}
ResponseType.ServerError -> {
val localVarError = localVarResponse as ServerError<*>
throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse)
}
}
}
/**
* Returns pet inventories by status
* Returns a map of status codes to quantities
* @return kotlin.collections.Map<kotlin.String, kotlin.Int>
* @throws UnsupportedOperationException If the API returns an informational or redirection response
* @throws ClientException If the API returns a client error response
* @throws ServerException If the API returns a server error response
*/
@Suppress("UNCHECKED_CAST")
@Throws(UnsupportedOperationException::class, ClientException::class, ServerException::class)
fun getInventory() : kotlin.collections.Map<kotlin.String, kotlin.Int> {
val localVariableBody: kotlin.Any? = null
val localVariableQuery: MultiValueMap = mutableMapOf()
val localVariableHeaders: MutableMap<String, String> = mutableMapOf()
val localVariableConfig = RequestConfig(
RequestMethod.GET,
"/store/inventory",
query = localVariableQuery,
headers = localVariableHeaders
)
val localVarResponse = request<kotlin.collections.Map<kotlin.String, kotlin.Int>>(
localVariableConfig,
localVariableBody
)
return when (localVarResponse.responseType) {
ResponseType.Success -> (localVarResponse as Success<*>).data as kotlin.collections.Map<kotlin.String, kotlin.Int>
ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.")
ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.")
ResponseType.ClientError -> {
val localVarError = localVarResponse as ClientError<*>
throw ClientException("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse)
}
ResponseType.ServerError -> {
val localVarError = localVarResponse as ServerError<*>
throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse)
}
}
}
/**
* 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
* @return Order
* @throws UnsupportedOperationException If the API returns an informational or redirection response
* @throws ClientException If the API returns a client error response
* @throws ServerException If the API returns a server error response
*/
@Suppress("UNCHECKED_CAST")
@Throws(UnsupportedOperationException::class, ClientException::class, ServerException::class)
fun getOrderById(orderId: kotlin.Long) : Order {
val localVariableBody: kotlin.Any? = null
val localVariableQuery: MultiValueMap = mutableMapOf()
val localVariableHeaders: MutableMap<String, String> = mutableMapOf()
val localVariableConfig = RequestConfig(
RequestMethod.GET,
"/store/order/{orderId}".replace("{"+"orderId"+"}", "$orderId"),
query = localVariableQuery,
headers = localVariableHeaders
)
val localVarResponse = request<Order>(
localVariableConfig,
localVariableBody
)
return when (localVarResponse.responseType) {
ResponseType.Success -> (localVarResponse as Success<*>).data as Order
ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.")
ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.")
ResponseType.ClientError -> {
val localVarError = localVarResponse as ClientError<*>
throw ClientException("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse)
}
ResponseType.ServerError -> {
val localVarError = localVarResponse as ServerError<*>
throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse)
}
}
}
/**
* Place an order for a pet
*
* @param body order placed for purchasing the pet
* @return Order
* @throws UnsupportedOperationException If the API returns an informational or redirection response
* @throws ClientException If the API returns a client error response
* @throws ServerException If the API returns a server error response
*/
@Suppress("UNCHECKED_CAST")
@Throws(UnsupportedOperationException::class, ClientException::class, ServerException::class)
fun placeOrder(body: Order) : Order {
val localVariableBody: kotlin.Any? = body
val localVariableQuery: MultiValueMap = mutableMapOf()
val localVariableHeaders: MutableMap<String, String> = mutableMapOf()
val localVariableConfig = RequestConfig(
RequestMethod.POST,
"/store/order",
query = localVariableQuery,
headers = localVariableHeaders
)
val localVarResponse = request<Order>(
localVariableConfig,
localVariableBody
)
return when (localVarResponse.responseType) {
ResponseType.Success -> (localVarResponse as Success<*>).data as Order
ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.")
ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.")
ResponseType.ClientError -> {
val localVarError = localVarResponse as ClientError<*>
throw ClientException("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse)
}
ResponseType.ServerError -> {
val localVarError = localVarResponse as ServerError<*>
throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse)
}
}
}
}

View File

@ -0,0 +1,363 @@
/**
* 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.client.apis
import org.openapitools.client.models.User
import org.openapitools.client.infrastructure.ApiClient
import org.openapitools.client.infrastructure.ClientException
import org.openapitools.client.infrastructure.ClientError
import org.openapitools.client.infrastructure.ServerException
import org.openapitools.client.infrastructure.ServerError
import org.openapitools.client.infrastructure.MultiValueMap
import org.openapitools.client.infrastructure.RequestConfig
import org.openapitools.client.infrastructure.RequestMethod
import org.openapitools.client.infrastructure.ResponseType
import org.openapitools.client.infrastructure.Success
import org.openapitools.client.infrastructure.toMultiValue
class UserApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) {
companion object {
@JvmStatic
val defaultBasePath: String by lazy {
System.getProperties().getProperty("org.openapitools.client.baseUrl", "http://petstore.swagger.io/v2")
}
}
/**
* Create user
* This can only be done by the logged in user.
* @param body Created user object
* @return void
* @throws UnsupportedOperationException If the API returns an informational or redirection response
* @throws ClientException If the API returns a client error response
* @throws ServerException If the API returns a server error response
*/
@Throws(UnsupportedOperationException::class, ClientException::class, ServerException::class)
fun createUser(body: User) : Unit {
val localVariableBody: kotlin.Any? = body
val localVariableQuery: MultiValueMap = mutableMapOf()
val localVariableHeaders: MutableMap<String, String> = mutableMapOf()
val localVariableConfig = RequestConfig(
RequestMethod.POST,
"/user",
query = localVariableQuery,
headers = localVariableHeaders
)
val localVarResponse = request<Any?>(
localVariableConfig,
localVariableBody
)
return when (localVarResponse.responseType) {
ResponseType.Success -> Unit
ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.")
ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.")
ResponseType.ClientError -> {
val localVarError = localVarResponse as ClientError<*>
throw ClientException("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse)
}
ResponseType.ServerError -> {
val localVarError = localVarResponse as ServerError<*>
throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse)
}
}
}
/**
* Creates list of users with given input array
*
* @param body List of user object
* @return void
* @throws UnsupportedOperationException If the API returns an informational or redirection response
* @throws ClientException If the API returns a client error response
* @throws ServerException If the API returns a server error response
*/
@Throws(UnsupportedOperationException::class, ClientException::class, ServerException::class)
fun createUsersWithArrayInput(body: kotlin.collections.List<User>) : Unit {
val localVariableBody: kotlin.Any? = body
val localVariableQuery: MultiValueMap = mutableMapOf()
val localVariableHeaders: MutableMap<String, String> = mutableMapOf()
val localVariableConfig = RequestConfig(
RequestMethod.POST,
"/user/createWithArray",
query = localVariableQuery,
headers = localVariableHeaders
)
val localVarResponse = request<Any?>(
localVariableConfig,
localVariableBody
)
return when (localVarResponse.responseType) {
ResponseType.Success -> Unit
ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.")
ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.")
ResponseType.ClientError -> {
val localVarError = localVarResponse as ClientError<*>
throw ClientException("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse)
}
ResponseType.ServerError -> {
val localVarError = localVarResponse as ServerError<*>
throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse)
}
}
}
/**
* Creates list of users with given input array
*
* @param body List of user object
* @return void
* @throws UnsupportedOperationException If the API returns an informational or redirection response
* @throws ClientException If the API returns a client error response
* @throws ServerException If the API returns a server error response
*/
@Throws(UnsupportedOperationException::class, ClientException::class, ServerException::class)
fun createUsersWithListInput(body: kotlin.collections.List<User>) : Unit {
val localVariableBody: kotlin.Any? = body
val localVariableQuery: MultiValueMap = mutableMapOf()
val localVariableHeaders: MutableMap<String, String> = mutableMapOf()
val localVariableConfig = RequestConfig(
RequestMethod.POST,
"/user/createWithList",
query = localVariableQuery,
headers = localVariableHeaders
)
val localVarResponse = request<Any?>(
localVariableConfig,
localVariableBody
)
return when (localVarResponse.responseType) {
ResponseType.Success -> Unit
ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.")
ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.")
ResponseType.ClientError -> {
val localVarError = localVarResponse as ClientError<*>
throw ClientException("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse)
}
ResponseType.ServerError -> {
val localVarError = localVarResponse as ServerError<*>
throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse)
}
}
}
/**
* Delete user
* This can only be done by the logged in user.
* @param username The name that needs to be deleted
* @return void
* @throws UnsupportedOperationException If the API returns an informational or redirection response
* @throws ClientException If the API returns a client error response
* @throws ServerException If the API returns a server error response
*/
@Throws(UnsupportedOperationException::class, ClientException::class, ServerException::class)
fun deleteUser(username: kotlin.String) : Unit {
val localVariableBody: kotlin.Any? = null
val localVariableQuery: MultiValueMap = mutableMapOf()
val localVariableHeaders: MutableMap<String, String> = mutableMapOf()
val localVariableConfig = RequestConfig(
RequestMethod.DELETE,
"/user/{username}".replace("{"+"username"+"}", "$username"),
query = localVariableQuery,
headers = localVariableHeaders
)
val localVarResponse = request<Any?>(
localVariableConfig,
localVariableBody
)
return when (localVarResponse.responseType) {
ResponseType.Success -> Unit
ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.")
ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.")
ResponseType.ClientError -> {
val localVarError = localVarResponse as ClientError<*>
throw ClientException("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse)
}
ResponseType.ServerError -> {
val localVarError = localVarResponse as ServerError<*>
throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse)
}
}
}
/**
* Get user by user name
*
* @param username The name that needs to be fetched. Use user1 for testing.
* @return User
* @throws UnsupportedOperationException If the API returns an informational or redirection response
* @throws ClientException If the API returns a client error response
* @throws ServerException If the API returns a server error response
*/
@Suppress("UNCHECKED_CAST")
@Throws(UnsupportedOperationException::class, ClientException::class, ServerException::class)
fun getUserByName(username: kotlin.String) : User {
val localVariableBody: kotlin.Any? = null
val localVariableQuery: MultiValueMap = mutableMapOf()
val localVariableHeaders: MutableMap<String, String> = mutableMapOf()
val localVariableConfig = RequestConfig(
RequestMethod.GET,
"/user/{username}".replace("{"+"username"+"}", "$username"),
query = localVariableQuery,
headers = localVariableHeaders
)
val localVarResponse = request<User>(
localVariableConfig,
localVariableBody
)
return when (localVarResponse.responseType) {
ResponseType.Success -> (localVarResponse as Success<*>).data as User
ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.")
ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.")
ResponseType.ClientError -> {
val localVarError = localVarResponse as ClientError<*>
throw ClientException("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse)
}
ResponseType.ServerError -> {
val localVarError = localVarResponse as ServerError<*>
throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse)
}
}
}
/**
* Logs user into the system
*
* @param username The user name for login
* @param password The password for login in clear text
* @return kotlin.String
* @throws UnsupportedOperationException If the API returns an informational or redirection response
* @throws ClientException If the API returns a client error response
* @throws ServerException If the API returns a server error response
*/
@Suppress("UNCHECKED_CAST")
@Throws(UnsupportedOperationException::class, ClientException::class, ServerException::class)
fun loginUser(username: kotlin.String, password: kotlin.String) : kotlin.String {
val localVariableBody: kotlin.Any? = null
val localVariableQuery: MultiValueMap = mutableMapOf<kotlin.String, List<kotlin.String>>()
.apply {
put("username", listOf(username.toString()))
put("password", listOf(password.toString()))
}
val localVariableHeaders: MutableMap<String, String> = mutableMapOf()
val localVariableConfig = RequestConfig(
RequestMethod.GET,
"/user/login",
query = localVariableQuery,
headers = localVariableHeaders
)
val localVarResponse = request<kotlin.String>(
localVariableConfig,
localVariableBody
)
return when (localVarResponse.responseType) {
ResponseType.Success -> (localVarResponse as Success<*>).data as kotlin.String
ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.")
ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.")
ResponseType.ClientError -> {
val localVarError = localVarResponse as ClientError<*>
throw ClientException("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse)
}
ResponseType.ServerError -> {
val localVarError = localVarResponse as ServerError<*>
throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse)
}
}
}
/**
* Logs out current logged in user session
*
* @return void
* @throws UnsupportedOperationException If the API returns an informational or redirection response
* @throws ClientException If the API returns a client error response
* @throws ServerException If the API returns a server error response
*/
@Throws(UnsupportedOperationException::class, ClientException::class, ServerException::class)
fun logoutUser() : Unit {
val localVariableBody: kotlin.Any? = null
val localVariableQuery: MultiValueMap = mutableMapOf()
val localVariableHeaders: MutableMap<String, String> = mutableMapOf()
val localVariableConfig = RequestConfig(
RequestMethod.GET,
"/user/logout",
query = localVariableQuery,
headers = localVariableHeaders
)
val localVarResponse = request<Any?>(
localVariableConfig,
localVariableBody
)
return when (localVarResponse.responseType) {
ResponseType.Success -> Unit
ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.")
ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.")
ResponseType.ClientError -> {
val localVarError = localVarResponse as ClientError<*>
throw ClientException("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse)
}
ResponseType.ServerError -> {
val localVarError = localVarResponse as ServerError<*>
throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse)
}
}
}
/**
* 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
* @return void
* @throws UnsupportedOperationException If the API returns an informational or redirection response
* @throws ClientException If the API returns a client error response
* @throws ServerException If the API returns a server error response
*/
@Throws(UnsupportedOperationException::class, ClientException::class, ServerException::class)
fun updateUser(username: kotlin.String, body: User) : Unit {
val localVariableBody: kotlin.Any? = body
val localVariableQuery: MultiValueMap = mutableMapOf()
val localVariableHeaders: MutableMap<String, String> = mutableMapOf()
val localVariableConfig = RequestConfig(
RequestMethod.PUT,
"/user/{username}".replace("{"+"username"+"}", "$username"),
query = localVariableQuery,
headers = localVariableHeaders
)
val localVarResponse = request<Any?>(
localVariableConfig,
localVariableBody
)
return when (localVarResponse.responseType) {
ResponseType.Success -> Unit
ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.")
ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.")
ResponseType.ClientError -> {
val localVarError = localVarResponse as ClientError<*>
throw ClientException("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse)
}
ResponseType.ServerError -> {
val localVarError = localVarResponse as ServerError<*>
throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse)
}
}
}
}

View File

@ -0,0 +1,23 @@
package org.openapitools.client.infrastructure
typealias MultiValueMap = MutableMap<String,List<String>>
fun collectionDelimiter(collectionFormat: String) = when(collectionFormat) {
"csv" -> ","
"tsv" -> "\t"
"pipe" -> "|"
"space" -> " "
else -> ""
}
val defaultMultiValueConverter: (item: Any?) -> String = { item -> "$item" }
fun <T : Any?> toMultiValue(items: Array<T>, collectionFormat: String, map: (item: T) -> String = defaultMultiValueConverter)
= toMultiValue(items.asIterable(), collectionFormat, map)
fun <T : Any?> toMultiValue(items: Iterable<T>, collectionFormat: String, map: (item: T) -> String = defaultMultiValueConverter): List<String> {
return when(collectionFormat) {
"multi" -> items.map(map)
else -> listOf(items.joinToString(separator = collectionDelimiter(collectionFormat), transform = map))
}
}

View File

@ -0,0 +1,251 @@
package org.openapitools.client.infrastructure
import okhttp3.Credentials
import okhttp3.OkHttpClient
import okhttp3.RequestBody
import okhttp3.RequestBody.Companion.asRequestBody
import okhttp3.RequestBody.Companion.toRequestBody
import okhttp3.FormBody
import okhttp3.HttpUrl.Companion.toHttpUrlOrNull
import okhttp3.ResponseBody
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.Request
import okhttp3.Headers
import okhttp3.MultipartBody
import java.io.File
import java.net.URLConnection
import java.util.Date
import java.time.LocalDate
import java.time.LocalDateTime
import java.time.LocalTime
import java.time.OffsetDateTime
import java.time.OffsetTime
open class ApiClient(val baseUrl: String) {
companion object {
protected const val ContentType = "Content-Type"
protected const val Accept = "Accept"
protected const val Authorization = "Authorization"
protected const val JsonMediaType = "application/json"
protected const val FormDataMediaType = "multipart/form-data"
protected const val FormUrlEncMediaType = "application/x-www-form-urlencoded"
protected const val XmlMediaType = "application/xml"
val apiKey: MutableMap<String, String> = mutableMapOf()
val apiKeyPrefix: MutableMap<String, String> = mutableMapOf()
var username: String? = null
var password: String? = null
var accessToken: String? = null
@JvmStatic
val client: OkHttpClient by lazy {
builder.build()
}
@JvmStatic
val builder: OkHttpClient.Builder = OkHttpClient.Builder()
}
/**
* Guess Content-Type header from the given file (defaults to "application/octet-stream").
*
* @param file The given file
* @return The guessed Content-Type
*/
protected fun guessContentTypeFromFile(file: File): String {
val contentType = URLConnection.guessContentTypeFromName(file.name)
return contentType ?: "application/octet-stream"
}
protected inline fun <reified T> requestBody(content: T, mediaType: String = JsonMediaType): RequestBody =
when {
content is File -> content.asRequestBody(
mediaType.toMediaTypeOrNull()
)
mediaType == FormDataMediaType -> {
MultipartBody.Builder()
.setType(MultipartBody.FORM)
.apply {
// content's type *must* be Map<String, Any?>
@Suppress("UNCHECKED_CAST")
(content as Map<String, Any?>).forEach { (key, value) ->
if (value is File) {
val partHeaders = Headers.headersOf(
"Content-Disposition",
"form-data; name=\"$key\"; filename=\"${value.name}\""
)
val fileMediaType = guessContentTypeFromFile(value).toMediaTypeOrNull()
addPart(partHeaders, value.asRequestBody(fileMediaType))
} else {
val partHeaders = Headers.headersOf(
"Content-Disposition",
"form-data; name=\"$key\""
)
addPart(
partHeaders,
parameterToString(value).toRequestBody(null)
)
}
}
}.build()
}
mediaType == FormUrlEncMediaType -> {
FormBody.Builder().apply {
// content's type *must* be Map<String, Any?>
@Suppress("UNCHECKED_CAST")
(content as Map<String, Any?>).forEach { (key, value) ->
add(key, parameterToString(value))
}
}.build()
}
mediaType == JsonMediaType -> Serializer.jacksonObjectMapper.writeValueAsString(content).toRequestBody(
mediaType.toMediaTypeOrNull()
)
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.")
}
protected inline fun <reified T: Any?> responseBody(body: ResponseBody?, mediaType: String? = JsonMediaType): T? {
if(body == null) {
return null
}
val bodyContent = body.string()
if (bodyContent.isEmpty()) {
return null
}
return when(mediaType) {
JsonMediaType -> Serializer.jacksonObjectMapper.readValue(bodyContent, T::class.java)
else -> throw UnsupportedOperationException("responseBody currently only supports JSON body.")
}
}
protected fun updateAuthParams(requestConfig: RequestConfig) {
if (requestConfig.headers["api_key"].isNullOrEmpty()) {
if (apiKey["api_key"] != null) {
if (apiKeyPrefix["api_key"] != null) {
requestConfig.headers["api_key"] = apiKeyPrefix["api_key"]!! + " " + apiKey["api_key"]!!
} else {
requestConfig.headers["api_key"] = apiKey["api_key"]!!
}
}
}
if (requestConfig.headers[Authorization].isNullOrEmpty()) {
accessToken?.let { accessToken ->
requestConfig.headers[Authorization] = "Bearer $accessToken "
}
}
}
protected inline fun <reified T: Any?> request(requestConfig: RequestConfig, body : Any? = null): ApiInfrastructureResponse<T?> {
val httpUrl = baseUrl.toHttpUrlOrNull() ?: throw IllegalStateException("baseUrl is invalid.")
// take authMethod from operation
updateAuthParams(requestConfig)
val url = httpUrl.newBuilder()
.addPathSegments(requestConfig.path.trimStart('/'))
.apply {
requestConfig.query.forEach { query ->
query.value.forEach { queryValue ->
addQueryParameter(query.key, queryValue)
}
}
}.build()
// take content-type/accept from spec or set to default (application/json) if not defined
if (requestConfig.headers[ContentType].isNullOrEmpty()) {
requestConfig.headers[ContentType] = JsonMediaType
}
if (requestConfig.headers[Accept].isNullOrEmpty()) {
requestConfig.headers[Accept] = JsonMediaType
}
val headers = requestConfig.headers
if(headers[ContentType] ?: "" == "") {
throw kotlin.IllegalStateException("Missing Content-Type header. This is required.")
}
if(headers[Accept] ?: "" == "") {
throw kotlin.IllegalStateException("Missing Accept header. This is required.")
}
// TODO: support multiple contentType options here.
val contentType = (headers[ContentType] as String).substringBefore(";").toLowerCase()
val request = when (requestConfig.method) {
RequestMethod.DELETE -> Request.Builder().url(url).delete(requestBody(body, contentType))
RequestMethod.GET -> Request.Builder().url(url)
RequestMethod.HEAD -> Request.Builder().url(url).head()
RequestMethod.PATCH -> Request.Builder().url(url).patch(requestBody(body, contentType))
RequestMethod.PUT -> Request.Builder().url(url).put(requestBody(body, contentType))
RequestMethod.POST -> Request.Builder().url(url).post(requestBody(body, contentType))
RequestMethod.OPTIONS -> Request.Builder().url(url).method("OPTIONS", null)
}.apply {
headers.forEach { header -> addHeader(header.key, header.value) }
}.build()
val response = client.newCall(request).execute()
val accept = response.header(ContentType)?.substringBefore(";")?.toLowerCase()
// TODO: handle specific mapping types. e.g. Map<int, Class<?>>
when {
response.isRedirect -> return Redirection(
response.code,
response.headers.toMultimap()
)
response.isInformational -> return Informational(
response.message,
response.code,
response.headers.toMultimap()
)
response.isSuccessful -> return Success(
responseBody(response.body, accept),
response.code,
response.headers.toMultimap()
)
response.isClientError -> return ClientError(
response.message,
response.body?.string(),
response.code,
response.headers.toMultimap()
)
else -> return ServerError(
response.message,
response.body?.string(),
response.code,
response.headers.toMultimap()
)
}
}
protected fun parameterToString(value: Any?): String {
when (value) {
null -> {
return ""
}
is Array<*> -> {
return toMultiValue(value, "csv").toString()
}
is Iterable<*> -> {
return toMultiValue(value, "csv").toString()
}
is OffsetDateTime, is OffsetTime, is LocalDateTime, is LocalDate, is LocalTime, is Date -> {
return parseDateToQueryString<Any>(value)
}
else -> {
return value.toString()
}
}
}
protected inline fun <reified T: Any> parseDateToQueryString(value : T): String {
/*
.replace("\"", "") converts the json object string to an actual string for the query parameter.
The moshi or gson adapter allows a more generic solution instead of trying to use a native
formatter. It also easily allows to provide a simple way to define a custom date format pattern
inside a gson/moshi adapter.
*/
return Serializer.jacksonObjectMapper.writeValueAsString(value).replace("\"", "")
}
}

View File

@ -0,0 +1,43 @@
package org.openapitools.client.infrastructure
enum class ResponseType {
Success, Informational, Redirection, ClientError, ServerError
}
interface Response
abstract class ApiInfrastructureResponse<T>(val responseType: ResponseType): Response {
abstract val statusCode: Int
abstract val headers: Map<String,List<String>>
}
class Success<T>(
val data: T,
override val statusCode: Int = -1,
override val headers: Map<String, List<String>> = mapOf()
): ApiInfrastructureResponse<T>(ResponseType.Success)
class Informational<T>(
val statusText: String,
override val statusCode: Int = -1,
override val headers: Map<String, List<String>> = mapOf()
) : ApiInfrastructureResponse<T>(ResponseType.Informational)
class Redirection<T>(
override val statusCode: Int = -1,
override val headers: Map<String, List<String>> = mapOf()
) : ApiInfrastructureResponse<T>(ResponseType.Redirection)
class ClientError<T>(
val message: String? = null,
val body: Any? = null,
override val statusCode: Int = -1,
override val headers: Map<String, List<String>> = mapOf()
) : ApiInfrastructureResponse<T>(ResponseType.ClientError)
class ServerError<T>(
val message: String? = null,
val body: Any? = null,
override val statusCode: Int = -1,
override val headers: Map<String, List<String>>
): ApiInfrastructureResponse<T>(ResponseType.ServerError)

View File

@ -0,0 +1,29 @@
package org.openapitools.client.infrastructure
import kotlin.properties.ReadWriteProperty
import kotlin.reflect.KProperty
object ApplicationDelegates {
/**
* Provides a property delegate, allowing the property to be set once and only once.
*
* If unset (no default value), a get on the property will throw [IllegalStateException].
*/
fun <T> setOnce(defaultValue: T? = null) : ReadWriteProperty<Any?, T> = SetOnce(defaultValue)
private class SetOnce<T>(defaultValue: T? = null) : ReadWriteProperty<Any?, T> {
private var isSet = false
private var value: T? = defaultValue
override fun getValue(thisRef: Any?, property: KProperty<*>): T {
return value ?: throw IllegalStateException("${property.name} not initialized")
}
override fun setValue(thisRef: Any?, property: KProperty<*>, value: T) = synchronized(this) {
if (!isSet) {
this.value = value
isSet = true
}
}
}
}

View File

@ -0,0 +1,3 @@
package org.openapitools.client.infrastructure

View File

@ -0,0 +1,18 @@
@file:Suppress("unused")
package org.openapitools.client.infrastructure
import java.lang.RuntimeException
open class ClientException(message: kotlin.String? = null, val statusCode: Int = -1, val response: Response? = null) : RuntimeException(message) {
companion object {
private const val serialVersionUID: Long = 123L
}
}
open class ServerException(message: kotlin.String? = null, val statusCode: Int = -1, val response: Response? = null) : RuntimeException(message) {
companion object {
private const val serialVersionUID: Long = 456L
}
}

View File

@ -0,0 +1,16 @@
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<String,String> because rfc2616 defines
* multi-valued headers as csv-only.
*/
data class RequestConfig(
val method: RequestMethod,
val path: String,
val headers: MutableMap<String, String> = mutableMapOf(),
val query: MutableMap<String, List<String>> = mutableMapOf()
)

View File

@ -0,0 +1,8 @@
package org.openapitools.client.infrastructure
/**
* Provides enumerated HTTP verbs
*/
enum class RequestMethod {
GET, DELETE, HEAD, OPTIONS, PATCH, POST, PUT
}

View File

@ -0,0 +1,24 @@
package org.openapitools.client.infrastructure
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
/**
* Provides an extension to evaluation whether the response is a 3xx code
*/
@Suppress("EXTENSION_SHADOWED_BY_MEMBER")
val Response.isRedirect : Boolean get() = this.code 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
/**
* 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

View File

@ -0,0 +1,18 @@
package org.openapitools.client.infrastructure
import com.fasterxml.jackson.databind.ObjectMapper
import com.fasterxml.jackson.databind.SerializationFeature
import com.fasterxml.jackson.datatype.jdk8.Jdk8Module
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule
import com.fasterxml.jackson.annotation.JsonInclude
import com.fasterxml.jackson.module.kotlin.jacksonObjectMapper
import java.util.Date
object Serializer {
@JvmStatic
val jacksonObjectMapper: ObjectMapper = jacksonObjectMapper()
.registerModule(Jdk8Module())
.registerModule(JavaTimeModule())
.setSerializationInclusion(JsonInclude.Include.NON_ABSENT)
.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false)
}

View File

@ -0,0 +1,32 @@
/**
* 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.client.models
import com.fasterxml.jackson.annotation.JsonProperty
/**
* Describes the result of uploading an image resource
* @param code
* @param type
* @param message
*/
data class ApiResponse (
@field:JsonProperty("code")
val code: kotlin.Int? = null,
@field:JsonProperty("type")
val type: kotlin.String? = null,
@field:JsonProperty("message")
val message: kotlin.String? = null
)

View File

@ -0,0 +1,29 @@
/**
* 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.client.models
import com.fasterxml.jackson.annotation.JsonProperty
/**
* A category for a pet
* @param id
* @param name
*/
data class Category (
@field:JsonProperty("id")
val id: kotlin.Long? = null,
@field:JsonProperty("name")
val name: kotlin.String? = null
)

View File

@ -0,0 +1,54 @@
/**
* 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.client.models
import com.fasterxml.jackson.annotation.JsonProperty
/**
* 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 (
@field:JsonProperty("id")
val id: kotlin.Long? = null,
@field:JsonProperty("petId")
val petId: kotlin.Long? = null,
@field:JsonProperty("quantity")
val quantity: kotlin.Int? = null,
@field:JsonProperty("shipDate")
val shipDate: java.time.OffsetDateTime? = null,
/* Order Status */
@field:JsonProperty("status")
val status: Order.Status? = null,
@field:JsonProperty("complete")
val complete: kotlin.Boolean? = null
) {
/**
* Order Status
* Values: PLACED,APPROVED,DELIVERED
*/
enum class Status(val value: kotlin.String){
@JsonProperty(value = "placed") PLACED("placed"),
@JsonProperty(value = "approved") APPROVED("approved"),
@JsonProperty(value = "delivered") DELIVERED("delivered");
}
}

View File

@ -0,0 +1,56 @@
/**
* 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.client.models
import org.openapitools.client.models.Category
import org.openapitools.client.models.Tag
import com.fasterxml.jackson.annotation.JsonProperty
/**
* 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 (
@field:JsonProperty("name")
val name: kotlin.String,
@field:JsonProperty("photoUrls")
val photoUrls: kotlin.collections.List<kotlin.String>,
@field:JsonProperty("id")
val id: kotlin.Long? = null,
@field:JsonProperty("category")
val category: Category? = null,
@field:JsonProperty("tags")
val tags: kotlin.collections.List<Tag>? = null,
/* pet status in the store */
@field:JsonProperty("status")
val status: Pet.Status? = null
) {
/**
* pet status in the store
* Values: AVAILABLE,PENDING,SOLD
*/
enum class Status(val value: kotlin.String){
@JsonProperty(value = "available") AVAILABLE("available"),
@JsonProperty(value = "pending") PENDING("pending"),
@JsonProperty(value = "sold") SOLD("sold");
}
}

View File

@ -0,0 +1,29 @@
/**
* 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.client.models
import com.fasterxml.jackson.annotation.JsonProperty
/**
* A tag for a pet
* @param id
* @param name
*/
data class Tag (
@field:JsonProperty("id")
val id: kotlin.Long? = null,
@field:JsonProperty("name")
val name: kotlin.String? = null
)

View File

@ -0,0 +1,48 @@
/**
* 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.client.models
import com.fasterxml.jackson.annotation.JsonProperty
/**
* 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 (
@field:JsonProperty("id")
val id: kotlin.Long? = null,
@field:JsonProperty("username")
val username: kotlin.String? = null,
@field:JsonProperty("firstName")
val firstName: kotlin.String? = null,
@field:JsonProperty("lastName")
val lastName: kotlin.String? = null,
@field:JsonProperty("email")
val email: kotlin.String? = null,
@field:JsonProperty("password")
val password: kotlin.String? = null,
@field:JsonProperty("phone")
val phone: kotlin.String? = null,
/* User Status */
@field:JsonProperty("userStatus")
val userStatus: kotlin.Int? = null
)

View File

@ -0,0 +1,376 @@
/**
* 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.client.apis
import org.openapitools.client.models.ApiResponse
import org.openapitools.client.models.Pet
import org.openapitools.client.infrastructure.ApiClient
import org.openapitools.client.infrastructure.ClientException
import org.openapitools.client.infrastructure.ClientError
import org.openapitools.client.infrastructure.ServerException
import org.openapitools.client.infrastructure.ServerError
import org.openapitools.client.infrastructure.MultiValueMap
import org.openapitools.client.infrastructure.RequestConfig
import org.openapitools.client.infrastructure.RequestMethod
import org.openapitools.client.infrastructure.ResponseType
import org.openapitools.client.infrastructure.Success
import org.openapitools.client.infrastructure.toMultiValue
class PetApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) {
companion object {
@JvmStatic
val defaultBasePath: String by lazy {
System.getProperties().getProperty("org.openapitools.client.baseUrl", "http://petstore.swagger.io/v2")
}
}
/**
* Add a new pet to the store
*
* @param body Pet object that needs to be added to the store
* @return void
* @throws UnsupportedOperationException If the API returns an informational or redirection response
* @throws ClientException If the API returns a client error response
* @throws ServerException If the API returns a server error response
*/
@Throws(UnsupportedOperationException::class, ClientException::class, ServerException::class)
fun addPet(body: Pet) : Unit {
val localVariableBody: kotlin.Any? = body
val localVariableQuery: MultiValueMap = mutableMapOf()
val localVariableHeaders: MutableMap<String, String> = mutableMapOf()
val localVariableConfig = RequestConfig(
RequestMethod.POST,
"/pet",
query = localVariableQuery,
headers = localVariableHeaders
)
val localVarResponse = request<Any?>(
localVariableConfig,
localVariableBody
)
return when (localVarResponse.responseType) {
ResponseType.Success -> Unit
ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.")
ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.")
ResponseType.ClientError -> {
val localVarError = localVarResponse as ClientError<*>
throw ClientException("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse)
}
ResponseType.ServerError -> {
val localVarError = localVarResponse as ServerError<*>
throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse)
}
}
}
/**
* Deletes a pet
*
* @param petId Pet id to delete
* @param apiKey (optional)
* @return void
* @throws UnsupportedOperationException If the API returns an informational or redirection response
* @throws ClientException If the API returns a client error response
* @throws ServerException If the API returns a server error response
*/
@Throws(UnsupportedOperationException::class, ClientException::class, ServerException::class)
fun deletePet(petId: kotlin.Long, apiKey: kotlin.String?) : Unit {
val localVariableBody: kotlin.Any? = null
val localVariableQuery: MultiValueMap = mutableMapOf()
val localVariableHeaders: MutableMap<String, String> = mutableMapOf()
apiKey?.apply { localVariableHeaders["api_key"] = this.toString() }
val localVariableConfig = RequestConfig(
RequestMethod.DELETE,
"/pet/{petId}".replace("{"+"petId"+"}", "$petId"),
query = localVariableQuery,
headers = localVariableHeaders
)
val localVarResponse = request<Any?>(
localVariableConfig,
localVariableBody
)
return when (localVarResponse.responseType) {
ResponseType.Success -> Unit
ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.")
ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.")
ResponseType.ClientError -> {
val localVarError = localVarResponse as ClientError<*>
throw ClientException("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse)
}
ResponseType.ServerError -> {
val localVarError = localVarResponse as ServerError<*>
throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse)
}
}
}
/**
* 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
* @return kotlin.collections.List<Pet>
* @throws UnsupportedOperationException If the API returns an informational or redirection response
* @throws ClientException If the API returns a client error response
* @throws ServerException If the API returns a server error response
*/
@Suppress("UNCHECKED_CAST")
@Throws(UnsupportedOperationException::class, ClientException::class, ServerException::class)
@Deprecated(message = "This operation is deprecated.")
fun findPetsByTags(tags: kotlin.collections.List<kotlin.String>) : kotlin.collections.List<Pet> {
val localVariableBody: kotlin.Any? = null
val localVariableQuery: MultiValueMap = mutableMapOf<kotlin.String, List<kotlin.String>>()
.apply {
put("tags", toMultiValue(tags.toList(), "csv"))
}
val localVariableHeaders: MutableMap<String, String> = mutableMapOf()
val localVariableConfig = RequestConfig(
RequestMethod.GET,
"/pet/findByTags",
query = localVariableQuery,
headers = localVariableHeaders
)
val localVarResponse = request<kotlin.collections.List<Pet>>(
localVariableConfig,
localVariableBody
)
return when (localVarResponse.responseType) {
ResponseType.Success -> (localVarResponse as Success<*>).data as kotlin.collections.List<Pet>
ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.")
ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.")
ResponseType.ClientError -> {
val localVarError = localVarResponse as ClientError<*>
throw ClientException("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse)
}
ResponseType.ServerError -> {
val localVarError = localVarResponse as ServerError<*>
throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse)
}
}
}
/**
* Get all pets
*
* @param lastUpdated When this endpoint was hit last to help indentify if the client already has the latest copy. (optional)
* @return kotlin.collections.List<Pet>
* @throws UnsupportedOperationException If the API returns an informational or redirection response
* @throws ClientException If the API returns a client error response
* @throws ServerException If the API returns a server error response
*/
@Suppress("UNCHECKED_CAST")
@Throws(UnsupportedOperationException::class, ClientException::class, ServerException::class)
fun getAllPets(lastUpdated: java.time.OffsetDateTime?) : kotlin.collections.List<Pet> {
val localVariableBody: kotlin.Any? = null
val localVariableQuery: MultiValueMap = mutableMapOf<kotlin.String, List<kotlin.String>>()
.apply {
if (lastUpdated != null) {
put("lastUpdated", listOf(parseDateToQueryString(lastUpdated)))
}
}
val localVariableHeaders: MutableMap<String, String> = mutableMapOf()
val localVariableConfig = RequestConfig(
RequestMethod.GET,
"/pet/getAll",
query = localVariableQuery,
headers = localVariableHeaders
)
val localVarResponse = request<kotlin.collections.List<Pet>>(
localVariableConfig,
localVariableBody
)
return when (localVarResponse.responseType) {
ResponseType.Success -> (localVarResponse as Success<*>).data as kotlin.collections.List<Pet>
ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.")
ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.")
ResponseType.ClientError -> {
val localVarError = localVarResponse as ClientError<*>
throw ClientException("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse)
}
ResponseType.ServerError -> {
val localVarError = localVarResponse as ServerError<*>
throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse)
}
}
}
/**
* Find pet by ID
* Returns a single pet
* @param petId ID of pet to return
* @return Pet
* @throws UnsupportedOperationException If the API returns an informational or redirection response
* @throws ClientException If the API returns a client error response
* @throws ServerException If the API returns a server error response
*/
@Suppress("UNCHECKED_CAST")
@Throws(UnsupportedOperationException::class, ClientException::class, ServerException::class)
fun getPetById(petId: kotlin.Long) : Pet {
val localVariableBody: kotlin.Any? = null
val localVariableQuery: MultiValueMap = mutableMapOf()
val localVariableHeaders: MutableMap<String, String> = mutableMapOf()
val localVariableConfig = RequestConfig(
RequestMethod.GET,
"/pet/{petId}".replace("{"+"petId"+"}", "$petId"),
query = localVariableQuery,
headers = localVariableHeaders
)
val localVarResponse = request<Pet>(
localVariableConfig,
localVariableBody
)
return when (localVarResponse.responseType) {
ResponseType.Success -> (localVarResponse as Success<*>).data as Pet
ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.")
ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.")
ResponseType.ClientError -> {
val localVarError = localVarResponse as ClientError<*>
throw ClientException("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse)
}
ResponseType.ServerError -> {
val localVarError = localVarResponse as ServerError<*>
throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse)
}
}
}
/**
* Update an existing pet
*
* @param body Pet object that needs to be added to the store
* @return void
* @throws UnsupportedOperationException If the API returns an informational or redirection response
* @throws ClientException If the API returns a client error response
* @throws ServerException If the API returns a server error response
*/
@Throws(UnsupportedOperationException::class, ClientException::class, ServerException::class)
fun updatePet(body: Pet) : Unit {
val localVariableBody: kotlin.Any? = body
val localVariableQuery: MultiValueMap = mutableMapOf()
val localVariableHeaders: MutableMap<String, String> = mutableMapOf()
val localVariableConfig = RequestConfig(
RequestMethod.PUT,
"/pet",
query = localVariableQuery,
headers = localVariableHeaders
)
val localVarResponse = request<Any?>(
localVariableConfig,
localVariableBody
)
return when (localVarResponse.responseType) {
ResponseType.Success -> Unit
ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.")
ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.")
ResponseType.ClientError -> {
val localVarError = localVarResponse as ClientError<*>
throw ClientException("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse)
}
ResponseType.ServerError -> {
val localVarError = localVarResponse as ServerError<*>
throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse)
}
}
}
/**
* 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)
* @return void
* @throws UnsupportedOperationException If the API returns an informational or redirection response
* @throws ClientException If the API returns a client error response
* @throws ServerException If the API returns a server error response
*/
@Throws(UnsupportedOperationException::class, ClientException::class, ServerException::class)
fun updatePetWithForm(petId: kotlin.Long, name: kotlin.String?, status: kotlin.String?) : Unit {
val localVariableBody: kotlin.Any? = mapOf("name" to name, "status" to status)
val localVariableQuery: MultiValueMap = mutableMapOf()
val localVariableHeaders: MutableMap<String, String> = mutableMapOf("Content-Type" to "application/x-www-form-urlencoded")
val localVariableConfig = RequestConfig(
RequestMethod.POST,
"/pet/{petId}".replace("{"+"petId"+"}", "$petId"),
query = localVariableQuery,
headers = localVariableHeaders
)
val localVarResponse = request<Any?>(
localVariableConfig,
localVariableBody
)
return when (localVarResponse.responseType) {
ResponseType.Success -> Unit
ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.")
ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.")
ResponseType.ClientError -> {
val localVarError = localVarResponse as ClientError<*>
throw ClientException("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse)
}
ResponseType.ServerError -> {
val localVarError = localVarResponse as ServerError<*>
throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse)
}
}
}
/**
* 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)
* @return ApiResponse
* @throws UnsupportedOperationException If the API returns an informational or redirection response
* @throws ClientException If the API returns a client error response
* @throws ServerException If the API returns a server error response
*/
@Suppress("UNCHECKED_CAST")
@Throws(UnsupportedOperationException::class, ClientException::class, ServerException::class)
fun uploadFile(petId: kotlin.Long, additionalMetadata: kotlin.String?, file: java.io.File?) : ApiResponse {
val localVariableBody: kotlin.Any? = mapOf("additionalMetadata" to additionalMetadata, "file" to file)
val localVariableQuery: MultiValueMap = mutableMapOf()
val localVariableHeaders: MutableMap<String, String> = mutableMapOf("Content-Type" to "multipart/form-data")
val localVariableConfig = RequestConfig(
RequestMethod.POST,
"/pet/{petId}/uploadImage".replace("{"+"petId"+"}", "$petId"),
query = localVariableQuery,
headers = localVariableHeaders
)
val localVarResponse = request<ApiResponse>(
localVariableConfig,
localVariableBody
)
return when (localVarResponse.responseType) {
ResponseType.Success -> (localVarResponse as Success<*>).data as ApiResponse
ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.")
ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.")
ResponseType.ClientError -> {
val localVarError = localVarResponse as ClientError<*>
throw ClientException("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse)
}
ResponseType.ServerError -> {
val localVarError = localVarResponse as ServerError<*>
throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse)
}
}
}
}

View File

@ -0,0 +1,198 @@
/**
* 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.client.apis
import org.openapitools.client.models.Order
import org.openapitools.client.infrastructure.ApiClient
import org.openapitools.client.infrastructure.ClientException
import org.openapitools.client.infrastructure.ClientError
import org.openapitools.client.infrastructure.ServerException
import org.openapitools.client.infrastructure.ServerError
import org.openapitools.client.infrastructure.MultiValueMap
import org.openapitools.client.infrastructure.RequestConfig
import org.openapitools.client.infrastructure.RequestMethod
import org.openapitools.client.infrastructure.ResponseType
import org.openapitools.client.infrastructure.Success
import org.openapitools.client.infrastructure.toMultiValue
class StoreApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) {
companion object {
@JvmStatic
val defaultBasePath: String by lazy {
System.getProperties().getProperty("org.openapitools.client.baseUrl", "http://petstore.swagger.io/v2")
}
}
/**
* 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
* @return void
* @throws UnsupportedOperationException If the API returns an informational or redirection response
* @throws ClientException If the API returns a client error response
* @throws ServerException If the API returns a server error response
*/
@Throws(UnsupportedOperationException::class, ClientException::class, ServerException::class)
fun deleteOrder(orderId: kotlin.String) : Unit {
val localVariableBody: kotlin.Any? = null
val localVariableQuery: MultiValueMap = mutableMapOf()
val localVariableHeaders: MutableMap<String, String> = mutableMapOf()
val localVariableConfig = RequestConfig(
RequestMethod.DELETE,
"/store/order/{orderId}".replace("{"+"orderId"+"}", "$orderId"),
query = localVariableQuery,
headers = localVariableHeaders
)
val localVarResponse = request<Any?>(
localVariableConfig,
localVariableBody
)
return when (localVarResponse.responseType) {
ResponseType.Success -> Unit
ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.")
ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.")
ResponseType.ClientError -> {
val localVarError = localVarResponse as ClientError<*>
throw ClientException("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse)
}
ResponseType.ServerError -> {
val localVarError = localVarResponse as ServerError<*>
throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse)
}
}
}
/**
* Returns pet inventories by status
* Returns a map of status codes to quantities
* @return kotlin.collections.Map<kotlin.String, kotlin.Int>
* @throws UnsupportedOperationException If the API returns an informational or redirection response
* @throws ClientException If the API returns a client error response
* @throws ServerException If the API returns a server error response
*/
@Suppress("UNCHECKED_CAST")
@Throws(UnsupportedOperationException::class, ClientException::class, ServerException::class)
fun getInventory() : kotlin.collections.Map<kotlin.String, kotlin.Int> {
val localVariableBody: kotlin.Any? = null
val localVariableQuery: MultiValueMap = mutableMapOf()
val localVariableHeaders: MutableMap<String, String> = mutableMapOf()
val localVariableConfig = RequestConfig(
RequestMethod.GET,
"/store/inventory",
query = localVariableQuery,
headers = localVariableHeaders
)
val localVarResponse = request<kotlin.collections.Map<kotlin.String, kotlin.Int>>(
localVariableConfig,
localVariableBody
)
return when (localVarResponse.responseType) {
ResponseType.Success -> (localVarResponse as Success<*>).data as kotlin.collections.Map<kotlin.String, kotlin.Int>
ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.")
ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.")
ResponseType.ClientError -> {
val localVarError = localVarResponse as ClientError<*>
throw ClientException("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse)
}
ResponseType.ServerError -> {
val localVarError = localVarResponse as ServerError<*>
throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse)
}
}
}
/**
* 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
* @return Order
* @throws UnsupportedOperationException If the API returns an informational or redirection response
* @throws ClientException If the API returns a client error response
* @throws ServerException If the API returns a server error response
*/
@Suppress("UNCHECKED_CAST")
@Throws(UnsupportedOperationException::class, ClientException::class, ServerException::class)
fun getOrderById(orderId: kotlin.Long) : Order {
val localVariableBody: kotlin.Any? = null
val localVariableQuery: MultiValueMap = mutableMapOf()
val localVariableHeaders: MutableMap<String, String> = mutableMapOf()
val localVariableConfig = RequestConfig(
RequestMethod.GET,
"/store/order/{orderId}".replace("{"+"orderId"+"}", "$orderId"),
query = localVariableQuery,
headers = localVariableHeaders
)
val localVarResponse = request<Order>(
localVariableConfig,
localVariableBody
)
return when (localVarResponse.responseType) {
ResponseType.Success -> (localVarResponse as Success<*>).data as Order
ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.")
ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.")
ResponseType.ClientError -> {
val localVarError = localVarResponse as ClientError<*>
throw ClientException("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse)
}
ResponseType.ServerError -> {
val localVarError = localVarResponse as ServerError<*>
throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse)
}
}
}
/**
* Place an order for a pet
*
* @param body order placed for purchasing the pet
* @return Order
* @throws UnsupportedOperationException If the API returns an informational or redirection response
* @throws ClientException If the API returns a client error response
* @throws ServerException If the API returns a server error response
*/
@Suppress("UNCHECKED_CAST")
@Throws(UnsupportedOperationException::class, ClientException::class, ServerException::class)
fun placeOrder(body: Order) : Order {
val localVariableBody: kotlin.Any? = body
val localVariableQuery: MultiValueMap = mutableMapOf()
val localVariableHeaders: MutableMap<String, String> = mutableMapOf()
val localVariableConfig = RequestConfig(
RequestMethod.POST,
"/store/order",
query = localVariableQuery,
headers = localVariableHeaders
)
val localVarResponse = request<Order>(
localVariableConfig,
localVariableBody
)
return when (localVarResponse.responseType) {
ResponseType.Success -> (localVarResponse as Success<*>).data as Order
ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.")
ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.")
ResponseType.ClientError -> {
val localVarError = localVarResponse as ClientError<*>
throw ClientException("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse)
}
ResponseType.ServerError -> {
val localVarError = localVarResponse as ServerError<*>
throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse)
}
}
}
}

View File

@ -0,0 +1,363 @@
/**
* 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.client.apis
import org.openapitools.client.models.User
import org.openapitools.client.infrastructure.ApiClient
import org.openapitools.client.infrastructure.ClientException
import org.openapitools.client.infrastructure.ClientError
import org.openapitools.client.infrastructure.ServerException
import org.openapitools.client.infrastructure.ServerError
import org.openapitools.client.infrastructure.MultiValueMap
import org.openapitools.client.infrastructure.RequestConfig
import org.openapitools.client.infrastructure.RequestMethod
import org.openapitools.client.infrastructure.ResponseType
import org.openapitools.client.infrastructure.Success
import org.openapitools.client.infrastructure.toMultiValue
class UserApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) {
companion object {
@JvmStatic
val defaultBasePath: String by lazy {
System.getProperties().getProperty("org.openapitools.client.baseUrl", "http://petstore.swagger.io/v2")
}
}
/**
* Create user
* This can only be done by the logged in user.
* @param body Created user object
* @return void
* @throws UnsupportedOperationException If the API returns an informational or redirection response
* @throws ClientException If the API returns a client error response
* @throws ServerException If the API returns a server error response
*/
@Throws(UnsupportedOperationException::class, ClientException::class, ServerException::class)
fun createUser(body: User) : Unit {
val localVariableBody: kotlin.Any? = body
val localVariableQuery: MultiValueMap = mutableMapOf()
val localVariableHeaders: MutableMap<String, String> = mutableMapOf()
val localVariableConfig = RequestConfig(
RequestMethod.POST,
"/user",
query = localVariableQuery,
headers = localVariableHeaders
)
val localVarResponse = request<Any?>(
localVariableConfig,
localVariableBody
)
return when (localVarResponse.responseType) {
ResponseType.Success -> Unit
ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.")
ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.")
ResponseType.ClientError -> {
val localVarError = localVarResponse as ClientError<*>
throw ClientException("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse)
}
ResponseType.ServerError -> {
val localVarError = localVarResponse as ServerError<*>
throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse)
}
}
}
/**
* Creates list of users with given input array
*
* @param body List of user object
* @return void
* @throws UnsupportedOperationException If the API returns an informational or redirection response
* @throws ClientException If the API returns a client error response
* @throws ServerException If the API returns a server error response
*/
@Throws(UnsupportedOperationException::class, ClientException::class, ServerException::class)
fun createUsersWithArrayInput(body: kotlin.collections.List<User>) : Unit {
val localVariableBody: kotlin.Any? = body
val localVariableQuery: MultiValueMap = mutableMapOf()
val localVariableHeaders: MutableMap<String, String> = mutableMapOf()
val localVariableConfig = RequestConfig(
RequestMethod.POST,
"/user/createWithArray",
query = localVariableQuery,
headers = localVariableHeaders
)
val localVarResponse = request<Any?>(
localVariableConfig,
localVariableBody
)
return when (localVarResponse.responseType) {
ResponseType.Success -> Unit
ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.")
ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.")
ResponseType.ClientError -> {
val localVarError = localVarResponse as ClientError<*>
throw ClientException("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse)
}
ResponseType.ServerError -> {
val localVarError = localVarResponse as ServerError<*>
throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse)
}
}
}
/**
* Creates list of users with given input array
*
* @param body List of user object
* @return void
* @throws UnsupportedOperationException If the API returns an informational or redirection response
* @throws ClientException If the API returns a client error response
* @throws ServerException If the API returns a server error response
*/
@Throws(UnsupportedOperationException::class, ClientException::class, ServerException::class)
fun createUsersWithListInput(body: kotlin.collections.List<User>) : Unit {
val localVariableBody: kotlin.Any? = body
val localVariableQuery: MultiValueMap = mutableMapOf()
val localVariableHeaders: MutableMap<String, String> = mutableMapOf()
val localVariableConfig = RequestConfig(
RequestMethod.POST,
"/user/createWithList",
query = localVariableQuery,
headers = localVariableHeaders
)
val localVarResponse = request<Any?>(
localVariableConfig,
localVariableBody
)
return when (localVarResponse.responseType) {
ResponseType.Success -> Unit
ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.")
ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.")
ResponseType.ClientError -> {
val localVarError = localVarResponse as ClientError<*>
throw ClientException("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse)
}
ResponseType.ServerError -> {
val localVarError = localVarResponse as ServerError<*>
throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse)
}
}
}
/**
* Delete user
* This can only be done by the logged in user.
* @param username The name that needs to be deleted
* @return void
* @throws UnsupportedOperationException If the API returns an informational or redirection response
* @throws ClientException If the API returns a client error response
* @throws ServerException If the API returns a server error response
*/
@Throws(UnsupportedOperationException::class, ClientException::class, ServerException::class)
fun deleteUser(username: kotlin.String) : Unit {
val localVariableBody: kotlin.Any? = null
val localVariableQuery: MultiValueMap = mutableMapOf()
val localVariableHeaders: MutableMap<String, String> = mutableMapOf()
val localVariableConfig = RequestConfig(
RequestMethod.DELETE,
"/user/{username}".replace("{"+"username"+"}", "$username"),
query = localVariableQuery,
headers = localVariableHeaders
)
val localVarResponse = request<Any?>(
localVariableConfig,
localVariableBody
)
return when (localVarResponse.responseType) {
ResponseType.Success -> Unit
ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.")
ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.")
ResponseType.ClientError -> {
val localVarError = localVarResponse as ClientError<*>
throw ClientException("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse)
}
ResponseType.ServerError -> {
val localVarError = localVarResponse as ServerError<*>
throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse)
}
}
}
/**
* Get user by user name
*
* @param username The name that needs to be fetched. Use user1 for testing.
* @return User
* @throws UnsupportedOperationException If the API returns an informational or redirection response
* @throws ClientException If the API returns a client error response
* @throws ServerException If the API returns a server error response
*/
@Suppress("UNCHECKED_CAST")
@Throws(UnsupportedOperationException::class, ClientException::class, ServerException::class)
fun getUserByName(username: kotlin.String) : User {
val localVariableBody: kotlin.Any? = null
val localVariableQuery: MultiValueMap = mutableMapOf()
val localVariableHeaders: MutableMap<String, String> = mutableMapOf()
val localVariableConfig = RequestConfig(
RequestMethod.GET,
"/user/{username}".replace("{"+"username"+"}", "$username"),
query = localVariableQuery,
headers = localVariableHeaders
)
val localVarResponse = request<User>(
localVariableConfig,
localVariableBody
)
return when (localVarResponse.responseType) {
ResponseType.Success -> (localVarResponse as Success<*>).data as User
ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.")
ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.")
ResponseType.ClientError -> {
val localVarError = localVarResponse as ClientError<*>
throw ClientException("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse)
}
ResponseType.ServerError -> {
val localVarError = localVarResponse as ServerError<*>
throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse)
}
}
}
/**
* Logs user into the system
*
* @param username The user name for login
* @param password The password for login in clear text
* @return kotlin.String
* @throws UnsupportedOperationException If the API returns an informational or redirection response
* @throws ClientException If the API returns a client error response
* @throws ServerException If the API returns a server error response
*/
@Suppress("UNCHECKED_CAST")
@Throws(UnsupportedOperationException::class, ClientException::class, ServerException::class)
fun loginUser(username: kotlin.String, password: kotlin.String) : kotlin.String {
val localVariableBody: kotlin.Any? = null
val localVariableQuery: MultiValueMap = mutableMapOf<kotlin.String, List<kotlin.String>>()
.apply {
put("username", listOf(username.toString()))
put("password", listOf(password.toString()))
}
val localVariableHeaders: MutableMap<String, String> = mutableMapOf()
val localVariableConfig = RequestConfig(
RequestMethod.GET,
"/user/login",
query = localVariableQuery,
headers = localVariableHeaders
)
val localVarResponse = request<kotlin.String>(
localVariableConfig,
localVariableBody
)
return when (localVarResponse.responseType) {
ResponseType.Success -> (localVarResponse as Success<*>).data as kotlin.String
ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.")
ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.")
ResponseType.ClientError -> {
val localVarError = localVarResponse as ClientError<*>
throw ClientException("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse)
}
ResponseType.ServerError -> {
val localVarError = localVarResponse as ServerError<*>
throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse)
}
}
}
/**
* Logs out current logged in user session
*
* @return void
* @throws UnsupportedOperationException If the API returns an informational or redirection response
* @throws ClientException If the API returns a client error response
* @throws ServerException If the API returns a server error response
*/
@Throws(UnsupportedOperationException::class, ClientException::class, ServerException::class)
fun logoutUser() : Unit {
val localVariableBody: kotlin.Any? = null
val localVariableQuery: MultiValueMap = mutableMapOf()
val localVariableHeaders: MutableMap<String, String> = mutableMapOf()
val localVariableConfig = RequestConfig(
RequestMethod.GET,
"/user/logout",
query = localVariableQuery,
headers = localVariableHeaders
)
val localVarResponse = request<Any?>(
localVariableConfig,
localVariableBody
)
return when (localVarResponse.responseType) {
ResponseType.Success -> Unit
ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.")
ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.")
ResponseType.ClientError -> {
val localVarError = localVarResponse as ClientError<*>
throw ClientException("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse)
}
ResponseType.ServerError -> {
val localVarError = localVarResponse as ServerError<*>
throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse)
}
}
}
/**
* 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
* @return void
* @throws UnsupportedOperationException If the API returns an informational or redirection response
* @throws ClientException If the API returns a client error response
* @throws ServerException If the API returns a server error response
*/
@Throws(UnsupportedOperationException::class, ClientException::class, ServerException::class)
fun updateUser(username: kotlin.String, body: User) : Unit {
val localVariableBody: kotlin.Any? = body
val localVariableQuery: MultiValueMap = mutableMapOf()
val localVariableHeaders: MutableMap<String, String> = mutableMapOf()
val localVariableConfig = RequestConfig(
RequestMethod.PUT,
"/user/{username}".replace("{"+"username"+"}", "$username"),
query = localVariableQuery,
headers = localVariableHeaders
)
val localVarResponse = request<Any?>(
localVariableConfig,
localVariableBody
)
return when (localVarResponse.responseType) {
ResponseType.Success -> Unit
ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.")
ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.")
ResponseType.ClientError -> {
val localVarError = localVarResponse as ClientError<*>
throw ClientException("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse)
}
ResponseType.ServerError -> {
val localVarError = localVarResponse as ServerError<*>
throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse)
}
}
}
}

View File

@ -0,0 +1,23 @@
package org.openapitools.client.infrastructure
typealias MultiValueMap = MutableMap<String,List<String>>
fun collectionDelimiter(collectionFormat: String) = when(collectionFormat) {
"csv" -> ","
"tsv" -> "\t"
"pipe" -> "|"
"space" -> " "
else -> ""
}
val defaultMultiValueConverter: (item: Any?) -> String = { item -> "$item" }
fun <T : Any?> toMultiValue(items: Array<T>, collectionFormat: String, map: (item: T) -> String = defaultMultiValueConverter)
= toMultiValue(items.asIterable(), collectionFormat, map)
fun <T : Any?> toMultiValue(items: Iterable<T>, collectionFormat: String, map: (item: T) -> String = defaultMultiValueConverter): List<String> {
return when(collectionFormat) {
"multi" -> items.map(map)
else -> listOf(items.joinToString(separator = collectionDelimiter(collectionFormat), transform = map))
}
}

View File

@ -0,0 +1,245 @@
package org.openapitools.client.infrastructure
import okhttp3.Credentials
import okhttp3.OkHttpClient
import okhttp3.RequestBody
import okhttp3.RequestBody.Companion.asRequestBody
import okhttp3.RequestBody.Companion.toRequestBody
import okhttp3.FormBody
import okhttp3.HttpUrl.Companion.toHttpUrlOrNull
import okhttp3.ResponseBody
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.Request
import okhttp3.Headers
import okhttp3.MultipartBody
import java.io.File
import java.net.URLConnection
import java.util.Date
import java.time.LocalDate
import java.time.LocalDateTime
import java.time.LocalTime
import java.time.OffsetDateTime
import java.time.OffsetTime
open class ApiClient(val baseUrl: String) {
companion object {
protected const val ContentType = "Content-Type"
protected const val Accept = "Accept"
protected const val Authorization = "Authorization"
protected const val JsonMediaType = "application/json"
protected const val FormDataMediaType = "multipart/form-data"
protected const val FormUrlEncMediaType = "application/x-www-form-urlencoded"
protected const val XmlMediaType = "application/xml"
val apiKey: MutableMap<String, String> = mutableMapOf()
val apiKeyPrefix: MutableMap<String, String> = mutableMapOf()
var username: String? = null
var password: String? = null
var accessToken: String? = null
@JvmStatic
val client: OkHttpClient by lazy {
builder.build()
}
@JvmStatic
val builder: OkHttpClient.Builder = OkHttpClient.Builder()
}
/**
* Guess Content-Type header from the given file (defaults to "application/octet-stream").
*
* @param file The given file
* @return The guessed Content-Type
*/
protected fun guessContentTypeFromFile(file: File): String {
val contentType = URLConnection.guessContentTypeFromName(file.name)
return contentType ?: "application/octet-stream"
}
protected inline fun <reified T> requestBody(content: T, mediaType: String = JsonMediaType): RequestBody =
when {
content is File -> content.asRequestBody(
mediaType.toMediaTypeOrNull()
)
mediaType == FormDataMediaType -> {
MultipartBody.Builder()
.setType(MultipartBody.FORM)
.apply {
// content's type *must* be Map<String, Any?>
@Suppress("UNCHECKED_CAST")
(content as Map<String, Any?>).forEach { (key, value) ->
if (value is File) {
val partHeaders = Headers.headersOf(
"Content-Disposition",
"form-data; name=\"$key\"; filename=\"${value.name}\""
)
val fileMediaType = guessContentTypeFromFile(value).toMediaTypeOrNull()
addPart(partHeaders, value.asRequestBody(fileMediaType))
} else {
val partHeaders = Headers.headersOf(
"Content-Disposition",
"form-data; name=\"$key\""
)
addPart(
partHeaders,
parameterToString(value).toRequestBody(null)
)
}
}
}.build()
}
mediaType == FormUrlEncMediaType -> {
FormBody.Builder().apply {
// content's type *must* be Map<String, Any?>
@Suppress("UNCHECKED_CAST")
(content as Map<String, Any?>).forEach { (key, value) ->
add(key, parameterToString(value))
}
}.build()
}
mediaType == JsonMediaType -> Serializer.moshi.adapter(T::class.java).toJson(content).toRequestBody(
mediaType.toMediaTypeOrNull()
)
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.")
}
protected inline fun <reified T: Any?> responseBody(body: ResponseBody?, mediaType: String? = JsonMediaType): T? {
if(body == null) {
return null
}
val bodyContent = body.string()
if (bodyContent.isEmpty()) {
return null
}
return when(mediaType) {
JsonMediaType -> Serializer.moshi.adapter(T::class.java).fromJson(bodyContent)
else -> throw UnsupportedOperationException("responseBody currently only supports JSON body.")
}
}
protected fun updateAuthParams(requestConfig: RequestConfig) {
if (requestConfig.headers["api_key"].isNullOrEmpty()) {
if (apiKey["api_key"] != null) {
if (apiKeyPrefix["api_key"] != null) {
requestConfig.headers["api_key"] = apiKeyPrefix["api_key"]!! + " " + apiKey["api_key"]!!
} else {
requestConfig.headers["api_key"] = apiKey["api_key"]!!
}
}
}
if (requestConfig.headers[Authorization].isNullOrEmpty()) {
accessToken?.let { accessToken ->
requestConfig.headers[Authorization] = "Bearer $accessToken "
}
}
}
protected inline fun <reified T: Any?> request(requestConfig: RequestConfig, body : Any? = null): ApiInfrastructureResponse<T?> {
val httpUrl = baseUrl.toHttpUrlOrNull() ?: throw IllegalStateException("baseUrl is invalid.")
// take authMethod from operation
updateAuthParams(requestConfig)
val url = httpUrl.newBuilder()
.addPathSegments(requestConfig.path.trimStart('/'))
.apply {
requestConfig.query.forEach { query ->
query.value.forEach { queryValue ->
addQueryParameter(query.key, queryValue)
}
}
}.build()
// take content-type/accept from spec or set to default (application/json) if not defined
if (requestConfig.headers[ContentType].isNullOrEmpty()) {
requestConfig.headers[ContentType] = JsonMediaType
}
if (requestConfig.headers[Accept].isNullOrEmpty()) {
requestConfig.headers[Accept] = JsonMediaType
}
val headers = requestConfig.headers
if(headers[ContentType] ?: "" == "") {
throw kotlin.IllegalStateException("Missing Content-Type header. This is required.")
}
if(headers[Accept] ?: "" == "") {
throw kotlin.IllegalStateException("Missing Accept header. This is required.")
}
// TODO: support multiple contentType options here.
val contentType = (headers[ContentType] as String).substringBefore(";").toLowerCase()
val request = when (requestConfig.method) {
RequestMethod.DELETE -> Request.Builder().url(url).delete(requestBody(body, contentType))
RequestMethod.GET -> Request.Builder().url(url)
RequestMethod.HEAD -> Request.Builder().url(url).head()
RequestMethod.PATCH -> Request.Builder().url(url).patch(requestBody(body, contentType))
RequestMethod.PUT -> Request.Builder().url(url).put(requestBody(body, contentType))
RequestMethod.POST -> Request.Builder().url(url).post(requestBody(body, contentType))
RequestMethod.OPTIONS -> Request.Builder().url(url).method("OPTIONS", null)
}.apply {
headers.forEach { header -> addHeader(header.key, header.value) }
}.build()
val response = client.newCall(request).execute()
val accept = response.header(ContentType)?.substringBefore(";")?.toLowerCase()
// TODO: handle specific mapping types. e.g. Map<int, Class<?>>
when {
response.isRedirect -> return Redirection(
response.code,
response.headers.toMultimap()
)
response.isInformational -> return Informational(
response.message,
response.code,
response.headers.toMultimap()
)
response.isSuccessful -> return Success(
responseBody(response.body, accept),
response.code,
response.headers.toMultimap()
)
response.isClientError -> return ClientError(
response.message,
response.body?.string(),
response.code,
response.headers.toMultimap()
)
else -> return ServerError(
response.message,
response.body?.string(),
response.code,
response.headers.toMultimap()
)
}
}
protected fun parameterToString(value: Any?): String {
when (value) {
null -> {
return ""
}
is Array<*> -> {
return toMultiValue(value, "csv").toString()
}
is Iterable<*> -> {
return toMultiValue(value, "csv").toString()
}
is OffsetDateTime, is OffsetTime, is LocalDateTime, is LocalDate, is LocalTime, is Date -> {
return parseDateToQueryString<Any>(value)
}
else -> {
return value.toString()
}
}
}
protected inline fun <reified T: Any> parseDateToQueryString(value : T): String {
return value.toString()
}
}

View File

@ -0,0 +1,43 @@
package org.openapitools.client.infrastructure
enum class ResponseType {
Success, Informational, Redirection, ClientError, ServerError
}
interface Response
abstract class ApiInfrastructureResponse<T>(val responseType: ResponseType): Response {
abstract val statusCode: Int
abstract val headers: Map<String,List<String>>
}
class Success<T>(
val data: T,
override val statusCode: Int = -1,
override val headers: Map<String, List<String>> = mapOf()
): ApiInfrastructureResponse<T>(ResponseType.Success)
class Informational<T>(
val statusText: String,
override val statusCode: Int = -1,
override val headers: Map<String, List<String>> = mapOf()
) : ApiInfrastructureResponse<T>(ResponseType.Informational)
class Redirection<T>(
override val statusCode: Int = -1,
override val headers: Map<String, List<String>> = mapOf()
) : ApiInfrastructureResponse<T>(ResponseType.Redirection)
class ClientError<T>(
val message: String? = null,
val body: Any? = null,
override val statusCode: Int = -1,
override val headers: Map<String, List<String>> = mapOf()
) : ApiInfrastructureResponse<T>(ResponseType.ClientError)
class ServerError<T>(
val message: String? = null,
val body: Any? = null,
override val statusCode: Int = -1,
override val headers: Map<String, List<String>>
): ApiInfrastructureResponse<T>(ResponseType.ServerError)

View File

@ -0,0 +1,29 @@
package org.openapitools.client.infrastructure
import kotlin.properties.ReadWriteProperty
import kotlin.reflect.KProperty
object ApplicationDelegates {
/**
* Provides a property delegate, allowing the property to be set once and only once.
*
* If unset (no default value), a get on the property will throw [IllegalStateException].
*/
fun <T> setOnce(defaultValue: T? = null) : ReadWriteProperty<Any?, T> = SetOnce(defaultValue)
private class SetOnce<T>(defaultValue: T? = null) : ReadWriteProperty<Any?, T> {
private var isSet = false
private var value: T? = defaultValue
override fun getValue(thisRef: Any?, property: KProperty<*>): T {
return value ?: throw IllegalStateException("${property.name} not initialized")
}
override fun setValue(thisRef: Any?, property: KProperty<*>, value: T) = synchronized(this) {
if (!isSet) {
this.value = value
isSet = true
}
}
}
}

View File

@ -0,0 +1,12 @@
package org.openapitools.client.infrastructure
import com.squareup.moshi.FromJson
import com.squareup.moshi.ToJson
class ByteArrayAdapter {
@ToJson
fun toJson(data: ByteArray): String = String(data)
@FromJson
fun fromJson(data: String): ByteArray = data.toByteArray()
}

View File

@ -0,0 +1,18 @@
@file:Suppress("unused")
package org.openapitools.client.infrastructure
import java.lang.RuntimeException
open class ClientException(message: kotlin.String? = null, val statusCode: Int = -1, val response: Response? = null) : RuntimeException(message) {
companion object {
private const val serialVersionUID: Long = 123L
}
}
open class ServerException(message: kotlin.String? = null, val statusCode: Int = -1, val response: Response? = null) : RuntimeException(message) {
companion object {
private const val serialVersionUID: Long = 456L
}
}

View File

@ -0,0 +1,19 @@
package org.openapitools.client.infrastructure
import com.squareup.moshi.FromJson
import com.squareup.moshi.ToJson
import java.time.LocalDate
import java.time.format.DateTimeFormatter
class LocalDateAdapter {
@ToJson
fun toJson(value: LocalDate): String {
return DateTimeFormatter.ISO_LOCAL_DATE.format(value)
}
@FromJson
fun fromJson(value: String): LocalDate {
return LocalDate.parse(value, DateTimeFormatter.ISO_LOCAL_DATE)
}
}

View File

@ -0,0 +1,19 @@
package org.openapitools.client.infrastructure
import com.squareup.moshi.FromJson
import com.squareup.moshi.ToJson
import java.time.LocalDateTime
import java.time.format.DateTimeFormatter
class LocalDateTimeAdapter {
@ToJson
fun toJson(value: LocalDateTime): String {
return DateTimeFormatter.ISO_LOCAL_DATE_TIME.format(value)
}
@FromJson
fun fromJson(value: String): LocalDateTime {
return LocalDateTime.parse(value, DateTimeFormatter.ISO_LOCAL_DATE_TIME)
}
}

View File

@ -0,0 +1,19 @@
package org.openapitools.client.infrastructure
import com.squareup.moshi.FromJson
import com.squareup.moshi.ToJson
import java.time.OffsetDateTime
import java.time.format.DateTimeFormatter
class OffsetDateTimeAdapter {
@ToJson
fun toJson(value: OffsetDateTime): String {
return DateTimeFormatter.ISO_OFFSET_DATE_TIME.format(value)
}
@FromJson
fun fromJson(value: String): OffsetDateTime {
return OffsetDateTime.parse(value, DateTimeFormatter.ISO_OFFSET_DATE_TIME)
}
}

View File

@ -0,0 +1,16 @@
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<String,String> because rfc2616 defines
* multi-valued headers as csv-only.
*/
data class RequestConfig(
val method: RequestMethod,
val path: String,
val headers: MutableMap<String, String> = mutableMapOf(),
val query: MutableMap<String, List<String>> = mutableMapOf()
)

View File

@ -0,0 +1,8 @@
package org.openapitools.client.infrastructure
/**
* Provides enumerated HTTP verbs
*/
enum class RequestMethod {
GET, DELETE, HEAD, OPTIONS, PATCH, POST, PUT
}

View File

@ -0,0 +1,24 @@
package org.openapitools.client.infrastructure
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
/**
* Provides an extension to evaluation whether the response is a 3xx code
*/
@Suppress("EXTENSION_SHADOWED_BY_MEMBER")
val Response.isRedirect : Boolean get() = this.code 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
/**
* 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

View File

@ -0,0 +1,23 @@
package org.openapitools.client.infrastructure
import com.squareup.moshi.Moshi
import com.squareup.moshi.adapters.Rfc3339DateJsonAdapter
import com.squareup.moshi.kotlin.reflect.KotlinJsonAdapterFactory
import java.util.Date
object Serializer {
@JvmStatic
val moshiBuilder: Moshi.Builder = Moshi.Builder()
.add(Date::class.java, Rfc3339DateJsonAdapter().nullSafe())
.add(OffsetDateTimeAdapter())
.add(LocalDateTimeAdapter())
.add(LocalDateAdapter())
.add(UUIDAdapter())
.add(ByteArrayAdapter())
.add(KotlinJsonAdapterFactory())
@JvmStatic
val moshi: Moshi by lazy {
moshiBuilder.build()
}
}

View File

@ -0,0 +1,13 @@
package org.openapitools.client.infrastructure
import com.squareup.moshi.FromJson
import com.squareup.moshi.ToJson
import java.util.UUID
class UUIDAdapter {
@ToJson
fun toJson(uuid: UUID) = uuid.toString()
@FromJson
fun fromJson(s: String) = UUID.fromString(s)
}

View File

@ -0,0 +1,32 @@
/**
* 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.client.models
import com.squareup.moshi.Json
/**
* Describes the result of uploading an image resource
* @param code
* @param type
* @param message
*/
data class ApiResponse (
@Json(name = "code")
val code: kotlin.Int? = null,
@Json(name = "type")
val type: kotlin.String? = null,
@Json(name = "message")
val message: kotlin.String? = null
)

View File

@ -0,0 +1,29 @@
/**
* 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.client.models
import com.squareup.moshi.Json
/**
* A category for a pet
* @param id
* @param name
*/
data class Category (
@Json(name = "id")
val id: kotlin.Long? = null,
@Json(name = "name")
val name: kotlin.String? = null
)

View File

@ -0,0 +1,54 @@
/**
* 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.client.models
import com.squareup.moshi.Json
/**
* 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 (
@Json(name = "id")
val id: kotlin.Long? = null,
@Json(name = "petId")
val petId: kotlin.Long? = null,
@Json(name = "quantity")
val quantity: kotlin.Int? = null,
@Json(name = "shipDate")
val shipDate: java.time.OffsetDateTime? = null,
/* Order Status */
@Json(name = "status")
val status: Order.Status? = null,
@Json(name = "complete")
val complete: kotlin.Boolean? = null
) {
/**
* Order Status
* Values: placed,approved,delivered
*/
enum class Status(val value: kotlin.String){
@Json(name = "placed") placed("placed"),
@Json(name = "approved") approved("approved"),
@Json(name = "delivered") delivered("delivered");
}
}

View File

@ -0,0 +1,56 @@
/**
* 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.client.models
import org.openapitools.client.models.Category
import org.openapitools.client.models.Tag
import com.squareup.moshi.Json
/**
* 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 (
@Json(name = "name")
val name: kotlin.String,
@Json(name = "photoUrls")
val photoUrls: kotlin.collections.List<kotlin.String>,
@Json(name = "id")
val id: kotlin.Long? = null,
@Json(name = "category")
val category: Category? = null,
@Json(name = "tags")
val tags: kotlin.collections.List<Tag>? = null,
/* pet status in the store */
@Json(name = "status")
val status: Pet.Status? = null
) {
/**
* pet status in the store
* Values: available,pending,sold
*/
enum class Status(val value: kotlin.String){
@Json(name = "available") available("available"),
@Json(name = "pending") pending("pending"),
@Json(name = "sold") sold("sold");
}
}

View File

@ -0,0 +1,29 @@
/**
* 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.client.models
import com.squareup.moshi.Json
/**
* A tag for a pet
* @param id
* @param name
*/
data class Tag (
@Json(name = "id")
val id: kotlin.Long? = null,
@Json(name = "name")
val name: kotlin.String? = null
)

View File

@ -0,0 +1,48 @@
/**
* 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.client.models
import com.squareup.moshi.Json
/**
* 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 (
@Json(name = "id")
val id: kotlin.Long? = null,
@Json(name = "username")
val username: kotlin.String? = null,
@Json(name = "firstName")
val firstName: kotlin.String? = null,
@Json(name = "lastName")
val lastName: kotlin.String? = null,
@Json(name = "email")
val email: kotlin.String? = null,
@Json(name = "password")
val password: kotlin.String? = null,
@Json(name = "phone")
val phone: kotlin.String? = null,
/* User Status */
@Json(name = "userStatus")
val userStatus: kotlin.Int? = null
)

View File

@ -0,0 +1,374 @@
/**
* 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.client.apis
import org.openapitools.client.models.ApiResponse
import org.openapitools.client.models.Pet
import org.openapitools.client.infrastructure.ApiClient
import org.openapitools.client.infrastructure.ClientException
import org.openapitools.client.infrastructure.ClientError
import org.openapitools.client.infrastructure.ServerException
import org.openapitools.client.infrastructure.ServerError
import org.openapitools.client.infrastructure.MultiValueMap
import org.openapitools.client.infrastructure.RequestConfig
import org.openapitools.client.infrastructure.RequestMethod
import org.openapitools.client.infrastructure.ResponseType
import org.openapitools.client.infrastructure.Success
import org.openapitools.client.infrastructure.toMultiValue
class PetApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) {
companion object {
@JvmStatic
val defaultBasePath: String by lazy {
System.getProperties().getProperty("org.openapitools.client.baseUrl", "http://petstore.swagger.io/v2")
}
}
/**
* Add a new pet to the store
*
* @param body Pet object that needs to be added to the store
* @return void
* @throws UnsupportedOperationException If the API returns an informational or redirection response
* @throws ClientException If the API returns a client error response
* @throws ServerException If the API returns a server error response
*/
@Throws(UnsupportedOperationException::class, ClientException::class, ServerException::class)
fun addPet(body: Pet) : Unit {
val localVariableBody: kotlin.Any? = body
val localVariableQuery: MultiValueMap = mutableMapOf()
val localVariableHeaders: MutableMap<String, String> = mutableMapOf()
val localVariableConfig = RequestConfig(
RequestMethod.POST,
"/pet",
query = localVariableQuery,
headers = localVariableHeaders
)
val localVarResponse = request<Any?>(
localVariableConfig,
localVariableBody
)
return when (localVarResponse.responseType) {
ResponseType.Success -> Unit
ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.")
ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.")
ResponseType.ClientError -> {
val localVarError = localVarResponse as ClientError<*>
throw ClientException("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse)
}
ResponseType.ServerError -> {
val localVarError = localVarResponse as ServerError<*>
throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse)
}
}
}
/**
* Deletes a pet
*
* @param petId Pet id to delete
* @param apiKey (optional)
* @return void
* @throws UnsupportedOperationException If the API returns an informational or redirection response
* @throws ClientException If the API returns a client error response
* @throws ServerException If the API returns a server error response
*/
@Throws(UnsupportedOperationException::class, ClientException::class, ServerException::class)
fun deletePet(petId: kotlin.Long, apiKey: kotlin.String?) : Unit {
val localVariableBody: kotlin.Any? = null
val localVariableQuery: MultiValueMap = mutableMapOf()
val localVariableHeaders: MutableMap<String, String> = mutableMapOf()
apiKey?.apply { localVariableHeaders["api_key"] = this.toString() }
val localVariableConfig = RequestConfig(
RequestMethod.DELETE,
"/pet/{petId}".replace("{"+"petId"+"}", "$petId"),
query = localVariableQuery,
headers = localVariableHeaders
)
val localVarResponse = request<Any?>(
localVariableConfig,
localVariableBody
)
return when (localVarResponse.responseType) {
ResponseType.Success -> Unit
ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.")
ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.")
ResponseType.ClientError -> {
val localVarError = localVarResponse as ClientError<*>
throw ClientException("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse)
}
ResponseType.ServerError -> {
val localVarError = localVarResponse as ServerError<*>
throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse)
}
}
}
/**
* 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
* @return kotlin.collections.List<Pet>
* @throws UnsupportedOperationException If the API returns an informational or redirection response
* @throws ClientException If the API returns a client error response
* @throws ServerException If the API returns a server error response
*/
@Suppress("UNCHECKED_CAST")
@Throws(UnsupportedOperationException::class, ClientException::class, ServerException::class)
fun findPetsByStatus(status: kotlin.collections.List<kotlin.String>) : kotlin.collections.List<Pet> {
val localVariableBody: kotlin.Any? = null
val localVariableQuery: MultiValueMap = mutableMapOf<kotlin.String, List<kotlin.String>>()
.apply {
put("status", toMultiValue(status.toList(), "csv"))
}
val localVariableHeaders: MutableMap<String, String> = mutableMapOf()
val localVariableConfig = RequestConfig(
RequestMethod.GET,
"/pet/findByStatus",
query = localVariableQuery,
headers = localVariableHeaders
)
val localVarResponse = request<kotlin.collections.List<Pet>>(
localVariableConfig,
localVariableBody
)
return when (localVarResponse.responseType) {
ResponseType.Success -> (localVarResponse as Success<*>).data as kotlin.collections.List<Pet>
ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.")
ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.")
ResponseType.ClientError -> {
val localVarError = localVarResponse as ClientError<*>
throw ClientException("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse)
}
ResponseType.ServerError -> {
val localVarError = localVarResponse as ServerError<*>
throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse)
}
}
}
/**
* 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
* @return kotlin.collections.List<Pet>
* @throws UnsupportedOperationException If the API returns an informational or redirection response
* @throws ClientException If the API returns a client error response
* @throws ServerException If the API returns a server error response
*/
@Suppress("UNCHECKED_CAST")
@Throws(UnsupportedOperationException::class, ClientException::class, ServerException::class)
@Deprecated(message = "This operation is deprecated.")
fun findPetsByTags(tags: kotlin.collections.List<kotlin.String>) : kotlin.collections.List<Pet> {
val localVariableBody: kotlin.Any? = null
val localVariableQuery: MultiValueMap = mutableMapOf<kotlin.String, List<kotlin.String>>()
.apply {
put("tags", toMultiValue(tags.toList(), "csv"))
}
val localVariableHeaders: MutableMap<String, String> = mutableMapOf()
val localVariableConfig = RequestConfig(
RequestMethod.GET,
"/pet/findByTags",
query = localVariableQuery,
headers = localVariableHeaders
)
val localVarResponse = request<kotlin.collections.List<Pet>>(
localVariableConfig,
localVariableBody
)
return when (localVarResponse.responseType) {
ResponseType.Success -> (localVarResponse as Success<*>).data as kotlin.collections.List<Pet>
ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.")
ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.")
ResponseType.ClientError -> {
val localVarError = localVarResponse as ClientError<*>
throw ClientException("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse)
}
ResponseType.ServerError -> {
val localVarError = localVarResponse as ServerError<*>
throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse)
}
}
}
/**
* Find pet by ID
* Returns a single pet
* @param petId ID of pet to return
* @return Pet
* @throws UnsupportedOperationException If the API returns an informational or redirection response
* @throws ClientException If the API returns a client error response
* @throws ServerException If the API returns a server error response
*/
@Suppress("UNCHECKED_CAST")
@Throws(UnsupportedOperationException::class, ClientException::class, ServerException::class)
fun getPetById(petId: kotlin.Long) : Pet {
val localVariableBody: kotlin.Any? = null
val localVariableQuery: MultiValueMap = mutableMapOf()
val localVariableHeaders: MutableMap<String, String> = mutableMapOf()
val localVariableConfig = RequestConfig(
RequestMethod.GET,
"/pet/{petId}".replace("{"+"petId"+"}", "$petId"),
query = localVariableQuery,
headers = localVariableHeaders
)
val localVarResponse = request<Pet>(
localVariableConfig,
localVariableBody
)
return when (localVarResponse.responseType) {
ResponseType.Success -> (localVarResponse as Success<*>).data as Pet
ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.")
ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.")
ResponseType.ClientError -> {
val localVarError = localVarResponse as ClientError<*>
throw ClientException("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse)
}
ResponseType.ServerError -> {
val localVarError = localVarResponse as ServerError<*>
throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse)
}
}
}
/**
* Update an existing pet
*
* @param body Pet object that needs to be added to the store
* @return void
* @throws UnsupportedOperationException If the API returns an informational or redirection response
* @throws ClientException If the API returns a client error response
* @throws ServerException If the API returns a server error response
*/
@Throws(UnsupportedOperationException::class, ClientException::class, ServerException::class)
fun updatePet(body: Pet) : Unit {
val localVariableBody: kotlin.Any? = body
val localVariableQuery: MultiValueMap = mutableMapOf()
val localVariableHeaders: MutableMap<String, String> = mutableMapOf()
val localVariableConfig = RequestConfig(
RequestMethod.PUT,
"/pet",
query = localVariableQuery,
headers = localVariableHeaders
)
val localVarResponse = request<Any?>(
localVariableConfig,
localVariableBody
)
return when (localVarResponse.responseType) {
ResponseType.Success -> Unit
ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.")
ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.")
ResponseType.ClientError -> {
val localVarError = localVarResponse as ClientError<*>
throw ClientException("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse)
}
ResponseType.ServerError -> {
val localVarError = localVarResponse as ServerError<*>
throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse)
}
}
}
/**
* 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)
* @return void
* @throws UnsupportedOperationException If the API returns an informational or redirection response
* @throws ClientException If the API returns a client error response
* @throws ServerException If the API returns a server error response
*/
@Throws(UnsupportedOperationException::class, ClientException::class, ServerException::class)
fun updatePetWithForm(petId: kotlin.Long, name: kotlin.String?, status: kotlin.String?) : Unit {
val localVariableBody: kotlin.Any? = mapOf("name" to name, "status" to status)
val localVariableQuery: MultiValueMap = mutableMapOf()
val localVariableHeaders: MutableMap<String, String> = mutableMapOf("Content-Type" to "application/x-www-form-urlencoded")
val localVariableConfig = RequestConfig(
RequestMethod.POST,
"/pet/{petId}".replace("{"+"petId"+"}", "$petId"),
query = localVariableQuery,
headers = localVariableHeaders
)
val localVarResponse = request<Any?>(
localVariableConfig,
localVariableBody
)
return when (localVarResponse.responseType) {
ResponseType.Success -> Unit
ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.")
ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.")
ResponseType.ClientError -> {
val localVarError = localVarResponse as ClientError<*>
throw ClientException("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse)
}
ResponseType.ServerError -> {
val localVarError = localVarResponse as ServerError<*>
throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse)
}
}
}
/**
* 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)
* @return ApiResponse
* @throws UnsupportedOperationException If the API returns an informational or redirection response
* @throws ClientException If the API returns a client error response
* @throws ServerException If the API returns a server error response
*/
@Suppress("UNCHECKED_CAST")
@Throws(UnsupportedOperationException::class, ClientException::class, ServerException::class)
fun uploadFile(petId: kotlin.Long, additionalMetadata: kotlin.String?, file: java.io.File?) : ApiResponse {
val localVariableBody: kotlin.Any? = mapOf("additionalMetadata" to additionalMetadata, "file" to file)
val localVariableQuery: MultiValueMap = mutableMapOf()
val localVariableHeaders: MutableMap<String, String> = mutableMapOf("Content-Type" to "multipart/form-data")
val localVariableConfig = RequestConfig(
RequestMethod.POST,
"/pet/{petId}/uploadImage".replace("{"+"petId"+"}", "$petId"),
query = localVariableQuery,
headers = localVariableHeaders
)
val localVarResponse = request<ApiResponse>(
localVariableConfig,
localVariableBody
)
return when (localVarResponse.responseType) {
ResponseType.Success -> (localVarResponse as Success<*>).data as ApiResponse
ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.")
ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.")
ResponseType.ClientError -> {
val localVarError = localVarResponse as ClientError<*>
throw ClientException("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse)
}
ResponseType.ServerError -> {
val localVarError = localVarResponse as ServerError<*>
throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse)
}
}
}
}

View File

@ -0,0 +1,198 @@
/**
* 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.client.apis
import org.openapitools.client.models.Order
import org.openapitools.client.infrastructure.ApiClient
import org.openapitools.client.infrastructure.ClientException
import org.openapitools.client.infrastructure.ClientError
import org.openapitools.client.infrastructure.ServerException
import org.openapitools.client.infrastructure.ServerError
import org.openapitools.client.infrastructure.MultiValueMap
import org.openapitools.client.infrastructure.RequestConfig
import org.openapitools.client.infrastructure.RequestMethod
import org.openapitools.client.infrastructure.ResponseType
import org.openapitools.client.infrastructure.Success
import org.openapitools.client.infrastructure.toMultiValue
class StoreApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) {
companion object {
@JvmStatic
val defaultBasePath: String by lazy {
System.getProperties().getProperty("org.openapitools.client.baseUrl", "http://petstore.swagger.io/v2")
}
}
/**
* 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
* @return void
* @throws UnsupportedOperationException If the API returns an informational or redirection response
* @throws ClientException If the API returns a client error response
* @throws ServerException If the API returns a server error response
*/
@Throws(UnsupportedOperationException::class, ClientException::class, ServerException::class)
fun deleteOrder(orderId: kotlin.String) : Unit {
val localVariableBody: kotlin.Any? = null
val localVariableQuery: MultiValueMap = mutableMapOf()
val localVariableHeaders: MutableMap<String, String> = mutableMapOf()
val localVariableConfig = RequestConfig(
RequestMethod.DELETE,
"/store/order/{orderId}".replace("{"+"orderId"+"}", "$orderId"),
query = localVariableQuery,
headers = localVariableHeaders
)
val localVarResponse = request<Any?>(
localVariableConfig,
localVariableBody
)
return when (localVarResponse.responseType) {
ResponseType.Success -> Unit
ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.")
ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.")
ResponseType.ClientError -> {
val localVarError = localVarResponse as ClientError<*>
throw ClientException("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse)
}
ResponseType.ServerError -> {
val localVarError = localVarResponse as ServerError<*>
throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse)
}
}
}
/**
* Returns pet inventories by status
* Returns a map of status codes to quantities
* @return kotlin.collections.Map<kotlin.String, kotlin.Int>
* @throws UnsupportedOperationException If the API returns an informational or redirection response
* @throws ClientException If the API returns a client error response
* @throws ServerException If the API returns a server error response
*/
@Suppress("UNCHECKED_CAST")
@Throws(UnsupportedOperationException::class, ClientException::class, ServerException::class)
fun getInventory() : kotlin.collections.Map<kotlin.String, kotlin.Int> {
val localVariableBody: kotlin.Any? = null
val localVariableQuery: MultiValueMap = mutableMapOf()
val localVariableHeaders: MutableMap<String, String> = mutableMapOf()
val localVariableConfig = RequestConfig(
RequestMethod.GET,
"/store/inventory",
query = localVariableQuery,
headers = localVariableHeaders
)
val localVarResponse = request<kotlin.collections.Map<kotlin.String, kotlin.Int>>(
localVariableConfig,
localVariableBody
)
return when (localVarResponse.responseType) {
ResponseType.Success -> (localVarResponse as Success<*>).data as kotlin.collections.Map<kotlin.String, kotlin.Int>
ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.")
ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.")
ResponseType.ClientError -> {
val localVarError = localVarResponse as ClientError<*>
throw ClientException("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse)
}
ResponseType.ServerError -> {
val localVarError = localVarResponse as ServerError<*>
throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse)
}
}
}
/**
* 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
* @return Order
* @throws UnsupportedOperationException If the API returns an informational or redirection response
* @throws ClientException If the API returns a client error response
* @throws ServerException If the API returns a server error response
*/
@Suppress("UNCHECKED_CAST")
@Throws(UnsupportedOperationException::class, ClientException::class, ServerException::class)
fun getOrderById(orderId: kotlin.Long) : Order {
val localVariableBody: kotlin.Any? = null
val localVariableQuery: MultiValueMap = mutableMapOf()
val localVariableHeaders: MutableMap<String, String> = mutableMapOf()
val localVariableConfig = RequestConfig(
RequestMethod.GET,
"/store/order/{orderId}".replace("{"+"orderId"+"}", "$orderId"),
query = localVariableQuery,
headers = localVariableHeaders
)
val localVarResponse = request<Order>(
localVariableConfig,
localVariableBody
)
return when (localVarResponse.responseType) {
ResponseType.Success -> (localVarResponse as Success<*>).data as Order
ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.")
ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.")
ResponseType.ClientError -> {
val localVarError = localVarResponse as ClientError<*>
throw ClientException("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse)
}
ResponseType.ServerError -> {
val localVarError = localVarResponse as ServerError<*>
throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse)
}
}
}
/**
* Place an order for a pet
*
* @param body order placed for purchasing the pet
* @return Order
* @throws UnsupportedOperationException If the API returns an informational or redirection response
* @throws ClientException If the API returns a client error response
* @throws ServerException If the API returns a server error response
*/
@Suppress("UNCHECKED_CAST")
@Throws(UnsupportedOperationException::class, ClientException::class, ServerException::class)
fun placeOrder(body: Order) : Order {
val localVariableBody: kotlin.Any? = body
val localVariableQuery: MultiValueMap = mutableMapOf()
val localVariableHeaders: MutableMap<String, String> = mutableMapOf()
val localVariableConfig = RequestConfig(
RequestMethod.POST,
"/store/order",
query = localVariableQuery,
headers = localVariableHeaders
)
val localVarResponse = request<Order>(
localVariableConfig,
localVariableBody
)
return when (localVarResponse.responseType) {
ResponseType.Success -> (localVarResponse as Success<*>).data as Order
ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.")
ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.")
ResponseType.ClientError -> {
val localVarError = localVarResponse as ClientError<*>
throw ClientException("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse)
}
ResponseType.ServerError -> {
val localVarError = localVarResponse as ServerError<*>
throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse)
}
}
}
}

View File

@ -0,0 +1,363 @@
/**
* 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.client.apis
import org.openapitools.client.models.User
import org.openapitools.client.infrastructure.ApiClient
import org.openapitools.client.infrastructure.ClientException
import org.openapitools.client.infrastructure.ClientError
import org.openapitools.client.infrastructure.ServerException
import org.openapitools.client.infrastructure.ServerError
import org.openapitools.client.infrastructure.MultiValueMap
import org.openapitools.client.infrastructure.RequestConfig
import org.openapitools.client.infrastructure.RequestMethod
import org.openapitools.client.infrastructure.ResponseType
import org.openapitools.client.infrastructure.Success
import org.openapitools.client.infrastructure.toMultiValue
class UserApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) {
companion object {
@JvmStatic
val defaultBasePath: String by lazy {
System.getProperties().getProperty("org.openapitools.client.baseUrl", "http://petstore.swagger.io/v2")
}
}
/**
* Create user
* This can only be done by the logged in user.
* @param body Created user object
* @return void
* @throws UnsupportedOperationException If the API returns an informational or redirection response
* @throws ClientException If the API returns a client error response
* @throws ServerException If the API returns a server error response
*/
@Throws(UnsupportedOperationException::class, ClientException::class, ServerException::class)
fun createUser(body: User) : Unit {
val localVariableBody: kotlin.Any? = body
val localVariableQuery: MultiValueMap = mutableMapOf()
val localVariableHeaders: MutableMap<String, String> = mutableMapOf()
val localVariableConfig = RequestConfig(
RequestMethod.POST,
"/user",
query = localVariableQuery,
headers = localVariableHeaders
)
val localVarResponse = request<Any?>(
localVariableConfig,
localVariableBody
)
return when (localVarResponse.responseType) {
ResponseType.Success -> Unit
ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.")
ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.")
ResponseType.ClientError -> {
val localVarError = localVarResponse as ClientError<*>
throw ClientException("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse)
}
ResponseType.ServerError -> {
val localVarError = localVarResponse as ServerError<*>
throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse)
}
}
}
/**
* Creates list of users with given input array
*
* @param body List of user object
* @return void
* @throws UnsupportedOperationException If the API returns an informational or redirection response
* @throws ClientException If the API returns a client error response
* @throws ServerException If the API returns a server error response
*/
@Throws(UnsupportedOperationException::class, ClientException::class, ServerException::class)
fun createUsersWithArrayInput(body: kotlin.collections.List<User>) : Unit {
val localVariableBody: kotlin.Any? = body
val localVariableQuery: MultiValueMap = mutableMapOf()
val localVariableHeaders: MutableMap<String, String> = mutableMapOf()
val localVariableConfig = RequestConfig(
RequestMethod.POST,
"/user/createWithArray",
query = localVariableQuery,
headers = localVariableHeaders
)
val localVarResponse = request<Any?>(
localVariableConfig,
localVariableBody
)
return when (localVarResponse.responseType) {
ResponseType.Success -> Unit
ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.")
ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.")
ResponseType.ClientError -> {
val localVarError = localVarResponse as ClientError<*>
throw ClientException("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse)
}
ResponseType.ServerError -> {
val localVarError = localVarResponse as ServerError<*>
throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse)
}
}
}
/**
* Creates list of users with given input array
*
* @param body List of user object
* @return void
* @throws UnsupportedOperationException If the API returns an informational or redirection response
* @throws ClientException If the API returns a client error response
* @throws ServerException If the API returns a server error response
*/
@Throws(UnsupportedOperationException::class, ClientException::class, ServerException::class)
fun createUsersWithListInput(body: kotlin.collections.List<User>) : Unit {
val localVariableBody: kotlin.Any? = body
val localVariableQuery: MultiValueMap = mutableMapOf()
val localVariableHeaders: MutableMap<String, String> = mutableMapOf()
val localVariableConfig = RequestConfig(
RequestMethod.POST,
"/user/createWithList",
query = localVariableQuery,
headers = localVariableHeaders
)
val localVarResponse = request<Any?>(
localVariableConfig,
localVariableBody
)
return when (localVarResponse.responseType) {
ResponseType.Success -> Unit
ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.")
ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.")
ResponseType.ClientError -> {
val localVarError = localVarResponse as ClientError<*>
throw ClientException("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse)
}
ResponseType.ServerError -> {
val localVarError = localVarResponse as ServerError<*>
throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse)
}
}
}
/**
* Delete user
* This can only be done by the logged in user.
* @param username The name that needs to be deleted
* @return void
* @throws UnsupportedOperationException If the API returns an informational or redirection response
* @throws ClientException If the API returns a client error response
* @throws ServerException If the API returns a server error response
*/
@Throws(UnsupportedOperationException::class, ClientException::class, ServerException::class)
fun deleteUser(username: kotlin.String) : Unit {
val localVariableBody: kotlin.Any? = null
val localVariableQuery: MultiValueMap = mutableMapOf()
val localVariableHeaders: MutableMap<String, String> = mutableMapOf()
val localVariableConfig = RequestConfig(
RequestMethod.DELETE,
"/user/{username}".replace("{"+"username"+"}", "$username"),
query = localVariableQuery,
headers = localVariableHeaders
)
val localVarResponse = request<Any?>(
localVariableConfig,
localVariableBody
)
return when (localVarResponse.responseType) {
ResponseType.Success -> Unit
ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.")
ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.")
ResponseType.ClientError -> {
val localVarError = localVarResponse as ClientError<*>
throw ClientException("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse)
}
ResponseType.ServerError -> {
val localVarError = localVarResponse as ServerError<*>
throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse)
}
}
}
/**
* Get user by user name
*
* @param username The name that needs to be fetched. Use user1 for testing.
* @return User
* @throws UnsupportedOperationException If the API returns an informational or redirection response
* @throws ClientException If the API returns a client error response
* @throws ServerException If the API returns a server error response
*/
@Suppress("UNCHECKED_CAST")
@Throws(UnsupportedOperationException::class, ClientException::class, ServerException::class)
fun getUserByName(username: kotlin.String) : User {
val localVariableBody: kotlin.Any? = null
val localVariableQuery: MultiValueMap = mutableMapOf()
val localVariableHeaders: MutableMap<String, String> = mutableMapOf()
val localVariableConfig = RequestConfig(
RequestMethod.GET,
"/user/{username}".replace("{"+"username"+"}", "$username"),
query = localVariableQuery,
headers = localVariableHeaders
)
val localVarResponse = request<User>(
localVariableConfig,
localVariableBody
)
return when (localVarResponse.responseType) {
ResponseType.Success -> (localVarResponse as Success<*>).data as User
ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.")
ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.")
ResponseType.ClientError -> {
val localVarError = localVarResponse as ClientError<*>
throw ClientException("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse)
}
ResponseType.ServerError -> {
val localVarError = localVarResponse as ServerError<*>
throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse)
}
}
}
/**
* Logs user into the system
*
* @param username The user name for login
* @param password The password for login in clear text
* @return kotlin.String
* @throws UnsupportedOperationException If the API returns an informational or redirection response
* @throws ClientException If the API returns a client error response
* @throws ServerException If the API returns a server error response
*/
@Suppress("UNCHECKED_CAST")
@Throws(UnsupportedOperationException::class, ClientException::class, ServerException::class)
fun loginUser(username: kotlin.String, password: kotlin.String) : kotlin.String {
val localVariableBody: kotlin.Any? = null
val localVariableQuery: MultiValueMap = mutableMapOf<kotlin.String, List<kotlin.String>>()
.apply {
put("username", listOf(username.toString()))
put("password", listOf(password.toString()))
}
val localVariableHeaders: MutableMap<String, String> = mutableMapOf()
val localVariableConfig = RequestConfig(
RequestMethod.GET,
"/user/login",
query = localVariableQuery,
headers = localVariableHeaders
)
val localVarResponse = request<kotlin.String>(
localVariableConfig,
localVariableBody
)
return when (localVarResponse.responseType) {
ResponseType.Success -> (localVarResponse as Success<*>).data as kotlin.String
ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.")
ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.")
ResponseType.ClientError -> {
val localVarError = localVarResponse as ClientError<*>
throw ClientException("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse)
}
ResponseType.ServerError -> {
val localVarError = localVarResponse as ServerError<*>
throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse)
}
}
}
/**
* Logs out current logged in user session
*
* @return void
* @throws UnsupportedOperationException If the API returns an informational or redirection response
* @throws ClientException If the API returns a client error response
* @throws ServerException If the API returns a server error response
*/
@Throws(UnsupportedOperationException::class, ClientException::class, ServerException::class)
fun logoutUser() : Unit {
val localVariableBody: kotlin.Any? = null
val localVariableQuery: MultiValueMap = mutableMapOf()
val localVariableHeaders: MutableMap<String, String> = mutableMapOf()
val localVariableConfig = RequestConfig(
RequestMethod.GET,
"/user/logout",
query = localVariableQuery,
headers = localVariableHeaders
)
val localVarResponse = request<Any?>(
localVariableConfig,
localVariableBody
)
return when (localVarResponse.responseType) {
ResponseType.Success -> Unit
ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.")
ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.")
ResponseType.ClientError -> {
val localVarError = localVarResponse as ClientError<*>
throw ClientException("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse)
}
ResponseType.ServerError -> {
val localVarError = localVarResponse as ServerError<*>
throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse)
}
}
}
/**
* 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
* @return void
* @throws UnsupportedOperationException If the API returns an informational or redirection response
* @throws ClientException If the API returns a client error response
* @throws ServerException If the API returns a server error response
*/
@Throws(UnsupportedOperationException::class, ClientException::class, ServerException::class)
fun updateUser(username: kotlin.String, body: User) : Unit {
val localVariableBody: kotlin.Any? = body
val localVariableQuery: MultiValueMap = mutableMapOf()
val localVariableHeaders: MutableMap<String, String> = mutableMapOf()
val localVariableConfig = RequestConfig(
RequestMethod.PUT,
"/user/{username}".replace("{"+"username"+"}", "$username"),
query = localVariableQuery,
headers = localVariableHeaders
)
val localVarResponse = request<Any?>(
localVariableConfig,
localVariableBody
)
return when (localVarResponse.responseType) {
ResponseType.Success -> Unit
ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.")
ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.")
ResponseType.ClientError -> {
val localVarError = localVarResponse as ClientError<*>
throw ClientException("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse)
}
ResponseType.ServerError -> {
val localVarError = localVarResponse as ServerError<*>
throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse)
}
}
}
}

View File

@ -0,0 +1,23 @@
package org.openapitools.client.infrastructure
typealias MultiValueMap = MutableMap<String,List<String>>
fun collectionDelimiter(collectionFormat: String) = when(collectionFormat) {
"csv" -> ","
"tsv" -> "\t"
"pipe" -> "|"
"space" -> " "
else -> ""
}
val defaultMultiValueConverter: (item: Any?) -> String = { item -> "$item" }
fun <T : Any?> toMultiValue(items: Array<T>, collectionFormat: String, map: (item: T) -> String = defaultMultiValueConverter)
= toMultiValue(items.asIterable(), collectionFormat, map)
fun <T : Any?> toMultiValue(items: Iterable<T>, collectionFormat: String, map: (item: T) -> String = defaultMultiValueConverter): List<String> {
return when(collectionFormat) {
"multi" -> items.map(map)
else -> listOf(items.joinToString(separator = collectionDelimiter(collectionFormat), transform = map))
}
}

View File

@ -0,0 +1,251 @@
package org.openapitools.client.infrastructure
import okhttp3.Credentials
import okhttp3.OkHttpClient
import okhttp3.RequestBody
import okhttp3.RequestBody.Companion.asRequestBody
import okhttp3.RequestBody.Companion.toRequestBody
import okhttp3.FormBody
import okhttp3.HttpUrl.Companion.toHttpUrlOrNull
import okhttp3.ResponseBody
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.Request
import okhttp3.Headers
import okhttp3.MultipartBody
import java.io.File
import java.net.URLConnection
import java.util.Date
import java.time.LocalDate
import java.time.LocalDateTime
import java.time.LocalTime
import java.time.OffsetDateTime
import java.time.OffsetTime
open class ApiClient(val baseUrl: String) {
companion object {
protected const val ContentType = "Content-Type"
protected const val Accept = "Accept"
protected const val Authorization = "Authorization"
protected const val JsonMediaType = "application/json"
protected const val FormDataMediaType = "multipart/form-data"
protected const val FormUrlEncMediaType = "application/x-www-form-urlencoded"
protected const val XmlMediaType = "application/xml"
val apiKey: MutableMap<String, String> = mutableMapOf()
val apiKeyPrefix: MutableMap<String, String> = mutableMapOf()
var username: String? = null
var password: String? = null
var accessToken: String? = null
@JvmStatic
val client: OkHttpClient by lazy {
builder.build()
}
@JvmStatic
val builder: OkHttpClient.Builder = OkHttpClient.Builder()
}
/**
* Guess Content-Type header from the given file (defaults to "application/octet-stream").
*
* @param file The given file
* @return The guessed Content-Type
*/
protected fun guessContentTypeFromFile(file: File): String {
val contentType = URLConnection.guessContentTypeFromName(file.name)
return contentType ?: "application/octet-stream"
}
protected inline fun <reified T> requestBody(content: T, mediaType: String = JsonMediaType): RequestBody =
when {
content is File -> content.asRequestBody(
mediaType.toMediaTypeOrNull()
)
mediaType == FormDataMediaType -> {
MultipartBody.Builder()
.setType(MultipartBody.FORM)
.apply {
// content's type *must* be Map<String, Any?>
@Suppress("UNCHECKED_CAST")
(content as Map<String, Any?>).forEach { (key, value) ->
if (value is File) {
val partHeaders = Headers.headersOf(
"Content-Disposition",
"form-data; name=\"$key\"; filename=\"${value.name}\""
)
val fileMediaType = guessContentTypeFromFile(value).toMediaTypeOrNull()
addPart(partHeaders, value.asRequestBody(fileMediaType))
} else {
val partHeaders = Headers.headersOf(
"Content-Disposition",
"form-data; name=\"$key\""
)
addPart(
partHeaders,
parameterToString(value).toRequestBody(null)
)
}
}
}.build()
}
mediaType == FormUrlEncMediaType -> {
FormBody.Builder().apply {
// content's type *must* be Map<String, Any?>
@Suppress("UNCHECKED_CAST")
(content as Map<String, Any?>).forEach { (key, value) ->
add(key, parameterToString(value))
}
}.build()
}
mediaType == JsonMediaType -> Serializer.moshi.adapter(T::class.java).toJson(content).toRequestBody(
mediaType.toMediaTypeOrNull()
)
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.")
}
protected inline fun <reified T: Any?> responseBody(body: ResponseBody?, mediaType: String? = JsonMediaType): T? {
if(body == null) {
return null
}
val bodyContent = body.string()
if (bodyContent.isEmpty()) {
return null
}
return when(mediaType) {
JsonMediaType -> Serializer.moshi.adapter(T::class.java).fromJson(bodyContent)
else -> throw UnsupportedOperationException("responseBody currently only supports JSON body.")
}
}
protected fun updateAuthParams(requestConfig: RequestConfig) {
if (requestConfig.headers["api_key"].isNullOrEmpty()) {
if (apiKey["api_key"] != null) {
if (apiKeyPrefix["api_key"] != null) {
requestConfig.headers["api_key"] = apiKeyPrefix["api_key"]!! + " " + apiKey["api_key"]!!
} else {
requestConfig.headers["api_key"] = apiKey["api_key"]!!
}
}
}
if (requestConfig.headers[Authorization].isNullOrEmpty()) {
accessToken?.let { accessToken ->
requestConfig.headers[Authorization] = "Bearer $accessToken "
}
}
}
protected inline fun <reified T: Any?> request(requestConfig: RequestConfig, body : Any? = null): ApiInfrastructureResponse<T?> {
val httpUrl = baseUrl.toHttpUrlOrNull() ?: throw IllegalStateException("baseUrl is invalid.")
// take authMethod from operation
updateAuthParams(requestConfig)
val url = httpUrl.newBuilder()
.addPathSegments(requestConfig.path.trimStart('/'))
.apply {
requestConfig.query.forEach { query ->
query.value.forEach { queryValue ->
addQueryParameter(query.key, queryValue)
}
}
}.build()
// take content-type/accept from spec or set to default (application/json) if not defined
if (requestConfig.headers[ContentType].isNullOrEmpty()) {
requestConfig.headers[ContentType] = JsonMediaType
}
if (requestConfig.headers[Accept].isNullOrEmpty()) {
requestConfig.headers[Accept] = JsonMediaType
}
val headers = requestConfig.headers
if(headers[ContentType] ?: "" == "") {
throw kotlin.IllegalStateException("Missing Content-Type header. This is required.")
}
if(headers[Accept] ?: "" == "") {
throw kotlin.IllegalStateException("Missing Accept header. This is required.")
}
// TODO: support multiple contentType options here.
val contentType = (headers[ContentType] as String).substringBefore(";").toLowerCase()
val request = when (requestConfig.method) {
RequestMethod.DELETE -> Request.Builder().url(url).delete(requestBody(body, contentType))
RequestMethod.GET -> Request.Builder().url(url)
RequestMethod.HEAD -> Request.Builder().url(url).head()
RequestMethod.PATCH -> Request.Builder().url(url).patch(requestBody(body, contentType))
RequestMethod.PUT -> Request.Builder().url(url).put(requestBody(body, contentType))
RequestMethod.POST -> Request.Builder().url(url).post(requestBody(body, contentType))
RequestMethod.OPTIONS -> Request.Builder().url(url).method("OPTIONS", null)
}.apply {
headers.forEach { header -> addHeader(header.key, header.value) }
}.build()
val response = client.newCall(request).execute()
val accept = response.header(ContentType)?.substringBefore(";")?.toLowerCase()
// TODO: handle specific mapping types. e.g. Map<int, Class<?>>
when {
response.isRedirect -> return Redirection(
response.code,
response.headers.toMultimap()
)
response.isInformational -> return Informational(
response.message,
response.code,
response.headers.toMultimap()
)
response.isSuccessful -> return Success(
responseBody(response.body, accept),
response.code,
response.headers.toMultimap()
)
response.isClientError -> return ClientError(
response.message,
response.body?.string(),
response.code,
response.headers.toMultimap()
)
else -> return ServerError(
response.message,
response.body?.string(),
response.code,
response.headers.toMultimap()
)
}
}
protected fun parameterToString(value: Any?): String {
when (value) {
null -> {
return ""
}
is Array<*> -> {
return toMultiValue(value, "csv").toString()
}
is Iterable<*> -> {
return toMultiValue(value, "csv").toString()
}
is OffsetDateTime, is OffsetTime, is LocalDateTime, is LocalDate, is LocalTime, is Date -> {
return parseDateToQueryString<Any>(value)
}
else -> {
return value.toString()
}
}
}
protected inline fun <reified T: Any> parseDateToQueryString(value : T): String {
/*
.replace("\"", "") converts the json object string to an actual string for the query parameter.
The moshi or gson adapter allows a more generic solution instead of trying to use a native
formatter. It also easily allows to provide a simple way to define a custom date format pattern
inside a gson/moshi adapter.
*/
return Serializer.moshi.adapter(T::class.java).toJson(value).replace("\"", "")
}
}

View File

@ -0,0 +1,43 @@
package org.openapitools.client.infrastructure
enum class ResponseType {
Success, Informational, Redirection, ClientError, ServerError
}
interface Response
abstract class ApiInfrastructureResponse<T>(val responseType: ResponseType): Response {
abstract val statusCode: Int
abstract val headers: Map<String,List<String>>
}
class Success<T>(
val data: T,
override val statusCode: Int = -1,
override val headers: Map<String, List<String>> = mapOf()
): ApiInfrastructureResponse<T>(ResponseType.Success)
class Informational<T>(
val statusText: String,
override val statusCode: Int = -1,
override val headers: Map<String, List<String>> = mapOf()
) : ApiInfrastructureResponse<T>(ResponseType.Informational)
class Redirection<T>(
override val statusCode: Int = -1,
override val headers: Map<String, List<String>> = mapOf()
) : ApiInfrastructureResponse<T>(ResponseType.Redirection)
class ClientError<T>(
val message: String? = null,
val body: Any? = null,
override val statusCode: Int = -1,
override val headers: Map<String, List<String>> = mapOf()
) : ApiInfrastructureResponse<T>(ResponseType.ClientError)
class ServerError<T>(
val message: String? = null,
val body: Any? = null,
override val statusCode: Int = -1,
override val headers: Map<String, List<String>>
): ApiInfrastructureResponse<T>(ResponseType.ServerError)

Some files were not shown because too many files have changed in this diff Show More