Compare commits

..

59 Commits

Author SHA1 Message Date
William Cheng
f37a431e49 update tests 2024-04-16 14:20:12 +08:00
William Cheng
f362ff1e88 fix 2024-04-16 14:05:37 +08:00
William Cheng
ef50215438 Merge remote-tracking branch 'origin/master' into timcbaoth-improve-camlization-in-default-codegen 2024-04-16 12:52:30 +08:00
weirdo
c7b33c4762 [Java] fix beanvalidation compilation failed when items type in array… (#18379)
* [Java] fix beanvalidation compilation failed when items type in array is int64

* [Java] add annotations container bean validation test
2024-04-16 12:30:39 +08:00
Radoslav Kotsev
1471e7a0d0 Go generate all of with multiple ref and discriminator (#18390)
* feat(go): Generate compiling stubs for allOf with multiple refs and discriminator

* feat(go): Generate compiling stubs for allOf with multiple refs and discriminator

* feat(go): Generate compiling stubs for allOf with multiple refs and discriminator
2024-04-16 12:21:00 +08:00
William Cheng
81f576c9da update dnspython to a newer version (#18376) 2024-04-13 10:52:43 +08:00
Daniel Metzner
8155d03c38 Allow Symfony 7 / Remove EOL PHP / Bearer Fix (#18357)
Bump requirements
  - add Symfony 7 support
  - remove support php < 8.2 (EOL)
  - remove symfony < 6.4 support

Bug Fix
  - add missing $security{{name}} variable when using Bearer Auth

Misc
 - getContentType method is deprecated; use getContentTypeFormat
 - use match instead of switch for simple assignments
 - remove default depth param from json_encode call
 - make data provider static (phpunit)
2024-04-13 10:46:47 +08:00
William Cheng
4cde53c3d7 update idna to newer version (fastapi) (#18372) 2024-04-13 09:37:08 +08:00
Aaron Pritzlaff
24c1968002 cask fix for response encoding (#18375) 2024-04-13 09:34:08 +08:00
William Cheng
359ff9e457 update html2 sample 2024-04-13 01:07:27 +08:00
Aaron Pritzlaff
85c81e84d5 scala cask fix for missing annotations on simple routes (#18371) 2024-04-13 00:46:51 +08:00
Aniokrait
86186586c7 [html2] Fix blank responses in html document (#18356)
* [html2]remove unnecessary mustache section

* [html2]add null check
2024-04-12 21:16:24 +08:00
Kathryn DiPippo
0b3e6edb98 [python] Update docs/ Markdown files for Classes to fix _form_ typo and correct casing for class name when calling from_dict() (#18359)
* Update Python mustache templates to fix _form_ typo and correct casing for class name when calling from_dict()

* Results of 'build the project' checklist step
2024-04-12 12:29:20 +08:00
Linh Tran Tuan
65e74a354d [Rust] [Axum] Revert PR #18061 (#18354) 2024-04-11 21:58:21 +08:00
William Cheng
b4c315ebce use model utils check instead of instanceof 2024-04-11 21:23:04 +08:00
William Cheng
03af25ce34 Fix null check in 3.1 spec (#18353)
* fix null check in 3.1 spec

* clean up
2024-04-11 16:52:31 +08:00
William Cheng
ff8fa40808 fix object and complex compposed schema check (#18352) 2024-04-11 14:26:45 +08:00
Viktor Szépe
172c4d11b4 Remove param tag for non-existent parameter in ObjectSerializer (#18347)
* Remove param tag for non-existent parameter in ObjectSerializer

* Remove all discriminator parameters
2024-04-11 13:17:15 +08:00
Mike Friesen
97c1dc8a1a #18252 - [REQ] add sessionToken support to AWS4Auth (#18253) 2024-04-11 11:56:40 +08:00
Bijan Chokoufe Nejad
44ae981830 Update versions for typescript-node and remove vulnerable test package (#18334)
* Update versions for typescript-node

Use latest versions for `bluebird` and `request` and remove `rewire`. `rewire` has high security alerts and shouldn't have been added to the generated clients as its used in tests. It was introduced here 960412a9b4 (diff-1df884eca4890fc2cff7eec6f61ac2157b1b9e72fe4cc13c782e300125fb0da3R20) although the same commit shows that it used to work without it 960412a9b4 (diff-d2785da28187b6d6ef1e0bdab42139309e443906fb5d9d365fce5e2a01673ef5R52-R56)

* Update Typescript sample
2024-04-11 10:45:41 +08:00
Beppe Catanese
a887f6d4bf Add test for CI suite (#18350) 2024-04-10 23:49:34 +08:00
BaptisteSaves
6bcc28d06e Python: Correctly serialize enum with its value (#18327) (#18328) 2024-04-10 21:12:37 +08:00
Val Packett
9351217048 [javascript] fix docs example quoting, fixes #6324 (#18349)
And prefer example over default
2024-04-10 18:58:13 +08:00
William Cheng
2bfc5a3958 [Scala] added new scala-cask generator for the cask framework (#18344)
* Ran `./new.sh -n scala-cask -s` to generate a new Scala Cask impl

* removed scala-cask-petstore

* Added Scala-cask param parser for BigDecimals

* added scala cask to samples

* splitting out validation and json

* Added GitHub workflow support

* regenerated cask samples

* cask build fix for local builds

* regenerated samples

* trying to reproduce failed cask build. checking in compiles sources, which have been reformatted

* reverted whaitespace change

* cask fix - adding gitignored files

* scala cask toLowreCase fix

* scala cask toUpperCase fix

* cask regenerated samples

* improved exception handling for scala cask

* File separator fix for windows

* Noob fix for cask

* regenerated api package

* Removed environment variable settings, debug code

* Updated samples

* moved scala-cask output

* Regenerated samples

* scala cask fix

* Updated scala cask settings for more typical package structure
Removed cask client samples

* cask - reran generate samples

* Removed duplicate ScalaCaskServer entry

* minor enhancements

* update samples

* update templates

---------

Co-authored-by: aaron.pritzlaff <aaron@kindservices.co.uk>
2024-04-10 18:49:59 +08:00
William Cheng
ef36ea410e Fix method naming for openapi normalzier, openapi ignore list option (#18348)
* fix openapi normalizer naming issue in config

* update openapi generator ignore list setting

* update

* fix

* update sample config

* update doc
2024-04-10 17:09:48 +08:00
William Cheng
eb506ee776 [java][native] use type reference instead to fix compilation issue in JDK11 (#18346)
* use type reference instead to fix compilation issue in jdk11

* fix
2024-04-10 11:29:51 +08:00
William Cheng
a651376b18 fix java native compilation errors 2024-04-10 02:57:41 +08:00
William Cheng
abfeb6e035 Merge branch 'master' of https://github.com/openapitools/openapi-generator 2024-04-10 02:33:15 +08:00
William Cheng
edd91063b4 hide generation timestamp in java microprofile samples 2024-04-10 02:33:01 +08:00
Ege Sucu
1a06e3e0fb [swift] Added solution for deprecated "UTTypeCopyPreferredTagWithClass" (#18330)
* Added solution for deprecated "UTTypeCopyPreferredTagWithClass"

UTTypeCopyPreferredTagWithClass is deprecated with iOS 15, so apps targeting iOS 15+ were getting this warning on any auto-generated code. This solution will solve that warning and works both iOS 15 and below.

* Project built

* macOS Related fixes applied
2024-04-09 18:20:48 +01:00
Knut Erik Langdahl
6a2ad134c6 [kotlin] Add support for modelNameMappings (#18342) 2024-04-10 01:19:52 +08:00
William Cheng
d6749f8a0e update samples 2024-04-09 20:49:23 +08:00
Joakim Holm
3cb3fc2898 Add Generated annotations to more classes (#17736) 2024-04-09 16:39:53 +08:00
Lionel Tesolin
a245e86b74 Update dataClass.mustache (#18205)
Added the missing additionalModelTypeAnnotations for the Kotlin data class generator
2024-04-09 16:25:44 +08:00
William Cheng
b2a7f435c8 "==" enum value generates "_" in Java which is invalid since Java 9 (#18338)
* #17276 "==" enum value generates "_" in Java which is invalid since Java 9

* update doc

---------

Co-authored-by: Julien BÉTI <jbeti@cosium.com>
2024-04-09 12:21:54 +08:00
Beppe Catanese
45a657f59d Deal with boolean field (#18294) 2024-04-09 11:28:48 +08:00
William Cheng
83b45fd1e8 [java][okhttp-gson] Fix oneof, anyof for array type (#18324)
* fix oneof, anyof for array type in java okhttp-gson

* fix oneof

* fix add tests

* clean up comments

* update

* add new files
2024-04-08 22:20:23 +08:00
sbilz
b2faf39ac7 Update README.md with consistend dmtech-sponsoring-link (#18329) 2024-04-08 20:41:14 +08:00
Zishun (Zack) Wei
453facc81c Fix 18271: Circular imports on AllOf generation with REFACTOR_ALLOF_WITH_PROPERTIES_ONLY=True (#18272)
* fix issue 18271

* the same update for python-pydantic-v1

* add test

* update samples

* update samples

* put properties under allOf for python client tests

* update samples

* add a test in test model
2024-04-08 19:01:01 +08:00
sbilz
2c663561ef update dmtech-sponsoring-link (#18326) 2024-04-08 18:59:01 +08:00
Michito Maeda
101b3fcc35 Removed unused file (#18325) 2024-04-08 15:44:08 +08:00
devhl-labs
79fe176ef2 fixed operation parameter handling (#18322) 2024-04-08 10:15:31 +08:00
Michael Esemplare
3f143a3b5a Fix #17768: Delegate Incorrectly generated when useOptional True (#18278)
- Update moustache dataType value to >optionalDataType section to use Optional DataType when it is a BodyParam and not reactive.
2024-04-07 23:33:00 +08:00
Taylor Becker
560089e4c7 Kotlin: Do not escape/sanitize quoted enum values (#18305) 2024-04-07 22:33:16 +08:00
Francisco Bretal
a91d8e2c57 fix: backticks are now unescaped (#18318) 2024-04-07 22:26:58 +08:00
William Cheng
494d74ab82 remove duplicated (#18320) 2024-04-07 22:25:03 +08:00
condorcorde
fbc8616a06 Fix #17740 (multipart/form-data request) and proxy behaviour (#18315)
* Support multipart requests

* Further code optimization

* Update ApiClient.ps1

* Set $Multipart

* Corrections after petstore tests

* Update api_client.mustache

* Update api_client.nustache

* Update api_client.mustache

* Tabs removed
2024-04-07 21:42:19 +08:00
Viswajith Venugopal
650e119f22 Update go-server template to include the conventional generated code line (#18304)
* Update go-server template to include the conventional generated code line

Follow the convention from https://pkg.go.dev/cmd/go#hdr-Generate_Go_files_by_processing_source.

The generated go client code already follows this: f357be480e/modules/openapi-generator/src/main/resources/go/partial_header.mustache (L18)

* gen files

* Move to top
2024-04-07 21:23:24 +08:00
William Cheng
f10a9939dd Merge remote-tracking branch 'origin/master' into timcbaoth-improve-camlization-in-default-codegen 2024-03-27 16:56:43 +08:00
William Cheng
e1b3dbc683 remove cs files 2024-03-27 16:54:41 +08:00
William Cheng
08590cb7f3 use additoinal properties appleyCamelizeFix instead 2024-03-24 23:13:29 +08:00
William Cheng
2cacac8aea another rollback option 2024-03-24 19:03:00 +08:00
William Cheng
0596817264 add system property to rollback 2024-03-24 18:52:59 +08:00
William Cheng
5a988d719f Merge branch 'improve-camlization-in-default-codegen' of https://github.com/timcbaoth/openapi-generator into timcbaoth-improve-camlization-in-default-codegen 2024-03-24 18:34:59 +08:00
Tim Selman
9714f12d5d generate samples and docs 2023-06-09 16:24:53 +02:00
Tim Selman
67a2ccc67f remove space 2023-06-09 16:12:58 +02:00
Tim Selman
a9de1ef614 Remove stale code 2023-06-09 16:12:10 +02:00
Tim Selman
cb1f2dab3a Improve overall camelization 2023-06-09 16:10:37 +02:00
Tim Selman
80b6dd933f Improve camelization in DefaultCodegen 2023-06-07 13:00:41 +02:00
1054 changed files with 21046 additions and 8284 deletions

View File

@@ -32,6 +32,7 @@ jobs:
- samples/server/petstore/scalatra
- samples/server/petstore/scala-finch # cannot be tested with jdk11
- samples/server/petstore/scala-http4s-server
- samples/server/petstore/scala-cask
steps:
- uses: actions/checkout@v4
- uses: actions/setup-java@v4

View File

@@ -61,7 +61,7 @@ If you find OpenAPI Generator useful for work, please consider asking your compa
[<img src="https://openapi-generator.tech/img/companies/bumpsh.png" width="128" height="128">](https://bump.sh/?utm_source=openapi_generator&utm_medium=github_webpage&utm_campaign=sponsor)
[<img src="https://openapi-generator.tech/img/companies/bileto.png" width="128" height="128">](https://www.bileto.com/?utm_source=openapi_generator&utm_medium=github_webpage&utm_campaign=sponsor)
[<img src="https://openapi-generator.tech/img/companies/bairesdev.png" width="128" height="128">](https://www.bairesdev.com/sponsoring-open-source-projects/?utm_source=openapi_generator&utm_medium=github_webpage&utm_campaign=sponsor)
[<img src="https://openapi-generator.tech/img/companies/dmtech.jpeg" width="128" height="128">](https://www.dm-jobs.com/?utm_source=openapi_generator&utm_medium=github_webpage&utm_campaign=sponsor)
[<img src="https://openapi-generator.tech/img/companies/dmtech.jpeg" width="128" height="128">](https://www.dmtech.de/?utm_source=openapi_generator&utm_medium=github_webpage&utm_campaign=sponsor)
[<img src="https://openapi-generator.tech/img/companies/adyen.png" width="128" height="128">](https://adyen.com/?utm_source=openapi_generator&utm_medium=github_webpage&utm_campaign=sponsor)
[<img src="https://openapi-generator.tech/img/companies/fornex.png" width="128" height="128">](https://fornex.com/?utm_source=openapi_generator&utm_medium=github_webpage&utm_campaign=sponsor)
[<img src="https://openapi-generator.tech/img/companies/alloyautomation.png" width="128" height="128">](https://runalloy.com/signup?utm_source=github&utm_medium=referral&utm_campaign=1524_openapigenerator)
@@ -85,7 +85,7 @@ OpenAPI Generator allows generation of API client libraries (SDK generation), se
| | Languages/Frameworks |
| -------------------------------- |-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| **API clients** | **ActionScript**, **Ada**, **Apex**, **Bash**, **C**, **C#** (.net 2.0, 3.5 or later, .NET Standard 1.3 - 2.1, .NET Core 3.1, .NET 5.0. Libraries: RestSharp, GenericHost, HttpClient), **C++** (Arduino, cpp-restsdk, Qt5, Tizen, Unreal Engine 4), **Clojure**, **Crystal**, **Dart**, **Elixir**, **Elm**, **Eiffel**, **Erlang**, **Go**, **Groovy**, **Haskell** (http-client, Servant), **Java** (Apache HttpClient 4.x, Apache HttpClient 5.x, Jersey2.x, OkHttp, Retrofit1.x, Retrofit2.x, Feign, RestTemplate, RESTEasy, Vertx, Google API Client Library for Java, Rest-assured, Spring 5 Web Client, MicroProfile Rest Client, Helidon), **Jetbrains HTTP Client**, **Julia**, **k6**, **Kotlin**, **Lua**, **N4JS**, **Nim**, **Node.js/JavaScript** (ES5, ES6, AngularJS with Google Closure Compiler annotations, Flow types, Apollo GraphQL DataStore), **Objective-C**, **OCaml**, **Perl**, **PHP**, **PowerShell**, **Python**, **R**, **Ruby**, **Rust** (hyper, reqwest, rust-server), **Scala** (akka, http4s, scalaz, sttp, swagger-async-httpclient, pekko), **Swift** (2.x, 3.x, 4.x, 5.x), **Typescript** (AngularJS, Angular (9.x - 17.x), Aurelia, Axios, Fetch, Inversify, jQuery, Nestjs, Node, redux-query, Rxjs), **XoJo**, **Zapier** |
| **Server stubs** | **Ada**, **C#** (ASP.NET Core, Azure Functions), **C++** (Pistache, Restbed, Qt5 QHTTPEngine), **Erlang**, **F#** (Giraffe), **Go** (net/http, Gin, Echo), **Haskell** (Servant, Yesod), **Java** (MSF4J, Spring, Undertow, JAX-RS: CDI, CXF, Inflector, Jersey, RestEasy, Play Framework, [PKMST](https://github.com/ProKarma-Inc/pkmst-getting-started-examples), [Vert.x](https://vertx.io/), [Apache Camel](https://camel.apache.org/), [Helidon](https://helidon.io/)), **Julia**, **Kotlin** (Spring Boot, [Ktor](https://github.com/ktorio/ktor), [Vert.x](https://vertx.io/)), **PHP** (Laravel, Lumen, [Mezzio (fka Zend Expressive)](https://github.com/mezzio/mezzio), Slim, Silex, [Symfony](https://symfony.com/)), **Python** (FastAPI, Flask), **NodeJS**, **Ruby** (Sinatra, Rails5), **Rust** ([rust-server](https://openapi-generator.tech/docs/generators/rust-server/)), **Scala** (Akka, [Finch](https://github.com/finagle/finch), [Lagom](https://github.com/lagom/lagom), [Play](https://www.playframework.com/), Scalatra) |
| **Server stubs** | **Ada**, **C#** (ASP.NET Core, Azure Functions), **C++** (Pistache, Restbed, Qt5 QHTTPEngine), **Erlang**, **F#** (Giraffe), **Go** (net/http, Gin, Echo), **Haskell** (Servant, Yesod), **Java** (MSF4J, Spring, Undertow, JAX-RS: CDI, CXF, Inflector, Jersey, RestEasy, Play Framework, [PKMST](https://github.com/ProKarma-Inc/pkmst-getting-started-examples), [Vert.x](https://vertx.io/), [Apache Camel](https://camel.apache.org/), [Helidon](https://helidon.io/)), **Julia**, **Kotlin** (Spring Boot, [Ktor](https://github.com/ktorio/ktor), [Vert.x](https://vertx.io/)), **PHP** (Laravel, Lumen, [Mezzio (fka Zend Expressive)](https://github.com/mezzio/mezzio), Slim, Silex, [Symfony](https://symfony.com/)), **Python** (FastAPI, Flask), **NodeJS**, **Ruby** (Sinatra, Rails5), **Rust** ([rust-server](https://openapi-generator.tech/docs/generators/rust-server/)), **Scala** (Akka, [Finch](https://github.com/finagle/finch), [Lagom](https://github.com/lagom/lagom), [Play](https://www.playframework.com/), [Cask](https://github.com/com-lihaoyi/cask), Scalatra) |
| **API documentation generators** | **HTML**, **Confluence Wiki**, **Asciidoc**, **Markdown**, **PlantUML** |
| **Configuration files** | [**Apache2**](https://httpd.apache.org/) |
| **Others** | **GraphQL**, **JMeter**, **Ktorm**, **MySQL Schema**, **Postman Collection**, **Protocol Buffer**, **WSDL** |
@@ -1102,6 +1102,7 @@ Here is a list of template creators:
* Ruby on Rails 5: @zlx
* Rust (rust-server): @metaswitch
* Scala Akka: @Bouillie
* Scala Cask: @aaronp
* Scala Finch: @jimschubert [:heart:](https://www.patreon.com/jimschubert)
* Scala Lagom: @gmkumar2005
* Scala Play: @adigerber

View File

@@ -8,4 +8,5 @@ additionalProperties:
serializationLibrary: jackson
artifactId: microprofile-rest-client-3-jackson-with-xml
configKey: petstore
microprofileRestClientVersion: "3.0"
microprofileRestClientVersion: "3.0"
hideGenerationTimestamp: true

View File

@@ -7,4 +7,5 @@ additionalProperties:
serializationLibrary: jackson
artifactId: microprofile-rest-client-3-jackson
configKey: petstore
microprofileRestClientVersion: "3.0"
microprofileRestClientVersion: "3.0"
hideGenerationTimestamp: true

View File

@@ -9,4 +9,5 @@ additionalProperties:
useOneOfDiscriminatorLookup: "true"
disallowAdditionalPropertiesIfNotPresent: false
annotationLibrary: "swagger1"
openapiNormalizer:
SET_TAGS_FOR_ALL_OPERATIONS: common

View File

@@ -12,4 +12,4 @@ additionalProperties:
enumPropertyNaming: UPPERCASE
serializationLibrary: gson
openapiNormalizer:
SIMPLIFY_ONEOF_ANYOF=false
SIMPLIFY_ONEOF_ANYOF: false

View File

@@ -12,4 +12,4 @@ additionalProperties:
enumPropertyNaming: UPPERCASE
serializationLibrary: gson
openapiNormalizer:
SIMPLIFY_ONEOF_ANYOF=false
SIMPLIFY_ONEOF_ANYOF: false

View File

@@ -0,0 +1,13 @@
generatorName: scala-cask
outputDir: samples/server/petstore/scala-cask
inputSpec: modules/openapi-generator/src/test/resources/3_0/petstore.yaml
templateDir: modules/openapi-generator/src/main/resources/scala-cask
additionalProperties:
hideGenerationTimestamp: "true"
artifactId: scala-cask-petstore
groupId: "cask.groupId"
package: "sample.cask"
modelPackage: "sample.cask.model"
apiPackage: "sample.cask.api"
gitRepoId: "sample-cask-repo"
gitUserId: "sample-cask-user"

View File

@@ -10,7 +10,7 @@
- filename: "samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/ClientTest.java"
sha256: db505f7801fef62c13a08a8e9ca1fc4c5c947ab46b46f12943139d353feacf17
- filename: "samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/JSONTest.java"
sha256: c479b587cf0d51fa550eb81d33b277081807b87dc28649027d1164224c25ad0a
sha256: 8210bdaf06aae8dc46521515a8a0ef10e48c980fadd3efd95313e6c806f409c2
- filename: "samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/api/PetApiTest.java"
sha256: 0d64cdc11809a7b5b952ccdad2bd91bd0045b3894d6fabf3e368fa0be12b8217
- filename: "samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/model/PetTest.java"

View File

@@ -304,6 +304,8 @@ You can use also `config.yml` with following equivalent example:
apiPackage: "petstore"
```
Another example of config file can be found in [modules/openapi-generator/src/test/resources/sampleConfig.json](https://github.com/OpenAPITools/openapi-generator/blob/master/modules/openapi-generator/src/test/resources/sampleConfig.json)
Supported config options can be different per language. Running `config-help -g {lang}` will show available options.
**These options are applied via configuration file (e.g. config.json or config.yml) or by passing them with `-p {optionName}={optionValue}`**. (If `-p {optionName}` does not work, please open a [ticket](https://github.com/openapitools/openapi-generator/issues/new) and we'll look into it)

View File

@@ -134,6 +134,7 @@ The following generators are available:
* [rust-axum (beta)](generators/rust-axum.md)
* [rust-server](generators/rust-server.md)
* [scala-akka-http-server (beta)](generators/scala-akka-http-server.md)
* [scala-cask](generators/scala-cask.md)
* [scala-finch](generators/scala-finch.md)
* [scala-http4s-server](generators/scala-http4s-server.md)
* [scala-lagom-server](generators/scala-lagom-server.md)

View File

@@ -135,6 +135,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl
## RESERVED WORDS
<ul class="column-ul">
<li>_</li>
<li>abstract</li>
<li>apiclient</li>
<li>apiexception</li>

View File

@@ -174,6 +174,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl
## RESERVED WORDS
<ul class="column-ul">
<li>_</li>
<li>abstract</li>
<li>apiclient</li>
<li>apiexception</li>

View File

@@ -128,6 +128,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl
## RESERVED WORDS
<ul class="column-ul">
<li>_</li>
<li>abstract</li>
<li>apiclient</li>
<li>apiexception</li>

View File

@@ -130,6 +130,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl
## RESERVED WORDS
<ul class="column-ul">
<li>_</li>
<li>abstract</li>
<li>apiclient</li>
<li>apiexception</li>

View File

@@ -132,6 +132,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl
## RESERVED WORDS
<ul class="column-ul">
<li>_</li>
<li>abstract</li>
<li>apiclient</li>
<li>apiexception</li>

View File

@@ -153,6 +153,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl
## RESERVED WORDS
<ul class="column-ul">
<li>_</li>
<li>abstract</li>
<li>apiclient</li>
<li>apiexception</li>

View File

@@ -153,6 +153,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl
## RESERVED WORDS
<ul class="column-ul">
<li>_</li>
<li>abstract</li>
<li>apiclient</li>
<li>apiexception</li>

View File

@@ -138,6 +138,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl
## RESERVED WORDS
<ul class="column-ul">
<li>_</li>
<li>abstract</li>
<li>apiclient</li>
<li>apiexception</li>

View File

@@ -139,6 +139,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl
## RESERVED WORDS
<ul class="column-ul">
<li>_</li>
<li>abstract</li>
<li>apiclient</li>
<li>apiexception</li>

View File

@@ -142,6 +142,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl
## RESERVED WORDS
<ul class="column-ul">
<li>_</li>
<li>abstract</li>
<li>apiclient</li>
<li>apiexception</li>

View File

@@ -132,6 +132,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl
## RESERVED WORDS
<ul class="column-ul">
<li>_</li>
<li>abstract</li>
<li>apiclient</li>
<li>apiexception</li>

View File

@@ -132,6 +132,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl
## RESERVED WORDS
<ul class="column-ul">
<li>_</li>
<li>abstract</li>
<li>apiclient</li>
<li>apiexception</li>

View File

@@ -135,6 +135,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl
## RESERVED WORDS
<ul class="column-ul">
<li>_</li>
<li>abstract</li>
<li>apiclient</li>
<li>apiexception</li>

View File

@@ -132,6 +132,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl
## RESERVED WORDS
<ul class="column-ul">
<li>_</li>
<li>abstract</li>
<li>apiclient</li>
<li>apiexception</li>

View File

@@ -164,6 +164,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl
## RESERVED WORDS
<ul class="column-ul">
<li>_</li>
<li>abstract</li>
<li>apiclient</li>
<li>apiexception</li>

View File

@@ -146,6 +146,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl
## RESERVED WORDS
<ul class="column-ul">
<li>_</li>
<li>abstract</li>
<li>apiclient</li>
<li>apiexception</li>

View File

@@ -137,6 +137,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl
## RESERVED WORDS
<ul class="column-ul">
<li>_</li>
<li>abstract</li>
<li>apiclient</li>
<li>apiexception</li>

View File

@@ -160,6 +160,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl
## RESERVED WORDS
<ul class="column-ul">
<li>_</li>
<li>abstract</li>
<li>apiclient</li>
<li>apiexception</li>

View File

@@ -155,6 +155,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl
## RESERVED WORDS
<ul class="column-ul">
<li>_</li>
<li>abstract</li>
<li>apiclient</li>
<li>apiexception</li>

View File

@@ -138,6 +138,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl
## RESERVED WORDS
<ul class="column-ul">
<li>_</li>
<li>abstract</li>
<li>apiclient</li>
<li>apiexception</li>

View File

@@ -139,6 +139,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl
## RESERVED WORDS
<ul class="column-ul">
<li>_</li>
<li>abstract</li>
<li>apiclient</li>
<li>apiexception</li>

View File

@@ -138,6 +138,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl
## RESERVED WORDS
<ul class="column-ul">
<li>_</li>
<li>abstract</li>
<li>apiclient</li>
<li>apiexception</li>

View File

@@ -146,6 +146,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl
## RESERVED WORDS
<ul class="column-ul">
<li>_</li>
<li>abstract</li>
<li>apiclient</li>
<li>apiexception</li>

View File

@@ -0,0 +1,261 @@
---
title: Documentation for the scala-cask Generator
---
## METADATA
| Property | Value | Notes |
| -------- | ----- | ----- |
| generator name | scala-cask | pass this to the generate command after -g |
| generator stability | STABLE | |
| generator type | SERVER | |
| generator language | Scala | |
| generator default templating engine | mustache | |
| helpTxt | Generates a scala-cask server. | |
## CONFIG OPTIONS
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 |
| ------ | ----------- | ------ | ------- |
|allowUnicodeIdentifiers|boolean, toggles whether unicode identifiers are allowed in names or not, default is false| |false|
|apiPackage|package for generated api classes| |null|
|artifactId|artifactId in generated pom.xml. This also becomes part of the generated library's filename| |null|
|dateLibrary|Option. Date library to use|<dl><dt>**joda**</dt><dd>Joda (for legacy app)</dd><dt>**java8**</dt><dd>Java 8 native JSR310 (preferred for JDK 1.8+)</dd></dl>|java8|
|disallowAdditionalPropertiesIfNotPresent|If false, the 'additionalProperties' implementation (set to true by default) is compliant with the OAS and JSON schema specifications. If true (default), keep the old (incorrect) behaviour that 'additionalProperties' is set to false by default.|<dl><dt>**false**</dt><dd>The 'additionalProperties' implementation is compliant with the OAS and JSON schema specifications.</dd><dt>**true**</dt><dd>Keep the old (incorrect) behaviour that 'additionalProperties' is set to false by default.</dd></dl>|true|
|ensureUniqueParams|Whether to ensure parameter names are unique in an operation (rename parameters that are not).| |true|
|enumUnknownDefaultCase|If the server adds new enum cases, that are unknown by an old spec/client, the client will fail to parse the network response.With this option enabled, each enum will have a new case, 'unknown_default_open_api', so that when the server sends an enum case that is not known by the client/spec, they can safely fallback to this case.|<dl><dt>**false**</dt><dd>No changes to the enum's are made, this is the default option.</dd><dt>**true**</dt><dd>With this option enabled, each enum will have a new case, 'unknown_default_open_api', so that when the enum case sent by the server is not known by the client/spec, can safely be decoded to this case.</dd></dl>|false|
|gitRepoId|Git repo ID, e.g. openapi-generator.| |null|
|gitUserId|Git user ID, e.g. openapitools.| |null|
|groupId|groupId in generated pom.xml| |null|
|legacyDiscriminatorBehavior|Set to false for generators with better support for discriminators. (Python, Java, Go, PowerShell, C# have this enabled by default).|<dl><dt>**true**</dt><dd>The mapping in the discriminator includes descendent schemas that allOf inherit from self and the discriminator mapping schemas in the OAS document.</dd><dt>**false**</dt><dd>The mapping in the discriminator includes any descendent schemas that allOf inherit from self, any oneOf schemas, any anyOf schemas, any x-discriminator-values, and the discriminator mapping schemas in the OAS document AND Codegen validates that oneOf and anyOf schemas contain the required discriminator and throws an error if the discriminator is missing.</dd></dl>|true|
|modelPackage|package for generated models| |null|
|modelPropertyNaming|Naming convention for the property: 'camelCase', 'PascalCase', 'snake_case' and 'original', which keeps the original name| |camelCase|
|packageName|packageDescription| |null|
|prependFormOrBodyParameters|Add form or body parameters to the beginning of the parameter list.| |false|
|sortModelPropertiesByRequiredFlag|Sort model properties to place required parameters before optional parameters.| |true|
|sortParamsByRequiredFlag|Sort method arguments to place required parameters before optional parameters.| |true|
|sourceFolder|source folder for generated code| |null|
## IMPORT MAPPING
| Type/Alias | Imports |
| ---------- | ------- |
|Array|java.util.List|
|ArrayList|java.util.ArrayList|
|Date|java.util.Date|
|DateTime|org.joda.time.*|
|File|java.io.File|
|HashMap|java.util.HashMap|
|ListBuffer|scala.collection.mutable.ListBuffer|
|ListSet|scala.collection.immutable.ListSet|
|LocalDate|org.joda.time.*|
|LocalDateTime|org.joda.time.*|
|LocalTime|org.joda.time.*|
|Seq|scala.collection.immutable.Seq|
|Set|scala.collection.immutable.Set|
|Timestamp|java.sql.Timestamp|
|URI|java.net.URI|
|UUID|java.util.UUID|
## INSTANTIATION TYPES
| Type/Alias | Instantiated By |
| ---------- | --------------- |
|set|Set|
## LANGUAGE PRIMITIVES
<ul class="column-ul">
<li>Any</li>
<li>Array</li>
<li>Boolean</li>
<li>Byte</li>
<li>Double</li>
<li>Float</li>
<li>Int</li>
<li>List</li>
<li>Long</li>
<li>Map</li>
<li>Object</li>
<li>Seq</li>
<li>String</li>
<li>boolean</li>
</ul>
## RESERVED WORDS
<ul class="column-ul">
<li>abstract</li>
<li>assert</li>
<li>boolean</li>
<li>break</li>
<li>byte</li>
<li>case</li>
<li>catch</li>
<li>char</li>
<li>class</li>
<li>const</li>
<li>continue</li>
<li>default</li>
<li>do</li>
<li>double</li>
<li>else</li>
<li>enum</li>
<li>extends</li>
<li>final</li>
<li>finally</li>
<li>float</li>
<li>for</li>
<li>goto</li>
<li>if</li>
<li>implements</li>
<li>import</li>
<li>instanceof</li>
<li>int</li>
<li>interface</li>
<li>long</li>
<li>native</li>
<li>new</li>
<li>package</li>
<li>private</li>
<li>protected</li>
<li>public</li>
<li>return</li>
<li>short</li>
<li>static</li>
<li>strictfp</li>
<li>super</li>
<li>switch</li>
<li>synchronized</li>
<li>this</li>
<li>throw</li>
<li>throws</li>
<li>transient</li>
<li>try</li>
<li>type</li>
<li>void</li>
<li>volatile</li>
<li>while</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
|Uuid|✗|
|Array|✓|OAS2,OAS3
|Null|✗|OAS3
|AnyType|✗|OAS2,OAS3
|Object|✓|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
|allOf|✗|OAS2,OAS3
|anyOf|✗|OAS3
|oneOf|✗|OAS3
|not|✗|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
|SignatureAuth|✗|OAS3
|AWSV4Signature|✗|ToolingExtension
### Wire Format Feature
| Name | Supported | Defined By |
| ---- | --------- | ---------- |
|JSON|✓|OAS2,OAS3
|XML|✓|OAS2,OAS3
|PROTOBUF|✗|ToolingExtension
|Custom|✗|OAS2,OAS3

View File

@@ -167,6 +167,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl
## RESERVED WORDS
<ul class="column-ul">
<li>_</li>
<li>abstract</li>
<li>apiclient</li>
<li>apiexception</li>

View File

@@ -515,11 +515,11 @@ public class Generate extends OpenApiGeneratorCommand {
applyModelNameMappingsKvpList(modelNameMappings, configurator);
applyEnumNameMappingsKvpList(enumNameMappings, configurator);
applyOperationIdNameMappingsKvpList(operationIdNameMappings, configurator);
applyOpenAPINormalizerKvpList(openapiNormalizer, configurator);
applyOpenapiNormalizerKvpList(openapiNormalizer, configurator);
applyTypeMappingsKvpList(typeMappings, configurator);
applyAdditionalPropertiesKvpList(additionalProperties, configurator);
applyLanguageSpecificPrimitivesCsvList(languageSpecificPrimitives, configurator);
applyOpenAPIGeneratorIgnoreListCsvList(openapiGeneratorIgnoreList, configurator);
applyOpenapiGeneratorIgnoreListCsvList(openapiGeneratorIgnoreList, configurator);
applyReservedWordsMappingsKvpList(reservedWordsMappings, configurator);
applyServerVariablesKvpList(serverVariableOverrides, configurator);

View File

@@ -321,7 +321,7 @@ public final class GeneratorSettings implements Serializable {
*
* @return a map of rules
*/
public Map<String, String> getOpenAPINormalizer() {
public Map<String, String> getOpenapiNormalizer() {
return openapiNormalizer;
}
@@ -346,7 +346,7 @@ public final class GeneratorSettings implements Serializable {
*
* @return the openapi generator ignore list
*/
public Set<String> getOpenAPIGeneratorIgnoreList() {
public Set<String> getOpenapiGeneratorIgnoreList() {
return openapiGeneratorIgnoreList;
}
@@ -614,14 +614,14 @@ public final class GeneratorSettings implements Serializable {
if (copy.getOperationIdNameMappings() != null) {
builder.operationIdNameMappings.putAll(copy.getOperationIdNameMappings());
}
if (copy.getOpenAPINormalizer() != null) {
builder.openapiNormalizer.putAll(copy.getOpenAPINormalizer());
if (copy.getOpenapiNormalizer() != null) {
builder.openapiNormalizer.putAll(copy.getOpenapiNormalizer());
}
if (copy.getLanguageSpecificPrimitives() != null) {
builder.languageSpecificPrimitives.addAll(copy.getLanguageSpecificPrimitives());
}
if (copy.getOpenAPIGeneratorIgnoreList() != null) {
builder.openapiGeneratorIgnoreList.addAll(copy.getOpenAPIGeneratorIgnoreList());
if (copy.getOpenapiGeneratorIgnoreList() != null) {
builder.openapiGeneratorIgnoreList.addAll(copy.getOpenapiGeneratorIgnoreList());
}
if (copy.getReservedWordsMappings() != null) {
builder.reservedWordsMappings.putAll(copy.getReservedWordsMappings());
@@ -1152,7 +1152,7 @@ public final class GeneratorSettings implements Serializable {
* @param openapiNormalizer the {@code openapiNormalizer} to set
* @return a reference to this Builder
*/
public Builder withOpenAPINormalizer(Map<String, String> openapiNormalizer) {
public Builder withOpenapiNormalizer(Map<String, String> openapiNormalizer) {
this.openapiNormalizer = openapiNormalizer;
return this;
}
@@ -1164,7 +1164,7 @@ public final class GeneratorSettings implements Serializable {
* @param value The value of the OpenAPI normalizer rule
* @return a reference to this Builder
*/
public Builder withOpenAPINormalizer(String key, String value) {
public Builder withOpenapiNormalizer(String key, String value) {
if (this.openapiNormalizer == null) {
this.openapiNormalizer = new HashMap<>();
}
@@ -1203,7 +1203,7 @@ public final class GeneratorSettings implements Serializable {
* @param openapiGeneratorIgnoreList the {@code openapiGeneratorIgnoreList} to set
* @return a reference to this Builder
*/
public Builder withOpenAPIGeneratorIgnoreList(Set<String> openapiGeneratorIgnoreList) {
public Builder withOpenapiGeneratorIgnoreList(Set<String> openapiGeneratorIgnoreList) {
this.openapiGeneratorIgnoreList = openapiGeneratorIgnoreList;
return this;
}
@@ -1214,7 +1214,7 @@ public final class GeneratorSettings implements Serializable {
* @param value The value of entry to set
* @return a reference to this Builder
*/
public Builder withOpenAPIGeneratorIgnoreList(String value) {
public Builder withOpenapiGeneratorIgnoreList(String value) {
if (this.openapiGeneratorIgnoreList == null) {
this.openapiGeneratorIgnoreList = new HashSet<>();
}
@@ -1390,9 +1390,9 @@ public final class GeneratorSettings implements Serializable {
Objects.equals(getModelNameMappings(), that.getModelNameMappings()) &&
Objects.equals(getEnumNameMappings(), that.getEnumNameMappings()) &&
Objects.equals(getOperationIdNameMappings(), that.getOperationIdNameMappings()) &&
Objects.equals(getOpenAPINormalizer(), that.getOpenAPINormalizer()) &&
Objects.equals(getOpenapiNormalizer(), that.getOpenapiNormalizer()) &&
Objects.equals(getLanguageSpecificPrimitives(), that.getLanguageSpecificPrimitives()) &&
Objects.equals(getOpenAPIGeneratorIgnoreList(), that.getOpenAPIGeneratorIgnoreList()) &&
Objects.equals(getOpenapiGeneratorIgnoreList(), that.getOpenapiGeneratorIgnoreList()) &&
Objects.equals(getReservedWordsMappings(), that.getReservedWordsMappings()) &&
Objects.equals(getGitHost(), that.getGitHost()) &&
Objects.equals(getGitUserId(), that.getGitUserId()) &&
@@ -1428,9 +1428,9 @@ public final class GeneratorSettings implements Serializable {
getModelNameMappings(),
getEnumNameMappings(),
getOperationIdNameMappings(),
getOpenAPINormalizer(),
getOpenapiNormalizer(),
getLanguageSpecificPrimitives(),
getOpenAPIGeneratorIgnoreList(),
getOpenapiGeneratorIgnoreList(),
getReservedWordsMappings(),
getGitHost(),
getGitUserId(),

View File

@@ -887,7 +887,7 @@ open class GenerateTask @Inject constructor(private val objectFactory: ObjectFac
if (openapiNormalizer.isPresent) {
openapiNormalizer.get().forEach { entry ->
configurator.addOpenAPINormalizer(entry.key, entry.value)
configurator.addOpenapiNormalizer(entry.key, entry.value)
}
}
@@ -917,7 +917,7 @@ open class GenerateTask @Inject constructor(private val objectFactory: ObjectFac
if (openapiGeneratorIgnoreList.isPresent) {
openapiGeneratorIgnoreList.get().forEach {
configurator.addOpenAPIGeneratorIgnoreList(it)
configurator.addOpenapiGeneratorIgnoreList(it)
}
}

View File

@@ -829,7 +829,7 @@ public class CodeGenMojo extends AbstractMojo {
// Retained for backwards-compatibility with configOptions -> openapi-normalizer
if (openapiNormalizer == null && configOptions.containsKey("openapi-normalizer")) {
applyOpenAPINormalizerKvp(configOptions.get("openapi-normalizer").toString(),
applyOpenapiNormalizerKvp(configOptions.get("openapi-normalizer").toString(),
configurator);
}
@@ -846,7 +846,7 @@ public class CodeGenMojo extends AbstractMojo {
// Retained for backwards-compatibility with configOptions -> openapi-generator-ignore-list
if (openapiGeneratorIgnoreList == null && configOptions.containsKey("openapi-generator-ignore-list")) {
applyOpenAPIGeneratorIgnoreListCsv(configOptions
applyOpenapiGeneratorIgnoreListCsv(configOptions
.get("openapi-generator-ignore-list").toString(), configurator);
}
@@ -919,7 +919,7 @@ public class CodeGenMojo extends AbstractMojo {
// Apply OpenAPI normalizer rules
if (openapiNormalizer != null && (configOptions == null || !configOptions.containsKey("openapi-normalizer"))) {
applyOpenAPINormalizerKvpList(openapiNormalizer, configurator);
applyOpenapiNormalizerKvpList(openapiNormalizer, configurator);
}
// Apply Type Mappings
@@ -936,7 +936,7 @@ public class CodeGenMojo extends AbstractMojo {
// Apply Language Specific Primitives
if (openapiGeneratorIgnoreList != null
&& (configOptions == null || !configOptions.containsKey("openapi-generator-ignore-list"))) {
applyOpenAPIGeneratorIgnoreListCsvList(openapiGeneratorIgnoreList, configurator);
applyOpenapiGeneratorIgnoreListCsvList(openapiGeneratorIgnoreList, configurator);
}
// Apply Additional Properties

View File

@@ -358,8 +358,7 @@ public interface CodegenConfig {
boolean getAddSuffixToDuplicateOperationNicknames();
boolean getUseOpenAPINormalizer();
Set<String> getOpenAPIGeneratorIgnoreList();
boolean getUseOpenapiNormalizer();
Set<String> getOpenapiGeneratorIgnoreList();
}

View File

@@ -52,7 +52,6 @@ import org.openapitools.codegen.api.TemplatingEngineAdapter;
import org.openapitools.codegen.config.GlobalSettings;
import org.openapitools.codegen.examples.ExampleGenerator;
import org.openapitools.codegen.languages.PhpNextgenClientCodegen;
import org.openapitools.codegen.languages.RustAxumServerCodegen;
import org.openapitools.codegen.languages.RustServerCodegen;
import org.openapitools.codegen.meta.FeatureSet;
import org.openapitools.codegen.meta.GeneratorMetadata;
@@ -707,7 +706,7 @@ public class DefaultCodegen implements CodegenConfig {
* Removes importToRemove from the imports of objs, if present.
* This is useful to remove imports that are already present in operations-related template files, to avoid importing the same thing twice.
*
* @param objs imports will be removed from this objs' imports collection
* @param objs imports will be removed from this objs' imports collection
* @param importToRemove the import statement to be removed
*/
protected void removeImport(OperationsMap objs, String importToRemove) {
@@ -2302,7 +2301,7 @@ public class DefaultCodegen implements CodegenConfig {
* Any non-null value will cause {{#defaultValue} check to pass.
*
* @param codegenProperty Codegen Property
* @param schema Parameter schema
* @param schema Parameter schema
* @return string presentation of the default value of the parameter
*/
public String toDefaultParameterValue(CodegenProperty codegenProperty, Schema<?> schema) {
@@ -2329,7 +2328,7 @@ public class DefaultCodegen implements CodegenConfig {
* Return null if you do NOT want a default value.
* Any non-null value will cause {{#defaultValue} check to pass.
*
* @param schema Property schema
* @param schema Property schema
* @param codegenProperty Codegen property
* @return string presentation of the default value of the property
*/
@@ -2372,7 +2371,6 @@ public class DefaultCodegen implements CodegenConfig {
}
protected Schema<?> getSchemaAdditionalProperties(Schema schema) {
Schema<?> inner = ModelUtils.getAdditionalProperties(schema);
if (inner == null) {
@@ -3009,6 +3007,7 @@ public class DefaultCodegen implements CodegenConfig {
/**
* A method that allows generators to pre-process test example payloads
* This can be useful if one needs to change how values like null in string are represented
*
* @param data the test data payload
* @return the updated test data payload
*/
@@ -3019,6 +3018,7 @@ public class DefaultCodegen implements CodegenConfig {
/**
* Processes any test cases if they exist in the components.x-test-examples vendor extensions
* If they exist then cast them to java class instances and return them back in a map
*
* @param refToTestCases the component schema name that the test cases are for
*/
private HashMap<String, SchemaTestCase> extractSchemaTestCases(String refToTestCases) {
@@ -3055,7 +3055,7 @@ public class DefaultCodegen implements CodegenConfig {
/**
* Sets the booleans that define the model's type
*
* @param model the model to update
* @param model the model to update
* @param schema the model's schema
*/
protected void updateModelForString(CodegenModel model, Schema schema) {
@@ -3313,7 +3313,6 @@ public class DefaultCodegen implements CodegenConfig {
* @param sc The Schema that may contain the discriminator
* @param discPropName The String that is the discriminator propertyName in the schema
* @param visitedSchemas A set of visited schema names
*
*/
private CodegenProperty discriminatorFound(String composedSchemaName, Schema sc, String discPropName, Set<String> visitedSchemas) {
if (visitedSchemas.contains(composedSchemaName)) { // recursive schema definition found
@@ -3400,7 +3399,7 @@ public class DefaultCodegen implements CodegenConfig {
/**
* Recursively look in Schema sc for the discriminator and return it
*
* @param sc The Schema that may contain the discriminator
* @param sc The Schema that may contain the discriminator
* @param visitedSchemas An array list of visited schemas
*/
private Discriminator recursiveGetDiscriminator(Schema sc, ArrayList<Schema> visitedSchemas) {
@@ -3620,9 +3619,9 @@ public class DefaultCodegen implements CodegenConfig {
Map<String, Object> vendorExtensions = cs.getExtensions();
String mappingName =
Optional.ofNullable(vendorExtensions)
.map(ve -> ve.get("x-discriminator-value"))
.map(discriminatorValue -> (String) discriminatorValue)
.orElse(currentSchemaName);
.map(ve -> ve.get("x-discriminator-value"))
.map(discriminatorValue -> (String) discriminatorValue)
.orElse(currentSchemaName);
MappedModel mm = new MappedModel(mappingName, toModelName(currentSchemaName), !mappingName.equals(currentSchemaName));
descendentSchemas.add(mm);
}
@@ -3649,11 +3648,11 @@ public class DefaultCodegen implements CodegenConfig {
// the future..
String propertyType =
Optional.ofNullable(schema.getProperties())
.map(p -> (Schema<?>) p.get(discriminatorPropertyName))
.map(Schema::get$ref)
.map(ModelUtils::getSimpleRef)
.map(this::toModelName)
.orElseGet(() -> typeMapping.get("string"));
.map(p -> (Schema<?>) p.get(discriminatorPropertyName))
.map(Schema::get$ref)
.map(ModelUtils::getSimpleRef)
.map(this::toModelName)
.orElseGet(() -> typeMapping.get("string"));
discriminator.setPropertyType(propertyType);
// check to see if the discriminator property is an enum string
@@ -3944,8 +3943,8 @@ public class DefaultCodegen implements CodegenConfig {
* This method was kept when required was added to the fromProperty signature
* to ensure that the change was non-breaking
*
* @param name name of the property
* @param p OAS property schema
* @param name name of the property
* @param p OAS property schema
* @return Codegen Property object
*/
public CodegenProperty fromProperty(String name, Schema p) {
@@ -3961,9 +3960,9 @@ public class DefaultCodegen implements CodegenConfig {
* Any subsequent processing of the CodegenModel return value must be idempotent
* for a given (String name, Schema schema).
*
* @param name name of the property
* @param p OAS property schema
* @param required true if the property is required in the next higher object schema, false otherwise
* @param name name of the property
* @param p OAS property schema
* @param required true if the property is required in the next higher object schema, false otherwise
* @param schemaIsFromAdditionalProperties true if the property is a required property defined by additional properties schema
* If this is the actual additionalProperties schema not defining a required property, then
* the value should be false
@@ -4742,7 +4741,7 @@ public class DefaultCodegen implements CodegenConfig {
if (contentType != null) {
contentType = contentType.toLowerCase(Locale.ROOT);
}
if (!(this instanceof RustAxumServerCodegen) && contentType != null &&
if (contentType != null &&
(contentType.startsWith("application/x-www-form-urlencoded") ||
contentType.startsWith("multipart"))) {
// process form parameters
@@ -5909,10 +5908,10 @@ public class DefaultCodegen implements CodegenConfig {
/**
* Add the model name of the child schema in a composed schema to the set of imports
*
* @param composed composed schema
* @param composed composed schema
* @param childSchema composed schema
* @param model codegen model
* @param modelName model name
* @param model codegen model
* @param modelName model name
*/
protected void addImport(Schema composed, Schema childSchema, CodegenModel model, String modelName) {
if (composed == null || childSchema == null) {
@@ -6795,12 +6794,12 @@ public class DefaultCodegen implements CodegenConfig {
String enumValue = isDataTypeString(dataType)
? enumUnknownDefaultCaseName
: // This is a dummy value that attempts to avoid collisions with previously specified cases.
// Int.max / 192
// The number 192 that is used to calculate this random value, is the Swift Evolution proposal for frozen/non-frozen enums.
// [SE-0192](https://github.com/apple/swift-evolution/blob/master/proposals/0192-non-exhaustive-enums.md)
// Since this functionality was born in the Swift 5 generator and latter on broth to all generators
// https://github.com/OpenAPITools/openapi-generator/pull/11013
String.valueOf(11184809);
// Int.max / 192
// The number 192 that is used to calculate this random value, is the Swift Evolution proposal for frozen/non-frozen enums.
// [SE-0192](https://github.com/apple/swift-evolution/blob/master/proposals/0192-non-exhaustive-enums.md)
// Since this functionality was born in the Swift 5 generator and latter on broth to all generators
// https://github.com/OpenAPITools/openapi-generator/pull/11013
String.valueOf(11184809);
enumVar.put("name", toEnumVarName(enumName, dataType));
enumVar.put("value", toEnumValue(enumValue, dataType));
@@ -7984,6 +7983,7 @@ public class DefaultCodegen implements CodegenConfig {
protected String getAdditionalPropertiesName() {
return "additional_properties";
}
private void addJsonSchemaForBodyRequestInCaseItsNotPresent(CodegenParameter codegenParameter, RequestBody body) {
if (codegenParameter.jsonSchema == null)
codegenParameter.jsonSchema = Json.pretty(body);
@@ -8250,8 +8250,8 @@ public class DefaultCodegen implements CodegenConfig {
/**
* Add a given ComposedSchema as an interface model to be generated, assuming it has `oneOf` defined
*
* @param cs ComposedSchema object to create as interface model
* @param type name to use for the generated interface model
* @param cs ComposedSchema object to create as interface model
* @param type name to use for the generated interface model
*/
public void addOneOfInterfaceModel(Schema cs, String type) {
if (cs.getOneOf() == null) {
@@ -8441,7 +8441,7 @@ public class DefaultCodegen implements CodegenConfig {
// in other sub-schemas of allOf/anyOf/oneOf
cp.vendorExtensions.putIfAbsent("x-duplicated-data-type", true);
} else {
if(isTypeErasedGenerics()) {
if (isTypeErasedGenerics()) {
dataTypeSet.add(cp.baseType);
} else {
dataTypeSet.add(cp.dataType);
@@ -8472,13 +8472,17 @@ public class DefaultCodegen implements CodegenConfig {
}
@Override
public boolean getUseInlineModelResolver() { return true; }
public boolean getUseInlineModelResolver() {
return true;
}
@Override
public boolean getUseOpenAPINormalizer() { return true; }
public boolean getUseOpenapiNormalizer() {
return true;
}
@Override
public Set<String> getOpenAPIGeneratorIgnoreList() {
public Set<String> getOpenapiGeneratorIgnoreList() {
return openapiGeneratorIgnoreList;
}
@@ -8492,7 +8496,9 @@ public class DefaultCodegen implements CodegenConfig {
And convert special characters like newline, tab, carriage return
Into strings that can be rendered in the language that the generator will output to
*/
protected String handleSpecialCharacters(String name) { return name; }
protected String handleSpecialCharacters(String name) {
return name;
}
/**
* Used to ensure that null or Schema is returned given an input Boolean/Schema/null

View File

@@ -257,6 +257,12 @@ public class DefaultGenerator implements Generator {
System.out.println(SerializerUtils.toJsonString(openAPI));
}
// check to see if we need to apply camelize fix
if (config.additionalProperties().containsKey("applyCamelizeFix")) {
org.openapitools.codegen.utils.StringUtils.applyCamelizeFix =
Boolean.parseBoolean(String.valueOf(config.additionalProperties().get("applyCamelizeFix")));
}
config.processOpts();
if (opts != null && opts.getGeneratorSettings() != null) {
config.typeMapping().putAll(opts.getGeneratorSettings().getTypeMappings());
@@ -265,7 +271,7 @@ public class DefaultGenerator implements Generator {
// normalize the spec
try {
if (config.getUseOpenAPINormalizer()) {
if (config.getUseOpenapiNormalizer()) {
SemVer version = new SemVer(openAPI.getOpenapi());
if (version.atLeast("3.1.0")) {
config.openapiNormalizer().put("NORMALIZE_31SPEC", "true");
@@ -929,8 +935,8 @@ public class DefaultGenerator implements Generator {
/*
* Generate .openapi-generator-ignore if the option openapiGeneratorIgnoreFile is enabled.
*/
private void generateOpenAPIGeneratorIgnoreFile() {
if (config.getOpenAPIGeneratorIgnoreList() == null || config.getOpenAPIGeneratorIgnoreList().isEmpty()) {
private void generateOpenapiGeneratorIgnoreFile() {
if (config.getOpenapiGeneratorIgnoreList() == null || config.getOpenapiGeneratorIgnoreList().isEmpty()) {
return;
}
@@ -982,7 +988,7 @@ public class DefaultGenerator implements Generator {
Writer fileWriter = Files.newBufferedWriter(ignoreFile.toPath(), StandardCharsets.UTF_8);
fileWriter.write(header);
// add entries provided by the users
for (String entry : config.getOpenAPIGeneratorIgnoreList()) {
for (String entry : config.getOpenapiGeneratorIgnoreList()) {
fileWriter.write(entry);
fileWriter.write("\n");
}
@@ -1219,7 +1225,7 @@ public class DefaultGenerator implements Generator {
processUserDefinedTemplates();
// generate .openapi-generator-ignore if the option openapiGeneratorIgnoreFile is enabled
generateOpenAPIGeneratorIgnoreFile();
generateOpenapiGeneratorIgnoreFile();
List<File> files = new ArrayList<>();
// models

View File

@@ -770,9 +770,8 @@ public class InlineModelResolver {
for (Map.Entry<String, Schema> propertiesEntry : properties.entrySet()) {
String key = propertiesEntry.getKey();
Schema property = propertiesEntry.getValue();
if (property instanceof ObjectSchema && ((ObjectSchema) property).getProperties() != null
&& ((ObjectSchema) property).getProperties().size() > 0) {
ObjectSchema op = (ObjectSchema) property;
if (ModelUtils.isObjectSchema(property)) {
Schema op = property;
String modelName = resolveModelName(op.getTitle(), path + "_" + key);
Schema model = modelFromProperty(openAPI, op, modelName);
String existing = matchGenerated(model);
@@ -789,8 +788,8 @@ public class InlineModelResolver {
}
} else if (ModelUtils.isArraySchema(property)) {
Schema inner = ModelUtils.getSchemaItems(property);
if (inner instanceof ObjectSchema) {
ObjectSchema op = (ObjectSchema) inner;
if (ModelUtils.isObjectSchema(inner)) {
Schema op = inner;
if (op.getProperties() != null && op.getProperties().size() > 0) {
flattenProperties(openAPI, op.getProperties(), path);
String modelName = resolveModelName(op.getTitle(), path + "_" + key);
@@ -819,8 +818,8 @@ public class InlineModelResolver {
}
} else if (ModelUtils.isMapSchema(property)) {
Schema inner = ModelUtils.getAdditionalProperties(property);
if (inner instanceof ObjectSchema) {
ObjectSchema op = (ObjectSchema) inner;
if (ModelUtils.isObjectSchema(inner)) {
Schema op = inner;
if (op.getProperties() != null && op.getProperties().size() > 0) {
flattenProperties(openAPI, op.getProperties(), path);
String modelName = resolveModelName(op.getTitle(), path + "_" + key);

View File

@@ -890,7 +890,7 @@ public class OpenAPINormalizer {
if (schema.getTypes() != null && !schema.getTypes().isEmpty()) {
// 3.1 spec
if (schema.getTypes().size() ==1) { // 1 type only
if (schema.getTypes().size() == 1) { // 1 type only
String type = (String) schema.getTypes().iterator().next();
return type == null || "null".equals(type);
} else { // more than 1 type so must not be just null
@@ -902,6 +902,11 @@ public class OpenAPINormalizer {
if (Boolean.TRUE.equals(schema.getNullable())) {
return true;
}
// for `type: null`
if (schema.getTypes() == null && schema.get$ref() == null) {
return true;
}
} else { // 3.0.x or 2.x spec
if ((schema.getType() == null || schema.getType().equals("null")) && schema.get$ref() == null) {
return true;
@@ -938,7 +943,7 @@ public class OpenAPINormalizer {
if (oneOfSchemas.size() == 6) {
TreeSet<String> ts = new TreeSet<>();
for (Schema s: oneOfSchemas) {
ts.add(s.getType());
ts.add(ModelUtils.getType(s));
}
if (ts.equals(anyTypeTreeSet)) {
@@ -1063,7 +1068,7 @@ public class OpenAPINormalizer {
if (anyOfSchemas.size() == 6) {
TreeSet<String> ts = new TreeSet<>();
for (Schema s: anyOfSchemas) {
ts.add(s.getType());
ts.add(ModelUtils.getType(s));
}
if (ts.equals(anyTypeTreeSet)) {

View File

@@ -145,14 +145,14 @@ public class CodegenConfigurator {
if(generatorSettings.getOperationIdNameMappings() != null) {
configurator.operationIdNameMappings.putAll(generatorSettings.getOperationIdNameMappings());
}
if(generatorSettings.getOpenAPINormalizer() != null) {
configurator.openapiNormalizer.putAll(generatorSettings.getOpenAPINormalizer());
if(generatorSettings.getOpenapiNormalizer() != null) {
configurator.openapiNormalizer.putAll(generatorSettings.getOpenapiNormalizer());
}
if(generatorSettings.getLanguageSpecificPrimitives() != null) {
configurator.languageSpecificPrimitives.addAll(generatorSettings.getLanguageSpecificPrimitives());
}
if(generatorSettings.getOpenAPIGeneratorIgnoreList() != null) {
configurator.openapiGeneratorIgnoreList.addAll(generatorSettings.getOpenAPIGeneratorIgnoreList());
if(generatorSettings.getOpenapiGeneratorIgnoreList() != null) {
configurator.openapiGeneratorIgnoreList.addAll(generatorSettings.getOpenapiGeneratorIgnoreList());
}
if(generatorSettings.getReservedWordsMappings() != null) {
configurator.reservedWordsMappings.putAll(generatorSettings.getReservedWordsMappings());
@@ -268,9 +268,9 @@ public class CodegenConfigurator {
return this;
}
public CodegenConfigurator addOpenAPINormalizer(String key, String value) {
public CodegenConfigurator addOpenapiNormalizer(String key, String value) {
this.openapiNormalizer.put(key, value);
generatorSettingsBuilder.withOpenAPINormalizer(key, value);
generatorSettingsBuilder.withOpenapiNormalizer(key, value);
return this;
}
@@ -286,9 +286,9 @@ public class CodegenConfigurator {
return this;
}
public CodegenConfigurator addOpenAPIGeneratorIgnoreList(String value) {
public CodegenConfigurator addOpenapiGeneratorIgnoreList(String value) {
this.openapiGeneratorIgnoreList.add(value);
generatorSettingsBuilder.withOpenAPIGeneratorIgnoreList(value);
generatorSettingsBuilder.withOpenapiGeneratorIgnoreList(value);
return this;
}
@@ -482,9 +482,9 @@ public class CodegenConfigurator {
return this;
}
public CodegenConfigurator setOpenAPINormalizer(Map<String, String> openapiNormalizer) {
public CodegenConfigurator setOpenapiNormalizer(Map<String, String> openapiNormalizer) {
this.openapiNormalizer = openapiNormalizer;
generatorSettingsBuilder.withOpenAPINormalizer(openapiNormalizer);
generatorSettingsBuilder.withOpenapiNormalizer(openapiNormalizer);
return this;
}
@@ -515,10 +515,10 @@ public class CodegenConfigurator {
return this;
}
public CodegenConfigurator setOpenAPIGeneratorIgnoreList(
public CodegenConfigurator setOpenapiGeneratorIgnoreList(
Set<String> openapiGeneratorIgnoreList) {
this.openapiGeneratorIgnoreList = openapiGeneratorIgnoreList;
generatorSettingsBuilder.withOpenAPIGeneratorIgnoreList(openapiGeneratorIgnoreList);
generatorSettingsBuilder.withOpenapiGeneratorIgnoreList(openapiGeneratorIgnoreList);
return this;
}
@@ -779,9 +779,9 @@ public class CodegenConfigurator {
config.modelNameMapping().putAll(generatorSettings.getModelNameMappings());
config.enumNameMapping().putAll(generatorSettings.getEnumNameMappings());
config.operationIdNameMapping().putAll(generatorSettings.getOperationIdNameMappings());
config.openapiNormalizer().putAll(generatorSettings.getOpenAPINormalizer());
config.openapiNormalizer().putAll(generatorSettings.getOpenapiNormalizer());
config.languageSpecificPrimitives().addAll(generatorSettings.getLanguageSpecificPrimitives());
config.openapiGeneratorIgnoreList().addAll(generatorSettings.getOpenAPIGeneratorIgnoreList());
config.openapiGeneratorIgnoreList().addAll(generatorSettings.getOpenapiGeneratorIgnoreList());
config.reservedWordsMappings().putAll(generatorSettings.getReservedWordsMappings());
config.additionalProperties().putAll(generatorSettings.getAdditionalProperties());

View File

@@ -185,16 +185,16 @@ public final class CodegenConfiguratorUtils {
}
}
public static void applyOpenAPINormalizerKvpList(List<String> openapiNormalizer, CodegenConfigurator configurator) {
public static void applyOpenapiNormalizerKvpList(List<String> openapiNormalizer, CodegenConfigurator configurator) {
for (String propString : openapiNormalizer) {
applyOpenAPINormalizerKvp(propString, configurator);
applyOpenapiNormalizerKvp(propString, configurator);
}
}
public static void applyOpenAPINormalizerKvp(String openapiNormalizer, CodegenConfigurator configurator) {
public static void applyOpenapiNormalizerKvp(String openapiNormalizer, CodegenConfigurator configurator) {
final Map<String, String> map = createMapFromKeyValuePairs(openapiNormalizer);
for (Map.Entry<String, String> entry : map.entrySet()) {
configurator.addOpenAPINormalizer(entry.getKey().trim(), entry.getValue().trim());
configurator.addOpenapiNormalizer(entry.getKey().trim(), entry.getValue().trim());
}
}
@@ -250,16 +250,16 @@ public final class CodegenConfiguratorUtils {
}
}
public static void applyOpenAPIGeneratorIgnoreListCsvList(List<String> openapiGeneratorIgnoreList, CodegenConfigurator configurator) {
public static void applyOpenapiGeneratorIgnoreListCsvList(List<String> openapiGeneratorIgnoreList, CodegenConfigurator configurator) {
for (String propString : openapiGeneratorIgnoreList) {
applyOpenAPIGeneratorIgnoreListCsv(propString, configurator);
applyOpenapiGeneratorIgnoreListCsv(propString, configurator);
}
}
public static void applyOpenAPIGeneratorIgnoreListCsv(String openapiGeneratorIgnoreList, CodegenConfigurator configurator) {
public static void applyOpenapiGeneratorIgnoreListCsv(String openapiGeneratorIgnoreList, CodegenConfigurator configurator) {
final Set<String> set = createSetFromCsvList(openapiGeneratorIgnoreList);
for (String item : set) {
configurator.addOpenAPIGeneratorIgnoreList(item);
configurator.addOpenapiGeneratorIgnoreList(item);
}
}

View File

@@ -192,7 +192,7 @@ public abstract class AbstractJavaCodegen extends DefaultCodegen implements Code
"ApiClient", "ApiException", "ApiResponse", "Configuration", "StringUtil",
// language reserved words
"abstract", "continue", "for", "new", "switch", "assert",
"_", "abstract", "continue", "for", "new", "switch", "assert",
"default", "if", "package", "synchronized", "boolean", "do", "goto", "private",
"this", "break", "double", "implements", "protected", "throw", "byte", "else",
"import", "public", "throws", "case", "enum", "instanceof", "return", "transient",
@@ -999,6 +999,10 @@ public abstract class AbstractJavaCodegen extends DefaultCodegen implements Code
return getNumberBeanValidation(items);
}
if (ModelUtils.isLongSchema(items)) {
return getLongBeanValidation(items);
}
if (ModelUtils.isIntegerSchema(items)) {
return getIntegerBeanValidation(items);
}
@@ -1021,6 +1025,21 @@ public abstract class AbstractJavaCodegen extends DefaultCodegen implements Code
return "";
}
private String getLongBeanValidation(Schema<?> items) {
if (items.getMinimum() != null && items.getMaximum() != null) {
return String.format(Locale.ROOT, "@Min(%sL) @Max(%sL)", items.getMinimum(), items.getMaximum());
}
if (items.getMinimum() != null) {
return String.format(Locale.ROOT, "@Min(%sL)", items.getMinimum());
}
if (items.getMaximum() != null) {
return String.format(Locale.ROOT, "@Max(%sL)", items.getMaximum());
}
return "";
}
private String getNumberBeanValidation(Schema<?> items) {
if (items.getMinimum() != null && items.getMaximum() != null) {
return String.format(Locale.ROOT, "@DecimalMin(value = \"%s\", inclusive = %s) @DecimalMax(value = \"%s\", inclusive = %s)",
@@ -1908,10 +1927,9 @@ public abstract class AbstractJavaCodegen extends DefaultCodegen implements Code
// string
String var = value.replaceAll("\\W+", "_").toUpperCase(Locale.ROOT);
if (var.matches("\\d.*")) {
return "_" + var;
} else {
return var;
var = "_" + var;
}
return this.toVarName(var);
}
@Override

View File

@@ -683,6 +683,11 @@ public abstract class AbstractKotlinCodegen extends DefaultCodegen implements Co
*/
@Override
public String toModelName(final String name) {
// obtain the name from modelNameMapping directly if provided
if (modelNameMapping.containsKey(name)) {
return modelNameMapping.get(name);
}
// memoization
if (schemaKeyToModelNameCache.containsKey(name)) {
return schemaKeyToModelNameCache.get(name);
@@ -901,7 +906,7 @@ public abstract class AbstractKotlinCodegen extends DefaultCodegen implements Co
} else if ("kotlin.Float".equals(datatype)) {
return value + "f";
} else {
return "\"" + escapeText(value) + "\"";
return "\"" + value + "\"";
}
}

View File

@@ -1000,6 +1000,11 @@ public abstract class AbstractPythonCodegen extends DefaultCodegen implements Co
// set the extensions if the key is absent
model.getVendorExtensions().putIfAbsent("x-py-readonly", readOnlyFields);
// remove the items of postponedModelImports in modelImports to avoid circular imports error
if (!modelImports.isEmpty() && !postponedModelImports.isEmpty()){
modelImports.removeAll(postponedModelImports);
}
// import models one by one
if (!modelImports.isEmpty()) {
Set<String> modelsToImport = new TreeSet<>();

View File

@@ -1002,6 +1002,11 @@ public abstract class AbstractPythonPydanticV1Codegen extends DefaultCodegen imp
model.getVendorExtensions().putIfAbsent("x-py-datetime-imports", datetimeImports);
model.getVendorExtensions().putIfAbsent("x-py-readonly", readOnlyFields);
// remove the items of postponedModelImports in modelImports to avoid circular imports error
if (!modelImports.isEmpty() && !postponedModelImports.isEmpty()){
modelImports.removeAll(postponedModelImports);
}
// import models one by one
if (!modelImports.isEmpty()) {
Set<String> modelsToImport = new TreeSet<>();

View File

@@ -17,11 +17,13 @@
package org.openapitools.codegen.languages;
import io.swagger.v3.oas.models.OpenAPI;
import io.swagger.v3.oas.models.examples.Example;
import io.swagger.v3.oas.models.info.Info;
import io.swagger.v3.oas.models.info.License;
import io.swagger.v3.oas.models.media.ArraySchema;
import io.swagger.v3.oas.models.media.ComposedSchema;
import io.swagger.v3.oas.models.media.Schema;
import io.swagger.v3.oas.models.parameters.Parameter;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang3.StringUtils;
import org.openapitools.codegen.*;
@@ -671,10 +673,10 @@ public class JavascriptApolloClientCodegen extends DefaultCodegen implements Cod
public void setParameterExampleValue(CodegenParameter p) {
String example;
if (p.defaultValue == null) {
example = p.example;
} else {
if (p.example == null) {
example = p.defaultValue;
} else {
example = p.example;
}
String type = p.baseType;
@@ -740,6 +742,24 @@ public class JavascriptApolloClientCodegen extends DefaultCodegen implements Cod
p.example = example;
}
@Override
public void setParameterExampleValue(CodegenParameter codegenParameter, Parameter parameter) {
Schema schema = parameter.getSchema();
if (parameter.getExample() != null) {
codegenParameter.example = parameter.getExample().toString();
} else if (parameter.getExamples() != null && !parameter.getExamples().isEmpty()) {
Example example = parameter.getExamples().values().iterator().next();
if (example.getValue() != null) {
codegenParameter.example = example.getValue().toString();
}
} else if (schema != null && schema.getExample() != null) {
codegenParameter.example = schema.getExample().toString();
}
setParameterExampleValue(codegenParameter);
}
protected String setPropertyExampleValue(CodegenProperty p) {
String example;

View File

@@ -18,11 +18,13 @@
package org.openapitools.codegen.languages;
import io.swagger.v3.oas.models.OpenAPI;
import io.swagger.v3.oas.models.examples.Example;
import io.swagger.v3.oas.models.info.Info;
import io.swagger.v3.oas.models.info.License;
import io.swagger.v3.oas.models.media.ArraySchema;
import io.swagger.v3.oas.models.media.ComposedSchema;
import io.swagger.v3.oas.models.media.Schema;
import io.swagger.v3.oas.models.parameters.Parameter;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang3.StringUtils;
import org.openapitools.codegen.*;
@@ -671,10 +673,10 @@ public class JavascriptClientCodegen extends DefaultCodegen implements CodegenCo
public void setParameterExampleValue(CodegenParameter p) {
String example;
if (p.defaultValue == null) {
example = p.example;
} else {
if (p.example == null) {
example = p.defaultValue;
} else {
example = p.example;
}
String type = p.baseType;
@@ -740,6 +742,24 @@ public class JavascriptClientCodegen extends DefaultCodegen implements CodegenCo
p.example = example;
}
@Override
public void setParameterExampleValue(CodegenParameter codegenParameter, Parameter parameter) {
Schema schema = parameter.getSchema();
if (parameter.getExample() != null) {
codegenParameter.example = parameter.getExample().toString();
} else if (parameter.getExamples() != null && !parameter.getExamples().isEmpty()) {
Example example = parameter.getExamples().values().iterator().next();
if (example.getValue() != null) {
codegenParameter.example = example.getValue().toString();
}
} else if (schema != null && schema.getExample() != null) {
codegenParameter.example = schema.getExample().toString();
}
setParameterExampleValue(codegenParameter);
}
protected String setPropertyExampleValue(CodegenProperty p) {
String example;

View File

@@ -281,7 +281,7 @@ public class OCamlClientCodegen extends DefaultCodegen implements CodegenConfig
private void collectEnumSchemas(String parentName, String sName, Schema schema) {
if (ModelUtils.isArraySchema(schema)) {
collectEnumSchemas(parentName, sName, ModelUtils.getSchemaItems(schema));
} else if (schema instanceof MapSchema && schema.getAdditionalProperties() instanceof Schema) {
} else if (ModelUtils.isMapSchema(schema) && schema.getAdditionalProperties() instanceof Schema) {
collectEnumSchemas(parentName, sName, (Schema) schema.getAdditionalProperties());
} else if (isEnumSchema(schema)) {
String h = hashEnum(schema);

View File

@@ -753,6 +753,9 @@ public class PostmanCollectionCodegen extends DefaultCodegen implements CodegenC
} else if (value instanceof Integer) {
ret = ret + JSON_ESCAPE_DOUBLE_QUOTE + key + JSON_ESCAPE_DOUBLE_QUOTE + ": " +
value;
} else if (value instanceof Boolean) {
ret = ret + JSON_ESCAPE_DOUBLE_QUOTE + key + JSON_ESCAPE_DOUBLE_QUOTE + ": " +
value;
} else if (value instanceof LinkedHashMap) {
String in = ret + JSON_ESCAPE_DOUBLE_QUOTE + key + JSON_ESCAPE_DOUBLE_QUOTE + ": ";
ret = traverseMap(((LinkedHashMap<String, Object>) value), in);

View File

@@ -0,0 +1,845 @@
/*
* 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.languages;
import io.swagger.v3.oas.models.OpenAPI;
import io.swagger.v3.oas.models.media.Schema;
import org.apache.commons.io.FileUtils;
import org.openapitools.codegen.*;
import org.openapitools.codegen.model.ModelMap;
import org.openapitools.codegen.model.ModelsMap;
import org.openapitools.codegen.model.OperationsMap;
import org.openapitools.codegen.serializer.SerializerUtils;
import org.openapitools.codegen.utils.ModelUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.nio.charset.StandardCharsets;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import static org.openapitools.codegen.utils.StringUtils.camelize;
public class ScalaCaskServerCodegen extends AbstractScalaCodegen implements CodegenConfig {
public static final String PROJECT_NAME = "projectName";
private final Logger LOGGER = LoggerFactory.getLogger(ScalaCaskServerCodegen.class);
public CodegenType getTag() {
return CodegenType.SERVER;
}
public String getName() {
return "scala-cask";
}
public String getHelp() {
return "Generates a scala-cask server.";
}
protected String artifactVersion = "0.0.1";
static String ApiServiceTemplate = "apiService.mustache";
public ScalaCaskServerCodegen() {
super();
outputFolder = "generated-code/scala-cask";
embeddedTemplateDir = templateDir = "scala-cask";
apiPackage = "Apis";
modelPackage = "Models";
supportingFiles.add(new SupportingFile("README.mustache", "", "README.md"));
outputFolder = "generated-code/cask";
modelTestTemplateFiles.put("modelTest.mustache", ".scala");
modelTemplateFiles.put("model.mustache", ".scala");
modelTemplateFiles.put("modelData.mustache", "Data.scala");
apiTemplateFiles.put("api.mustache", ".scala");
apiTemplateFiles.put("apiRoutes.mustache", ".scala");
apiTemplateFiles.put(ApiServiceTemplate, "Service.scala");
embeddedTemplateDir = templateDir = "scala-cask";
setReservedWordsLowerCase(
Arrays.asList(
"abstract", "continue", "for", "new", "switch", "assert",
"default", "if", "package", "synchronized", "boolean", "do", "goto", "private",
"this", "break", "double", "implements", "protected", "throw", "byte", "else",
"import", "public", "throws", "case", "enum", "instanceof", "return", "transient",
"catch", "extends", "int", "short", "try", "char", "final", "interface", "static",
"void", "class", "finally", "long", "strictfp", "volatile", "const", "float",
"native", "super", "while", "type")
);
defaultIncludes = new HashSet<String>(
Arrays.asList("double",
"Int",
"Long",
"Float",
"Double",
"char",
"float",
"String",
"boolean",
"Boolean",
"Double",
"Integer",
"Long",
"Float",
"List",
"Set",
"Map")
);
typeMapping.put("integer", "Int");
typeMapping.put("long", "Long");
//TODO binary should be mapped to byte array
// mapped to String as a workaround
typeMapping.put("binary", "String");
cliOptions.add(new CliOption(CodegenConstants.GROUP_ID, CodegenConstants.GROUP_ID_DESC));
cliOptions.add(new CliOption(CodegenConstants.ARTIFACT_ID, CodegenConstants.ARTIFACT_ID_DESC));
cliOptions.add(new CliOption(CodegenConstants.GIT_REPO_ID, CodegenConstants.GIT_REPO_ID_DESC));
cliOptions.add(new CliOption(CodegenConstants.GIT_USER_ID, CodegenConstants.GIT_USER_ID_DESC));
cliOptions.add(new CliOption(CodegenConstants.PACKAGE_NAME, CodegenConstants.PACKAGE_DESCRIPTION));
}
@Override
public String toDefaultValue(Schema p) {
if (ModelUtils.isMapSchema(p)) {
String inner = getSchemaType(ModelUtils.getAdditionalProperties(p));
return "Map[String, " + inner + "]() ";
}
return super.toDefaultValue(p);
}
@Override
public String testPackage() {
return "src/test/scala";
}
public String toModelTestFilename(String name) {
String n = super.toModelTestFilename(name);
return (modelPackage + "." + n).replace('.', '/');
}
private String ensureProp(String key, String defaultValue) {
if (additionalProperties.containsKey(key) && !additionalProperties.get(key).toString().trim().isEmpty()) {
return (String) additionalProperties.get(key);
} else {
additionalProperties.put(key, defaultValue);
return defaultValue;
}
}
@Override
public void processOpts() {
super.processOpts();
final String groupId = ensureProp(CodegenConstants.GROUP_ID, "org.openapitools");
ensureProp(CodegenConstants.ARTIFACT_ID, "caskgen");
artifactVersion = ensureProp(CodegenConstants.ARTIFACT_VERSION, "0.0.1");
gitRepoId = ensureProp(CodegenConstants.GIT_REPO_ID, "<your git repo -- set 'gitRepoId'>");
gitUserId = ensureProp(CodegenConstants.GIT_USER_ID, "<your git user -- set 'gitUserId'>");
String basePackage = ensureProp(CodegenConstants.PACKAGE_NAME, groupId + ".server");
apiPackage = ensureProp(CodegenConstants.API_PACKAGE, basePackage + ".api");
modelPackage = ensureProp(CodegenConstants.MODEL_PACKAGE, basePackage + ".model");
final String apiPath = "src/main/scala/" + apiPackage.replace('.', '/');
final String modelPath = "src/main/scala/" + modelPackage.replace('.', '/');
final List<String> appFullPath = Arrays.stream(apiPath.split("/")).collect(Collectors.toList());
final String appFolder = String.join("/", appFullPath.subList(0, appFullPath.size() - 1));
additionalProperties.put("appName", "Cask App");
additionalProperties.put("appDescription", "A cask service");
additionalProperties.put("infoUrl", "https://openapi-generator.tech");
additionalProperties.put("infoEmail", infoEmail);
additionalProperties.put("licenseInfo", "All rights reserved");
additionalProperties.put("licenseUrl", "http://apache.org/licenses/LICENSE-2.0.html");
additionalProperties.put(CodegenConstants.INVOKER_PACKAGE, invokerPackage);
additionalProperties.put("openbrackets", "{{");
additionalProperties.put("closebrackets", "}}");
supportingFiles.add(new SupportingFile("example.mustache", "example", "Server.scala"));
supportingFiles.add(new SupportingFile("Dockerfile.mustache", "example", "Dockerfile"));
supportingFiles.add(new SupportingFile("README.mustache", "", "README.md"));
supportingFiles.add(new SupportingFile("build.sbt.mustache", "", "build.sbt"));
supportingFiles.add(new SupportingFile("bulidAndPublish.yml.mustache", "", ".github/workflows/bulidAndPublish.yml"));
supportingFiles.add(new SupportingFile("build.sc.mustache", "", "build.sc"));
supportingFiles.add(new SupportingFile(".scalafmt.conf.mustache", "", ".scalafmt.conf"));
supportingFiles.add(new SupportingFile("gitignore.mustache", "", ".gitignore"));
supportingFiles.add(new SupportingFile("appPackage.mustache", appFolder, "package.scala"));
supportingFiles.add(new SupportingFile("apiPackage.mustache", apiPath, "package.scala"));
supportingFiles.add(new SupportingFile("modelPackage.mustache", modelPath, "package.scala"));
supportingFiles.add(new SupportingFile("exampleApp.mustache", appFolder, "ExampleApp.scala"));
supportingFiles.add(new SupportingFile("baseApp.mustache", appFolder, "BaseApp.scala"));
supportingFiles.add(new SupportingFile("openapiRoute.mustache", apiPath, "OpenApiRoutes.scala"));
supportingFiles.add(new SupportingFile("appRoutes.mustache", appFolder, "AppRoutes.scala"));
supportingFiles.add(new SupportingFile("project/build.properties", "project", "build.properties"));
supportingFiles.add(new SupportingFile("project/plugins.sbt", "project", "plugins.sbt"));
instantiationTypes.put("array", "Seq");
instantiationTypes.put("map", "Map");
importMapping = new HashMap<String, String>();
importMapping.put("BigDecimal", "scala.math.BigDecimal");
importMapping.put("UUID", "java.util.UUID");
importMapping.put("File", "java.io.File");
importMapping.put("Date", "java.time.LocalDate as Date");
importMapping.put("Timestamp", "java.sql.Timestamp");
importMapping.put("Map", "Map");
importMapping.put("HashMap", "Map");
importMapping.put("Array", "Seq");
importMapping.put("ArrayList", "Seq");
importMapping.put("List", "Seq");
importMapping.put("DateTime", "java.time.LocalDateTime");
importMapping.put("LocalDateTime", "java.time.LocalDateTime");
importMapping.put("LocalDate", "java.time.LocalDate");
importMapping.put("OffsetDateTime", "java.time.OffsetDateTime");
importMapping.put("LocalTime", "java.time.LocalTime");
}
static boolean consumesMimetype(CodegenOperation op, String mimetype) {
// people don't always/often specify the 'consumes' property, so we assume true when
// the optional 'consumes' is null or empty
boolean defaultRetValue = true;
final List<Map<String, String>> consumes = op.consumes;
if (consumes != null) {
for (Map<String, String> c : consumes) {
final String mt = c.get("mediaType");
if (mt.equalsIgnoreCase(mimetype)) {
return true;
}
}
return false;
} else {
return defaultRetValue;
}
}
static String formatMap(Map<?, ?> map) {
StringBuilder mapAsString = new StringBuilder("{");
for (Object key : map.keySet().stream().sorted().collect(Collectors.toList())) {
mapAsString.append(key + " -- " + map.get(key) + ",\n");
}
if (mapAsString.length() > 1) {
mapAsString.delete(mapAsString.length() - 2, mapAsString.length());
}
mapAsString.append("}");
return mapAsString.toString();
}
@Override
public String toApiName(String name) {
if (name.isEmpty()) {
return "DefaultApi";
}
name = sanitizeName(name);
return camelize(name);
}
@Override
public String apiFilename(String templateName, String tag) {
String suffix = apiTemplateFiles().get(templateName);
String fn = toApiFilename(tag);
if (templateName.equals(ApiServiceTemplate)) {
return apiFileFolder() + '/' + fn + suffix;
} else {
return apiFileFolder() + '/' + fn + "Routes" + suffix;
}
}
static String capitalise(String p) {
if (p.length() < 2) {
return p.toUpperCase(Locale.ROOT);
} else {
String first = "" + p.charAt(0);
return first.toUpperCase(Locale.ROOT) + p.substring(1);
}
}
// thanks FlaskConnectionCodeGen
private static List<Map<String, Object>> getOperations(Map<String, Object> objs) {
List<Map<String, Object>> result = new ArrayList<Map<String, Object>>();
Map<String, Object> apiInfo = (Map<String, Object>) objs.get("apiInfo");
List<Map<String, Object>> apis = (List<Map<String, Object>>) apiInfo.get("apis");
for (Map<String, Object> api : apis) {
Map<String, Object> operations = (Map<String, Object>) api.get("operations");
result.add(operations);
}
return result;
}
@Override
public Map<String, Object> postProcessSupportingFileData(Map<String, Object> objs) {
List<Map<String, Object>> operations = getOperations(objs);
for (int i = 0; i < operations.size(); i++) {
operations.get(i).put("hasMore", i < operations.size() - 1);
}
objs.put("operations", operations);
return super.postProcessSupportingFileData(objs);
}
protected String getResourceFolder() {
String src = getSourceFolder();
List<String> parts = Arrays.stream(src.split("/", -1)).collect(Collectors.toList());
if (parts.isEmpty()) {
return "resources";
} else {
String srcMain = String.join("/", parts.subList(0, parts.size() - 1));
return srcMain + "/resources";
}
}
@Override
public void processOpenAPI(OpenAPI openAPI) {
String jsonOpenAPI = SerializerUtils.toJsonString(openAPI);
try {
String outputFile = getOutputDir() + "/" + getResourceFolder() + "/openapi.json";
FileUtils.writeStringToFile(new File(outputFile), jsonOpenAPI, StandardCharsets.UTF_8);
LOGGER.info("wrote file to {}", outputFile);
} catch (Exception e) {
LOGGER.error(e.getMessage(), e);
}
}
public static class ParamPart {
final CodegenParameter param;
final String name;
final boolean isParam;
// flag for if there are more path parts
boolean hasMore;
// flag for if there are more path parts which are parameters
boolean hasMoreParams;
final String conversion;
public ParamPart(String name, CodegenParameter param) {
this.name = name;
this.param = param;
this.isParam = param != null;
this.hasMore = true;
this.conversion = !isParam || param.isString ? "" : ".to" + param.dataType;
}
}
/**
* Cask will compile but 'initialize' can throw a route overlap exception:
* <p>
* {{{
* Routes overlap with wildcards: get /user/logout, get /user/:username, get /user/login
* }}}
* <p>
* Note: The same error persists even if the suffixes are unique:
* {{{
* Routes overlap with wildcards: get /user/logout/3, get /user/:username/1, get /user/login/2
* }}}
* <p>
* To fix this, we need to identify and resolve conflicts in our generated code.
* <p>
* # How do we identify conflicts?
* </p>
* <p>
* 1. group routes by their non-param prefixes.
* <p>
* 2. add an "x-annotation" vendor extension for operations
* <p>
* 3. add a list of "RouteGroups" which can manually delegate as per below
* <p>
* <p>
* # How do we resolve conflicts?
* <p>
* We leave out the cask route annotation on the conflicting operations, e.g. :
* {{{
* //conflict: @cask.get("/user/:username")
* def getUserByName(username: String, request: cask.Request) = ...
* }}}
* <p>
* and we introduce a new discriminator function to "manually" call those conflicts:
* {{{
*
* @cask.get("/user", subpath = true)
* def userRouteDescriminator(request: cask.Request) = {
* request.remainingPathSegments match {
* case Seq("logout") => logoutUser(request)
* case Seq("login") => loginUser(request)
* case Seq(param) => getUserByName(param, request)
* }
* }
* }}}
*/
public static class OperationGroup {
List<CodegenOperation> operations = new ArrayList<>();
final String pathPrefix;
final String httpMethod;
final String caskAnnotation;
final String methodName;
// TODO - multiple operations may have the same query params, so we'll need to somehow merge them (and take the right type)
public boolean hasGroupQueryParams() {
return operations.stream().flatMap(op -> op.queryParams.stream()).count() > 0;
}
/**
* This is invoked from `scala-cask/apiRoutesQueryParamsTyped.mustache`
*
* @return the CodegenParameters
*/
public List<CodegenParameter> getGroupQueryParams() {
List<CodegenParameter> list = operations.stream().flatMap(op -> op.queryParams.stream()).map(p -> {
final CodegenParameter copy = p.copy();
copy.vendorExtensions.put("x-default-value", defaultValue(p));
copy.required = false; // all our query params are optional for our work-around as it's a super-set of a few different routes
copy.dataType = asScalaDataType(copy, false, true, true);
copy.defaultValue = defaultValue(copy);
return copy;
}
).collect(Collectors.toList());
return list;
}
@Override
public String toString() {
List<String> ops = operations.stream().map(o -> o.path + "\n").collect(Collectors.toList());
return httpMethod + " " + pathPrefix + " w/ " + operations.size() + " operations:\n" + String.join("", ops);
}
public OperationGroup(String httpMethod, String pathPrefix) {
this.httpMethod = httpMethod;
this.pathPrefix = pathPrefix;
caskAnnotation = "@cask." + httpMethod.toLowerCase(Locale.ROOT);
List<String> stripped = Arrays.stream(pathPrefix.split("/", -1))
.map(ScalaCaskServerCodegen::capitalise).collect(Collectors.toList());
methodName = "routeWorkAroundFor" + capitalise(httpMethod) + String.join("", stripped);
}
public void add(CodegenOperation op) {
if (!op.path.startsWith(pathPrefix)) {
throw new IllegalArgumentException("inconsistent path: " + pathPrefix);
}
if (!op.httpMethod.equals(httpMethod)) {
throw new IllegalArgumentException("inconsistent method: " + httpMethod);
}
final List<ScalaCaskServerCodegen.ParamPart> pathParts = new ArrayList<>();
final List<String> parts = Arrays.stream(op.path.substring(pathPrefix.length()).split("/", -1)).filter(p -> !p.isEmpty()).collect(Collectors.toList());
for (int i = 0; i < parts.size(); i++) {
String p = parts.get(i);
ScalaCaskServerCodegen.ParamPart pp = hasBrackets(p) ? new ScalaCaskServerCodegen.ParamPart(chompBrackets(p), pathParamForName(op, chompBrackets(p))) : new ScalaCaskServerCodegen.ParamPart(p, null);
pathParts.add(pp);
}
List<ScalaCaskServerCodegen.ParamPart> paramPathParts = pathParts.stream().filter(p -> p.isParam).collect(Collectors.toList());
if (!paramPathParts.isEmpty()) {
final String lastParamName = paramPathParts.get(paramPathParts.size() - 1).name;
paramPathParts.forEach(p -> p.hasMoreParams = !p.name.equals(lastParamName));
}
if (!pathParts.isEmpty()) {
pathParts.get(pathParts.size() - 1).hasMore = false;
}
op.vendorExtensions.put("x-path-remaining", pathParts);
op.vendorExtensions.put("x-has-path-remaining", !paramPathParts.isEmpty());
operations.add(op);
}
public boolean contains(CodegenOperation op) {
return operations.contains(op);
}
public void updateAnnotations() {
operations.forEach(op -> {
String annotation = op.vendorExtensions.get("x-annotation").toString();
String conflicts = String.join(", ", operations.stream().map(o -> o.path).collect(Collectors.toList()));
op.vendorExtensions.put("x-annotation", "// conflicts with [" + conflicts + "] after" + pathPrefix + ", ignoring " + annotation);
});
operations = operations.stream().sorted((a, b) -> a.pathParams.size() - b.pathParams.size()).collect(Collectors.toList());
}
}
static List<ScalaCaskServerCodegen.OperationGroup> group(List<CodegenOperation> operationList) {
Map<String, ScalaCaskServerCodegen.OperationGroup> groupedByPrefix = new HashMap<>();
operationList.forEach(op -> {
String prefix = nonParamPathPrefix(op);
String key = op.httpMethod + " " + prefix;
if (!op.pathParams.isEmpty()) {
final ScalaCaskServerCodegen.OperationGroup group = groupedByPrefix.getOrDefault(key, new ScalaCaskServerCodegen.OperationGroup(op.httpMethod, prefix));
group.add(op);
groupedByPrefix.put(key, group);
}
});
return groupedByPrefix.values().stream().collect(Collectors.toList());
}
static String nonParamPathPrefix(CodegenOperation op) {
if (op.pathParams.isEmpty()) {
return op.path;
}
final String firstParam = op.pathParams.stream().findFirst().get().paramName;
final int i = op.path.indexOf(firstParam);
final String path = chompSuffix(op.path.substring(0, i - 1), "/");
return path;
}
static List<ScalaCaskServerCodegen.OperationGroup> createRouteGroups(List<CodegenOperation> operationList) {
List<ScalaCaskServerCodegen.OperationGroup> groups = group(operationList);
operationList.forEach((op) -> {
// for the usage/call site
final String scalaPath = pathWithBracketPlaceholdersRemovedAndXPathIndexAdded(op);
op.vendorExtensions.put("x-cask-path", scalaPath);
final String annotation = "@cask." + op.httpMethod.toLowerCase(Locale.ROOT);
op.vendorExtensions.put("x-annotation", annotation);
for (final ScalaCaskServerCodegen.OperationGroup group : groups) {
if (!group.contains(op)) {
if (op.path.startsWith(group.pathPrefix) && op.httpMethod.equalsIgnoreCase(group.httpMethod)) {
group.add(op);
}
}
}
});
List<ScalaCaskServerCodegen.OperationGroup> trimmed = groups.stream().filter(g -> g.operations.size() > 1).map(g -> {
g.updateAnnotations();
return g;
}).collect(Collectors.toList());
return trimmed;
}
@Override
public OperationsMap postProcessOperationsWithModels(OperationsMap objs, List<ModelMap> allModels) {
final Map<String, Object> operations = (Map<String, Object>) objs.get("operations");
final List<CodegenOperation> operationList = (List<CodegenOperation>) operations.get("operation");
objs.put("route-groups", createRouteGroups(operationList));
operationList.forEach(ScalaCaskServerCodegen::postProcessOperation);
return objs;
}
@Override
public ModelsMap postProcessModels(ModelsMap objs) {
objs.getModels().stream().map(ModelMap::getModel).forEach(this::postProcessModel);
return objs;
}
private void setDefaultValueForCodegenProperty(CodegenProperty p) {
if (p.defaultValue == null || p.defaultValue.trim().isEmpty()) {
if (p.getIsEnumOrRef()) {
p.defaultValue = "null";
} else {
p.defaultValue = defaultValueNonOption(p);
}
} else if (p.defaultValue.contains("Seq.empty")) {
p.defaultValue = "Nil";
}
}
private void postProcessModel(CodegenModel model) {
model.getAllVars().forEach(this::setDefaultValueForCodegenProperty);
model.getVars().forEach(this::setDefaultValueForCodegenProperty);
model.getVars().forEach(ScalaCaskServerCodegen::postProcessProperty);
model.getAllVars().forEach(ScalaCaskServerCodegen::postProcessProperty);
}
private static void postProcessOperation(CodegenOperation op) {
// force http method to lower case
op.httpMethod = op.httpMethod.toLowerCase(Locale.ROOT);
/* Put in 'x-consumes-json' and 'x-consumes-xml' */
op.vendorExtensions.put("x-consumes-json", consumesMimetype(op, "application/json"));
op.vendorExtensions.put("x-consumes-xml", consumesMimetype(op, "application/xml"));
op.bodyParams.stream().filter((b) -> b.isBodyParam).forEach((p) -> {
p.vendorExtensions.put("x-consumes-json", consumesMimetype(op, "application/json"));
p.vendorExtensions.put("x-consumes-xml", consumesMimetype(op, "application/xml"));
});
/* put in 'x-container-type' to help with unmarshalling from json */
op.allParams.forEach((p) -> p.vendorExtensions.put("x-container-type", containerType(p.dataType)));
op.bodyParams.forEach((p) -> p.vendorExtensions.put("x-container-type", containerType(p.dataType)));
final String paramList = op.allParams.stream().map((p) -> p.paramName).collect(Collectors.joining(", "));
op.vendorExtensions.put("x-param-list", paramList);
final Stream<String> typed = op.allParams.stream().map((p) -> p.paramName + " : " + asScalaDataType(p, p.required, false));
op.vendorExtensions.put("x-param-list-typed", String.join(", ", typed.collect(Collectors.toList())));
final Stream<String> typedJson = op.allParams.stream().map((p) -> p.paramName + " : " + asScalaDataType(p, p.required, true));
op.vendorExtensions.put("x-param-list-typed-json", String.join(", ", typedJson.collect(Collectors.toList())));
// for the declaration site
op.vendorExtensions.put("x-cask-path-typed", routeArgs(op));
op.vendorExtensions.put("x-query-args", queryArgs(op));
List<String> responses = op.responses.stream().map(r -> r.dataType).filter(Objects::nonNull).collect(Collectors.toList());
op.vendorExtensions.put("x-response-type", responses.isEmpty() ? "Unit" : String.join(" | ", responses));
}
private static void postProcessProperty(CodegenProperty p) {
p.vendorExtensions.put("x-datatype-model", asScalaDataType(p, p.required, false));
p.vendorExtensions.put("x-defaultValue-model", defaultValue(p, p.required, p.defaultValue));
String dataTypeData = asScalaDataType(p, p.required, true);
p.vendorExtensions.put("x-datatype-data", dataTypeData);
p.vendorExtensions.put("x-containertype-data", containerType(dataTypeData));
p.vendorExtensions.put("x-defaultValue-data", defaultValueNonOption(p, p.defaultValue));
// the 'asModel' logic for modelData.mustache
//
// if it's optional (not required), then wrap the value in Option()
// ... unless it's a map or array, in which case it can just be empty
//
p.vendorExtensions.put("x-wrap-in-optional", !p.required && !p.isArray && !p.isMap);
// if it's an array or optional, we need to map it as a model -- unless it's a map,
// in which case we have to map the values
boolean hasItemModel = p.items != null && p.items.isModel;
boolean isObjectArray = p.isArray && hasItemModel;
boolean isOptionalObj = !p.required && p.isModel;
p.vendorExtensions.put("x-map-asModel", (isOptionalObj || isObjectArray) && !p.isMap);
// when deserialising map objects, the logic is tricky.
p.vendorExtensions.put("x-deserialize-asModelMap", p.isMap && hasItemModel);
// for some reason, an openapi spec with pattern field like this:
// pattern: '^[A-Za-z]+$'
// will result in the pattern property text of
// pattern: '/^[A-Za-z]+$/'
if (p.pattern != null && p.pattern.startsWith("/") && p.pattern.endsWith("/")) {
p.pattern = p.pattern.substring(1, p.pattern.length() - 1);
}
}
/**
* Cask path params use the :pathParam syntax rather than the {pathParam} syntax
*
* @param op
* @return
*/
private static String pathWithBracketPlaceholdersRemovedAndXPathIndexAdded(CodegenOperation op) {
String[] items = op.path.split("/", -1);
String scalaPath = "";
for (int i = 0; i < items.length; ++i) {
final String nextPart = hasBrackets(items[i]) ? ":" + chompBrackets(items[i]) : items[i];
if (i != items.length - 1) {
scalaPath = scalaPath + nextPart + "/";
} else {
scalaPath = scalaPath + nextPart;
}
}
return scalaPath;
}
private static CodegenParameter pathParamForName(CodegenOperation op, String pathParam) {
final CodegenParameter param = op.pathParams.stream().filter(p -> p.paramName.equals(pathParam)).findFirst().get();
if (param == null) {
throw new RuntimeException("Bug: path param " + pathParam + " not found");
}
return param;
}
/**
* The path placeholders as well as query parameters
*
* @param op the codegen operations
* @return a list of both the path and query parameters as typed arguments (e.g. "aPathArg : Int, request: cask.Request, aQueryArg : Option[Long]")
*/
private static String routeArgs(CodegenOperation op) {
final Stream<String> pathParamNames = Arrays.stream(op.path.split("/", -1)).filter(ScalaCaskServerCodegen::hasBrackets).map(p -> {
final CodegenParameter param = pathParamForName(op, chompBrackets(p));
return param.paramName + " : " + asScalaDataType(param, param.required, true);
});
final List<String> pathList = pathParamNames.collect(Collectors.toList());
// we always include the cask request
pathList.add("request: cask.Request");
final Stream<String> queryParams = op.queryParams.stream().map(p -> {
p.vendorExtensions.put("x-default-value", defaultValue(p));
return p.paramName + " : " + asScalaDataType(p, p.required, true, true);
});
pathList.addAll(queryParams.collect(Collectors.toList()));
return pathList.isEmpty() ? "" : (String.join(", ", pathList));
}
private static String defaultValue(CodegenParameter p) {
return defaultValue(p, p.required, p.defaultValue);
}
private static String defaultValue(IJsonSchemaValidationProperties p, boolean required, String fallbackDefaultValue) {
if (!required && !(p.getIsArray() || p.getIsMap())) {
return "None";
}
return defaultValueNonOption(p, fallbackDefaultValue);
}
private static String defaultValueNonOption(IJsonSchemaValidationProperties p, String fallbackDefaultValue) {
if (p.getIsArray()) {
if (p.getUniqueItems()) {
return "Set.empty";
}
return "Nil";
}
if (p.getIsMap()) {
return "Map.empty";
}
if (p.getIsNumber()) {
return "0";
}
if (p.getIsEnum()) {
return fallbackDefaultValue;
}
if (p.getIsBoolean()) {
return "false";
}
if (p.getIsUuid()) {
return "java.util.UUID.randomUUID()";
}
if (p.getIsString()) {
return "\"\"";
}
return fallbackDefaultValue;
}
private static String defaultValueNonOption(CodegenProperty p) {
if (p.getIsArray()) {
return "Nil";
}
if (p.getIsMap()) {
return "Map.empty";
}
if (p.isNumber || p.isNumeric) {
return "0";
}
if (p.isBoolean) {
return "false";
}
if (p.isUuid) {
return "java.util.UUID.randomUUID()";
}
if (p.isModel) {
return "null";
}
if (p.isDate || p.isDateTime) {
return "null";
}
if (p.isString) {
return "\"\"";
}
return p.defaultValue;
}
private static String queryArgs(final CodegenOperation op) {
final List<String> list = op.queryParams.stream().map(p -> p.paramName).collect(Collectors.toList());
final String prefix = list.isEmpty() ? "" : ", ";
return prefix + String.join(", ", list);
}
/**
* For our model classes, we have two variants:
* <p>
* 1) a {model}.scala one which is a validated, model class
* 2) a {model}Data.scala one which is just our data-transfer-object (DTO) which is written primarily for e.g. json serialisation
* <p>
* The data variant can have nulls and other non-scala things, but they know how to create validated model objects.
* <p>
* This 'asScalaDataType' is used to ensure the type hierarchy is correct for both the model and data varients.
* <p>
* e.g. consider this example:
* ```
* case class Foo(bar : Bar, bazz :List[Bazz])
* case class Bar(x : Option[String] = None)
* case class Bazz(y : Int)
* <p>
* // vs
* <p>
* case class FooData(bar : BarData, bazz :List[BazzData])
* case class BarData(x : String = "")
* case class BazzData(y : Int)
* ```
*/
private static String asScalaDataType(final IJsonSchemaValidationProperties param, boolean required, boolean useJason) {
return asScalaDataType(param, required, useJason, !useJason);
}
private static String asScalaDataType(final IJsonSchemaValidationProperties param, boolean required, boolean useJason, boolean allowOptional) {
String dataType = (param.getIsModel() && useJason) ? param.getDataType() + "Data" : param.getDataType();
final String dataSuffix = useJason && param.getItems() != null && param.getItems().getIsModel() ? "Data" : "";
if (dataType.startsWith("List[")) {
dataType = dataType.replace("List[", "Seq[");
dataType = dataType.replace("]", dataSuffix + "]");
} else if (dataType.startsWith("Set[")) {
dataType = dataType.replace("]", dataSuffix + "]");
} else if (!required && allowOptional) {
dataType = "Option[" + dataType + "]";
}
return dataType;
}
private static String chompBrackets(String str) {
return str.replace("{", "").replace("}", "");
}
private static String chompSuffix(String str, String suffix) {
return str.endsWith(suffix) ? chompSuffix(str.substring(0, str.length() - suffix.length()), suffix) : str;
}
private static boolean hasBrackets(String str) {
return str.matches("^\\{(.*)\\}$");
}
static String containerType(String dataType) {
String fixedForList = dataType.replaceAll(".*\\[(.*)\\]", "$1");
// if it is a map, we want the value type
final String[] parts = fixedForList.split(",");
return parts[parts.length - 1];
}
}

View File

@@ -460,7 +460,7 @@ public class ModelUtils {
return (schema instanceof ObjectSchema) ||
// must not be a map
(SchemaTypeUtil.OBJECT_TYPE.equals(schema.getType()) && !(schema instanceof MapSchema)) ||
(SchemaTypeUtil.OBJECT_TYPE.equals(schema.getType()) && !(ModelUtils.isMapSchema(schema))) ||
// must have at least one property
(schema.getType() == null && schema.getProperties() != null && !schema.getProperties().isEmpty());
}
@@ -509,10 +509,6 @@ public class ModelUtils {
* @return true if the specified schema is a Composed schema.
*/
public static boolean isComplexComposedSchema(Schema schema) {
if (!(schema instanceof ComposedSchema)) {
return false;
}
int count = 0;
if (schema.getAllOf() != null && !schema.getAllOf().isEmpty()) {
@@ -2130,6 +2126,25 @@ public class ModelUtils {
return false;
}
/**
* Returns schema type.
* For 3.1 spec, return the first one.
*
* @param schema the schema
* @return schema type
*/
public static String getType(Schema schema) {
if (schema == null) {
return null;
}
if (schema instanceof JsonSchema) {
return String.valueOf(schema.getTypes().iterator().next());
} else {
return schema.getType();
}
}
/**
* Returns true if any of the common attributes of the schema (e.g. readOnly, default, maximum, etc) is defined.
*

View File

@@ -29,6 +29,9 @@ public class StringUtils {
*/
public static final String NAME_CACHE_EXPIRY_PROPERTY = "org.openapitools.codegen.utils.namecache.expireafter.seconds";
// if set true, enable the camelize fix
public static boolean applyCamelizeFix = false;
// A cache of camelized words. The camelize() method is invoked many times with the same
// arguments, this cache is used to optimized performance.
private static Cache<Pair<String, CamelizeOption>, String> camelizedWordsCache;
@@ -38,7 +41,6 @@ public class StringUtils {
// A cache of escaped words, used to optimize the performance of the escape() method.
private static Cache<EscapedNameOptions, String> escapedWordsCache;
static {
int cacheSize = Integer.parseInt(GlobalSettings.getProperty(NAME_CACHE_SIZE_PROPERTY, "200"));
int cacheExpiry = Integer.parseInt(GlobalSettings.getProperty(NAME_CACHE_EXPIRY_PROPERTY, "5"));
@@ -117,6 +119,7 @@ public class StringUtils {
private static Pattern camelizeSlashPattern = Pattern.compile("\\/(.?)");
private static Pattern camelizeUppercasePattern = Pattern.compile("(\\.?)(\\w)([^\\.]*)$");
private static Pattern camelizeUppercaseStartPattern = Pattern.compile("^([A-Z]+)(([A-Z][a-z].*)|([^a-zA-Z].*)|$)$");
private static Pattern camelizeUnderscorePattern = Pattern.compile("(_)(.)");
private static Pattern camelizeHyphenPattern = Pattern.compile("(-)(.)");
private static Pattern camelizeDollarPattern = Pattern.compile("\\$");
@@ -135,8 +138,18 @@ public class StringUtils {
return camelizedWordsCache.get(key, pair -> {
String word = pair.getKey();
CamelizeOption option = pair.getValue();
Matcher m;
// Lowercase acronyms at start of word if not UPPERCASE_FIRST_CHAR
if (applyCamelizeFix) {
m = camelizeUppercaseStartPattern.matcher(word);
if (camelizeOption != UPPERCASE_FIRST_CHAR && m.find()) {
word = m.group(1).toLowerCase(Locale.ROOT) + m.group(2);
}
}
// Replace all slashes with dots (package separator)
Matcher m = camelizeSlashPattern.matcher(word);
m = camelizeSlashPattern.matcher(word);
while (m.find()) {
word = m.replaceFirst("." + m.group(1).replace("\\", "\\\\")/*.toUpperCase()*/);
m = camelizeSlashPattern.matcher(word);

View File

@@ -11,6 +11,7 @@ import java.text.DecimalFormat;
import java.util.GregorianCalendar;
import java.util.TimeZone;
{{>generatedAnnotation}}
public class RFC3339DateFormat extends DateFormat {
private static final long serialVersionUID = 1L;
private static final TimeZone TIMEZONE_Z = TimeZone.getTimeZone("UTC");
@@ -43,4 +44,4 @@ public class RFC3339DateFormat extends DateFormat {
public Object clone() {
return super.clone();
}
}
}

View File

@@ -5,6 +5,7 @@ import java.util.Map;
/**
* Representing a Server configuration.
*/
{{>generatedAnnotation}}
public class ServerConfiguration {
public String URL;
public String description;

View File

@@ -5,6 +5,7 @@ import java.util.HashSet;
/**
* Representing a Server Variable for server URL template substitution.
*/
{{>generatedAnnotation}}
public class ServerVariable {
public String description;
public String defaultValue;

View File

@@ -14,6 +14,7 @@ import java.util.TreeMap;
*
* @param <T> The type of data that is deserialized from response body
*/
{{>generatedAnnotation}}
public class ApiResponse<T> {
final private int statusCode;
final private Map<String, List<String>> headers;

View File

@@ -81,6 +81,7 @@ public class JSON {
/**
* Helper class to register the discriminator mappings.
*/
{{>generatedAnnotation}}
private static class ClassDiscriminatorMapping {
// The model class name.
Class<?> modelClass;

View File

@@ -540,6 +540,7 @@ public class {{classname}} {
}
return localVarRequestBuilder;
}
{{#vendorExtensions.x-group-parameters}}
{{#hasParams}}

View File

@@ -652,6 +652,29 @@ public class ApiClient {
throw new RuntimeException("No AWS4 authentication configured!");
}
/**
* Helper method to set credentials for AWSV4 Signature
*
* @param accessKey Access Key
* @param secretKey Secret Key
* @param sessionToken Session Token
* @param region Region
* @param service Service to access to
*/
public void setAWS4Configuration(String accessKey, String secretKey, String sessionToken, String region, String service) {
{{#withAWSV4Signature}}
for (Authentication auth : authentications.values()) {
if (auth instanceof AWS4Auth) {
((AWS4Auth) auth).setCredentials(accessKey, secretKey, sessionToken);
((AWS4Auth) auth).setRegion(region);
((AWS4Auth) auth).setService(service);
return;
}
}
{{/withAWSV4Signature}}
throw new RuntimeException("No AWS4 authentication configured!");
}
/**
* Set the User-Agent header's value (by adding to the default header map).
*

View File

@@ -54,8 +54,8 @@ public class {{classname}} extends AbstractOpenApiSchema{{#vendorExtensions.x-im
{{/isArray}}
{{#isArray}}
final Type typeInstance = new TypeToken<List<{{complexType}}>>(){}.getType();
final TypeAdapter<{{{dataType}}}> adapter{{complexType}}List = (TypeAdapter<List<{{complexType}}>>) gson.getDelegateAdapter(this, TypeToken.get(typeInstance));
final Type typeInstance = new TypeToken<{{{dataType}}}>(){}.getType();
final TypeAdapter<{{{dataType}}}> adapter{{#sanitizeGeneric}}{{{dataType}}}{{/sanitizeGeneric}} = (TypeAdapter<{{{dataType}}}>) gson.getDelegateAdapter(this, TypeToken.get(typeInstance));
{{/isArray}}
{{/anyOf}}
{{/composedSchemas}}
@@ -74,30 +74,32 @@ public class {{classname}} extends AbstractOpenApiSchema{{#vendorExtensions.x-im
// check if the actual instance is of the type `{{{dataType}}}`
if (value.getActualInstance() instanceof {{#isArray}}List<?>{{/isArray}}{{^isArray}}{{{dataType}}}{{/isArray}}) {
{{#isPrimitiveType}}
JsonPrimitive primitive = adapter{{{dataType}}}.toJsonTree(({{{dataType}}})value.getActualInstance()).getAsJsonPrimitive();
elementAdapter.write(out, primitive);
return;
{{/isPrimitiveType}}
{{#isArray}}
List<?> list = (List<?>) value.getActualInstance();
if(list.get(0) instanceof {{complexType}}) {
JsonArray array = adapter{{{complexType}}}List.toJsonTree(({{{dataType}}})value.getActualInstance()).getAsJsonArray();
elementAdapter.write(out, array);
JsonPrimitive primitive = adapter{{#sanitizeGeneric}}{{{dataType}}}{{/sanitizeGeneric}}.toJsonTree(({{{dataType}}})value.getActualInstance()).getAsJsonPrimitive();
elementAdapter.write(out, primitive);
return;
}
{{/isPrimitiveType}}
{{^isPrimitiveType}}
{{#isArray}}
List<?> list = (List<?>) value.getActualInstance();
if (list.get(0) instanceof {{{items.dataType}}}) {
JsonArray array = adapter{{#sanitizeGeneric}}{{{dataType}}}{{/sanitizeGeneric}}.toJsonTree(({{{dataType}}})value.getActualInstance()).getAsJsonArray();
elementAdapter.write(out, array);
return;
}
{{/isArray}}
{{/isPrimitiveType}}
{{^isArray}}
{{^isPrimitiveType}}
JsonElement element = adapter{{{dataType}}}.toJsonTree(({{{dataType}}})value.getActualInstance());
elementAdapter.write(out, element);
return;
JsonElement element = adapter{{{dataType}}}.toJsonTree(({{{dataType}}})value.getActualInstance());
elementAdapter.write(out, element);
return;
{{/isPrimitiveType}}
{{/isArray}}
}
{{/vendorExtensions.x-duplicated-data-type}}
{{/anyOf}}
{{/composedSchemas}}
throw new IOException("Failed to serialize as the type doesn't match anyOf schemae: {{#anyOf}}{{{.}}}{{^-last}}, {{/-last}}{{/anyOf}}");
throw new IOException("Failed to serialize as the type doesn't match anyOf schemas: {{#anyOf}}{{{.}}}{{^-last}}, {{/-last}}{{/anyOf}}");
}
@Override
@@ -114,63 +116,66 @@ public class {{classname}} extends AbstractOpenApiSchema{{#vendorExtensions.x-im
{{^hasVars}}
// deserialize {{{dataType}}}
try {
// validate the JSON object to see if any exception is thrown
// validate the JSON object to see if any exception is thrown
{{^isArray}}
{{#isNumber}}
if(!jsonElement.getAsJsonPrimitive().isNumber()) {
throw new IllegalArgumentException(String.format("Expected json element to be of type Number in the JSON string but got `%s`", jsonElement.toString()));
}
actualAdapter = adapter{{{dataType}}};
if (!jsonElement.getAsJsonPrimitive().isNumber()) {
throw new IllegalArgumentException(String.format("Expected json element to be of type Number in the JSON string but got `%s`", jsonElement.toString()));
}
actualAdapter = adapter{{#sanitizeGeneric}}{{{dataType}}}{{/sanitizeGeneric}};
{{/isNumber}}
{{^isNumber}}
{{#isPrimitiveType}}
if(!jsonElement.getAsJsonPrimitive().is{{#isBoolean}}Boolean{{/isBoolean}}{{#isString}}String{{/isString}}{{^isString}}{{^isBoolean}}Number{{/isBoolean}}{{/isString}}()) {
throw new IllegalArgumentException(String.format("Expected json element to be of type {{#isBoolean}}Boolean{{/isBoolean}}{{#isString}}String{{/isString}}{{^isString}}{{^isBoolean}}Number{{/isBoolean}}{{/isString}} in the JSON string but got `%s`", jsonElement.toString()));
}
actualAdapter = adapter{{{dataType}}};
{{/isPrimitiveType}}
{{^isPrimitiveType}}
{{^isArray}}
{{{dataType}}}.validateJsonElement(jsonElement);
actualAdapter = adapter{{{dataType}}};
{{/isArray}}
if (!jsonElement.getAsJsonPrimitive().is{{#isBoolean}}Boolean{{/isBoolean}}{{#isString}}String{{/isString}}{{^isString}}{{^isBoolean}}Number{{/isBoolean}}{{/isString}}()) {
throw new IllegalArgumentException(String.format("Expected json element to be of type {{#isBoolean}}Boolean{{/isBoolean}}{{#isString}}String{{/isString}}{{^isString}}{{^isBoolean}}Number{{/isBoolean}}{{/isString}} in the JSON string but got `%s`", jsonElement.toString()));
}
actualAdapter = adapter{{#sanitizeGeneric}}{{{dataType}}}{{/sanitizeGeneric}};
{{/isPrimitiveType}}
{{/isNumber}}
{{^isNumber}}
{{^isPrimitiveType}}
{{{dataType}}}.validateJsonElement(jsonElement);
actualAdapter = adapter{{#sanitizeGeneric}}{{{dataType}}}{{/sanitizeGeneric}};
{{/isPrimitiveType}}
{{/isNumber}}
{{#isArray}}
if (!jsonElement.isJsonArray()) {
throw new IllegalArgumentException(String.format("Expected json element to be a array type in the JSON string but got `%s`", jsonElement.toString()));
}
JsonArray array = jsonElement.getAsJsonArray();
// validate array items
for(JsonElement element : array) {
{{#items}}
{{#isNumber}}
if(!jsonElement.getAsJsonPrimitive().isNumber()) {
throw new IllegalArgumentException(String.format("Expected json element to be of type Number in the JSON string but got `%s`", jsonElement.toString()));
}
actualAdapter = adapter{{{dataType}}};
{{/isNumber}}
{{^isNumber}}
{{#isPrimitiveType}}
if(!element.getAsJsonPrimitive().is{{#isBoolean}}Boolean{{/isBoolean}}{{#isString}}String{{/isString}}{{^isString}}{{^isBoolean}}Number{{/isBoolean}}{{/isString}}()) {
throw new IllegalArgumentException(String.format("Expected array items to be of type {{#isBoolean}}Boolean{{/isBoolean}}{{#isString}}String{{/isString}}{{^isString}}{{^isBoolean}}Number{{/isBoolean}}{{/isString}} in the JSON string but got `%s`", jsonElement.toString()));
}
{{/isPrimitiveType}}
{{^isPrimitiveType}}
{{{dataType}}}.validateJsonElement(element);
{{/isPrimitiveType}}
{{/isNumber}}
{{/items}}
}
actualAdapter = adapter{{{complexType}}}List;
{{/isArray}}
{{classname}} ret = new {{classname}}();
ret.setActualInstance(actualAdapter.fromJsonTree(jsonElement));
return ret;
{{#isArray}}
if (!jsonElement.isJsonArray()) {
throw new IllegalArgumentException(String.format("Expected json element to be a array type in the JSON string but got `%s`", jsonElement.toString()));
}
JsonArray array = jsonElement.getAsJsonArray();
// validate array items
for(JsonElement element : array) {
{{#items}}
{{#isNumber}}
if (!jsonElement.getAsJsonPrimitive().isNumber()) {
throw new IllegalArgumentException(String.format("Expected json element to be of type Number in the JSON string but got `%s`", jsonElement.toString()));
}
{{/isNumber}}
{{^isNumber}}
{{#isPrimitiveType}}
if (!element.getAsJsonPrimitive().is{{#isBoolean}}Boolean{{/isBoolean}}{{#isString}}String{{/isString}}{{^isString}}{{^isBoolean}}Number{{/isBoolean}}{{/isString}}()) {
throw new IllegalArgumentException(String.format("Expected array items to be of type {{#isBoolean}}Boolean{{/isBoolean}}{{#isString}}String{{/isString}}{{^isString}}{{^isBoolean}}Number{{/isBoolean}}{{/isString}} in the JSON string but got `%s`", jsonElement.toString()));
}
{{/isPrimitiveType}}
{{/isNumber}}
{{^isNumber}}
{{^isPrimitiveType}}
{{{dataType}}}.validateJsonElement(element);
{{/isPrimitiveType}}
{{/isNumber}}
{{/items}}
}
actualAdapter = adapter{{#sanitizeGeneric}}{{{dataType}}}{{/sanitizeGeneric}};
{{/isArray}}
{{classname}} ret = new {{classname}}();
ret.setActualInstance(actualAdapter.fromJsonTree(jsonElement));
return ret;
} catch (Exception e) {
// deserialization failed, continue
errorMessages.add(String.format("Deserialization for {{{dataType}}} failed with `%s`.", e.getMessage()));
log.log(Level.FINER, "Input data does not match schema '{{{dataType}}}'", e);
// deserialization failed, continue
errorMessages.add(String.format("Deserialization for {{{dataType}}} failed with `%s`.", e.getMessage()));
log.log(Level.FINER, "Input data does not match schema '{{{dataType}}}'", e);
}
{{/hasVars}}
{{#hasVars}}
@@ -182,7 +187,6 @@ public class {{classname}} extends AbstractOpenApiSchema{{#vendorExtensions.x-im
{{classname}} ret = new {{classname}}();
ret.setActualInstance(actualAdapter.fromJsonTree(jsonElement));
return ret;
log.log(Level.FINER, "Input data matches schema '{{{.}}}'");
} catch (Exception e) {
// deserialization failed, continue
errorMessages.add(String.format("Deserialization for {{{.}}} failed with `%s`.", e.getMessage()));
@@ -250,10 +254,10 @@ public class {{classname}} extends AbstractOpenApiSchema{{#vendorExtensions.x-im
if (instance instanceof {{#isArray}}List<?>{{/isArray}}{{^isArray}}{{{dataType}}}{{/isArray}}) {
{{#isArray}}
List<?> list = (List<?>) instance;
if(list.get(0) instanceof {{complexType}}) {
super.setActualInstance(instance);
return;
}
if (list.get(0) instanceof {{{items.dataType}}}) {
super.setActualInstance(instance);
return;
}
{{/isArray}}
{{^isArray}}
super.setActualInstance(instance);
@@ -273,6 +277,7 @@ public class {{classname}} extends AbstractOpenApiSchema{{#vendorExtensions.x-im
*
* @return The actual instance ({{#anyOf}}{{{.}}}{{^-last}}, {{/-last}}{{/anyOf}})
*/
@SuppressWarnings("unchecked")
@Override
public Object getActualInstance() {
return super.getActualInstance();
@@ -288,105 +293,108 @@ public class {{classname}} extends AbstractOpenApiSchema{{#vendorExtensions.x-im
* @return The actual instance of `{{{dataType}}}`
* @throws ClassCastException if the instance is not `{{{dataType}}}`
*/
public {{{dataType}}} get{{#isArray}}{{complexType}}List{{/isArray}}{{^isArray}}{{{dataType}}}{{/isArray}}() throws ClassCastException {
public {{{dataType}}} get{{#isArray}}{{#sanitizeGeneric}}{{{dataType}}}{{/sanitizeGeneric}}{{/isArray}}{{^isArray}}{{{dataType}}}{{/isArray}}() throws ClassCastException {
return ({{{dataType}}})super.getActualInstance();
}
{{/vendorExtensions.x-duplicated-data-type}}
{{/anyOf}}
{{/composedSchemas}}
/**
* Validates the JSON Element and throws an exception if issues found
*
* @param jsonElement JSON Element
* @throws IOException if the JSON Element is invalid with respect to {{classname}}
*/
public static void validateJsonElement(JsonElement jsonElement) throws IOException {
// validate anyOf schemas one by one
ArrayList<String> errorMessages = new ArrayList<>();
{{#composedSchemas}}
{{#anyOf}}
{{^vendorExtensions.x-duplicated-data-type}}
// validate the json string with {{{dataType}}}
try {
{{^hasVars}}
{{#isNumber}}
if(!jsonElement.getAsJsonPrimitive().isNumber()) {
throw new IllegalArgumentException(String.format("Expected json element to be of type Number in the JSON string but got `%s`", jsonElement.toString()));
}
{{/isNumber}}
{{^isNumber}}
{{#isPrimitiveType}}
if(!jsonElement.getAsJsonPrimitive().is{{#isBoolean}}Boolean{{/isBoolean}}{{#isString}}String{{/isString}}{{^isString}}{{^isBoolean}}Number{{/isBoolean}}{{/isString}}()) {
throw new IllegalArgumentException(String.format("Expected json element to be of type {{#isBoolean}}Boolean{{/isBoolean}}{{#isString}}String{{/isString}}{{^isString}}{{^isBoolean}}Number{{/isBoolean}}{{/isString}} in the JSON string but got `%s`", jsonElement.toString()));
}
{{/isPrimitiveType}}
{{^isPrimitiveType}}
{{^isArray}}
{{{dataType}}}.validateJsonElement(jsonElement);
{{/isArray}}
{{/isPrimitiveType}}
{{/isNumber}}
{{#isArray}}
if (!jsonElement.isJsonArray()) {
throw new IllegalArgumentException(String.format("Expected json element to be a array type in the JSON string but got `%s`", jsonElement.toString()));
}
JsonArray array = jsonElement.getAsJsonArray();
// validate array items
for(JsonElement element : array) {
{{#items}}
/**
* Validates the JSON Element and throws an exception if issues found
*
* @param jsonElement JSON Element
* @throws IOException if the JSON Element is invalid with respect to {{classname}}
*/
public static void validateJsonElement(JsonElement jsonElement) throws IOException {
// validate anyOf schemas one by one
ArrayList<String> errorMessages = new ArrayList<>();
{{#composedSchemas}}
{{#anyOf}}
{{^vendorExtensions.x-duplicated-data-type}}
// validate the json string with {{{dataType}}}
try {
{{^hasVars}}
{{^isArray}}
{{#isNumber}}
if(!jsonElement.getAsJsonPrimitive().isNumber()) {
throw new IllegalArgumentException(String.format("Expected json element to be of type Number in the JSON string but got `%s`", jsonElement.toString()));
}
if (!jsonElement.getAsJsonPrimitive().isNumber()) {
throw new IllegalArgumentException(String.format("Expected json element to be of type Number in the JSON string but got `%s`", jsonElement.toString()));
}
{{/isNumber}}
{{^isNumber}}
{{#isPrimitiveType}}
if(!element.getAsJsonPrimitive().is{{#isBoolean}}Boolean{{/isBoolean}}{{#isString}}String{{/isString}}{{^isString}}{{^isBoolean}}Number{{/isBoolean}}{{/isString}}()) {
throw new IllegalArgumentException(String.format("Expected array items to be of type {{#isBoolean}}Boolean{{/isBoolean}}{{#isString}}String{{/isString}}{{^isString}}{{^isBoolean}}Number{{/isBoolean}}{{/isString}} in the JSON string but got `%s`", jsonElement.toString()));
}
{{/isPrimitiveType}}
{{^isPrimitiveType}}
{{{dataType}}}.validateJsonElement(element);
if (!jsonElement.getAsJsonPrimitive().is{{#isBoolean}}Boolean{{/isBoolean}}{{#isString}}String{{/isString}}{{^isString}}{{^isBoolean}}Number{{/isBoolean}}{{/isString}}()) {
throw new IllegalArgumentException(String.format("Expected json element to be of type {{#isBoolean}}Boolean{{/isBoolean}}{{#isString}}String{{/isString}}{{^isString}}{{^isBoolean}}Number{{/isBoolean}}{{/isString}} in the JSON string but got `%s`", jsonElement.toString()));
}
{{/isPrimitiveType}}
{{/isNumber}}
{{/items}}
}
{{/isArray}}
{{/hasVars}}
{{#hasVars}}
{{{.}}}.validateJsonElement(jsonElement);
return;
{{/hasVars}}
return;
} catch (Exception e) {
errorMessages.add(String.format("Deserialization for {{{dataType}}} failed with `%s`.", e.getMessage()));
// continue to the next one
{{^isNumber}}
{{^isPrimitiveType}}
{{{dataType}}}.validateJsonElement(jsonElement);
{{/isPrimitiveType}}
{{/isNumber}}
{{/isArray}}
{{#isArray}}
if (!jsonElement.isJsonArray()) {
throw new IllegalArgumentException(String.format("Expected json element to be a array type in the JSON string but got `%s`", jsonElement.toString()));
}
JsonArray array = jsonElement.getAsJsonArray();
// validate array items
for(JsonElement element : array) {
{{#items}}
{{#isNumber}}
if (!jsonElement.getAsJsonPrimitive().isNumber()) {
throw new IllegalArgumentException(String.format("Expected json element to be of type Number in the JSON string but got `%s`", jsonElement.toString()));
}
{{/isNumber}}
{{^isNumber}}
{{#isPrimitiveType}}
if (!element.getAsJsonPrimitive().is{{#isBoolean}}Boolean{{/isBoolean}}{{#isString}}String{{/isString}}{{^isString}}{{^isBoolean}}Number{{/isBoolean}}{{/isString}}()) {
throw new IllegalArgumentException(String.format("Expected array items to be of type {{#isBoolean}}Boolean{{/isBoolean}}{{#isString}}String{{/isString}}{{^isString}}{{^isBoolean}}Number{{/isBoolean}}{{/isString}} in the JSON string but got `%s`", jsonElement.toString()));
}
{{/isPrimitiveType}}
{{/isNumber}}
{{^isNumber}}
{{^isPrimitiveType}}
{{{dataType}}}.validateJsonElement(element);
{{/isPrimitiveType}}
{{/isNumber}}
{{/items}}
}
{{/isArray}}
{{/hasVars}}
{{#hasVars}}
{{{.}}}.validateJsonElement(jsonElement);
return;
{{/hasVars}}
return;
} catch (Exception e) {
errorMessages.add(String.format("Deserialization for {{{dataType}}} failed with `%s`.", e.getMessage()));
// continue to the next one
}
{{/vendorExtensions.x-duplicated-data-type}}
{{/anyOf}}
{{/composedSchemas}}
throw new IOException(String.format("The JSON string is invalid for {{classname}} with anyOf schemas: {{#anyOf}}{{{.}}}{{^-last}}, {{/-last}}{{/anyOf}}. no class match the result, expected at least 1. Detailed failure message for anyOf schemas: %s. JSON: %s", errorMessages, jsonElement.toString()));
}
{{/vendorExtensions.x-duplicated-data-type}}
{{/anyOf}}
{{/composedSchemas}}
throw new IOException(String.format("The JSON string is invalid for {{classname}} with anyOf schemas: {{#anyOf}}{{{.}}}{{^-last}}, {{/-last}}{{/anyOf}}. no class match the result, expected at least 1. Detailed failure message for anyOf schemas: %s. JSON: %s", errorMessages, jsonElement.toString()));
}
/**
* Create an instance of {{classname}} given an JSON string
*
* @param jsonString JSON string
* @return An instance of {{classname}}
* @throws IOException if the JSON string is invalid with respect to {{classname}}
*/
public static {{{classname}}} fromJson(String jsonString) throws IOException {
return JSON.getGson().fromJson(jsonString, {{{classname}}}.class);
}
/**
* Create an instance of {{classname}} given an JSON string
*
* @param jsonString JSON string
* @return An instance of {{classname}}
* @throws IOException if the JSON string is invalid with respect to {{classname}}
*/
public static {{{classname}}} fromJson(String jsonString) throws IOException {
return JSON.getGson().fromJson(jsonString, {{{classname}}}.class);
}
/**
* Convert an instance of {{classname}} to an JSON string
*
* @return JSON string
*/
public String toJson() {
return JSON.getGson().toJson(this);
}
/**
* Convert an instance of {{classname}} to an JSON string
*
* @return JSON string
*/
public String toJson() {
return JSON.getGson().toJson(this);
}
}

View File

@@ -16,6 +16,7 @@ import java.util.stream.Collectors;
import software.amazon.awssdk.auth.credentials.AnonymousCredentialsProvider;
import software.amazon.awssdk.auth.credentials.AwsBasicCredentials;
import software.amazon.awssdk.auth.credentials.AwsSessionCredentials;
import software.amazon.awssdk.auth.credentials.AwsCredentials;
import software.amazon.awssdk.auth.signer.Aws4Signer;
import software.amazon.awssdk.auth.signer.params.Aws4SignerParams;
@@ -41,6 +42,10 @@ public class AWS4Auth implements Authentication {
this.credentials = AwsBasicCredentials.create(accessKey, secretKey);
}
public void setCredentials(String accessKey, String secretKey, String sessionToken) {
this.credentials = AwsSessionCredentials.create(accessKey, secretKey, sessionToken);
}
public void setRegion(String region) {
this.region = region;
}

View File

@@ -54,8 +54,8 @@ public class {{classname}} extends AbstractOpenApiSchema{{#vendorExtensions.x-im
{{/isArray}}
{{#isArray}}
final Type typeInstance = new TypeToken<List<{{complexType}}>>(){}.getType();
final TypeAdapter<{{{dataType}}}> adapter{{complexType}}List = (TypeAdapter<List<{{complexType}}>>) gson.getDelegateAdapter(this, TypeToken.get(typeInstance));
final Type typeInstance = new TypeToken<{{{dataType}}}>(){}.getType();
final TypeAdapter<{{{dataType}}}> adapter{{#sanitizeGeneric}}{{{dataType}}}{{/sanitizeGeneric}} = (TypeAdapter<{{{dataType}}}>) gson.getDelegateAdapter(this, TypeToken.get(typeInstance));
{{/isArray}}
{{/oneOf}}
{{/composedSchemas}}
@@ -74,23 +74,25 @@ public class {{classname}} extends AbstractOpenApiSchema{{#vendorExtensions.x-im
// check if the actual instance is of the type `{{{dataType}}}`
if (value.getActualInstance() instanceof {{#isArray}}List<?>{{/isArray}}{{^isArray}}{{{dataType}}}{{/isArray}}) {
{{#isPrimitiveType}}
JsonPrimitive primitive = adapter{{{dataType}}}.toJsonTree(({{{dataType}}})value.getActualInstance()).getAsJsonPrimitive();
elementAdapter.write(out, primitive);
return;
{{/isPrimitiveType}}
{{#isArray}}
List<?> list = (List<?>) value.getActualInstance();
if(list.get(0) instanceof {{complexType}}) {
JsonArray array = adapter{{{complexType}}}List.toJsonTree(({{{dataType}}})value.getActualInstance()).getAsJsonArray();
elementAdapter.write(out, array);
JsonPrimitive primitive = adapter{{#sanitizeGeneric}}{{{dataType}}}{{/sanitizeGeneric}}.toJsonTree(({{{dataType}}})value.getActualInstance()).getAsJsonPrimitive();
elementAdapter.write(out, primitive);
return;
}
{{/isPrimitiveType}}
{{^isPrimitiveType}}
{{#isArray}}
List<?> list = (List<?>) value.getActualInstance();
if (list.get(0) instanceof {{{items.dataType}}}) {
JsonArray array = adapter{{#sanitizeGeneric}}{{{dataType}}}{{/sanitizeGeneric}}.toJsonTree(({{{dataType}}})value.getActualInstance()).getAsJsonArray();
elementAdapter.write(out, array);
return;
}
{{/isArray}}
{{/isPrimitiveType}}
{{^isArray}}
{{^isPrimitiveType}}
JsonElement element = adapter{{{dataType}}}.toJsonTree(({{{dataType}}})value.getActualInstance());
elementAdapter.write(out, element);
return;
JsonElement element = adapter{{{dataType}}}.toJsonTree(({{{dataType}}})value.getActualInstance());
elementAdapter.write(out, element);
return;
{{/isPrimitiveType}}
{{/isArray}}
}
@@ -139,62 +141,65 @@ public class {{classname}} extends AbstractOpenApiSchema{{#vendorExtensions.x-im
{{^hasVars}}
// deserialize {{{dataType}}}
try {
// validate the JSON object to see if any exception is thrown
// validate the JSON object to see if any exception is thrown
{{^isArray}}
{{#isNumber}}
if(!jsonElement.getAsJsonPrimitive().isNumber()) {
throw new IllegalArgumentException(String.format("Expected json element to be of type Number in the JSON string but got `%s`", jsonElement.toString()));
}
actualAdapter = adapter{{{dataType}}};
if (!jsonElement.getAsJsonPrimitive().isNumber()) {
throw new IllegalArgumentException(String.format("Expected json element to be of type Number in the JSON string but got `%s`", jsonElement.toString()));
}
actualAdapter = adapter{{#sanitizeGeneric}}{{{dataType}}}{{/sanitizeGeneric}};
{{/isNumber}}
{{^isNumber}}
{{#isPrimitiveType}}
if(!jsonElement.getAsJsonPrimitive().is{{#isBoolean}}Boolean{{/isBoolean}}{{#isString}}String{{/isString}}{{^isString}}{{^isBoolean}}Number{{/isBoolean}}{{/isString}}()) {
throw new IllegalArgumentException(String.format("Expected json element to be of type {{#isBoolean}}Boolean{{/isBoolean}}{{#isString}}String{{/isString}}{{^isString}}{{^isBoolean}}Number{{/isBoolean}}{{/isString}} in the JSON string but got `%s`", jsonElement.toString()));
}
actualAdapter = adapter{{{dataType}}};
{{/isPrimitiveType}}
{{^isPrimitiveType}}
{{^isArray}}
{{{dataType}}}.validateJsonElement(jsonElement);
actualAdapter = adapter{{{dataType}}};
{{/isArray}}
if (!jsonElement.getAsJsonPrimitive().is{{#isBoolean}}Boolean{{/isBoolean}}{{#isString}}String{{/isString}}{{^isString}}{{^isBoolean}}Number{{/isBoolean}}{{/isString}}()) {
throw new IllegalArgumentException(String.format("Expected json element to be of type {{#isBoolean}}Boolean{{/isBoolean}}{{#isString}}String{{/isString}}{{^isString}}{{^isBoolean}}Number{{/isBoolean}}{{/isString}} in the JSON string but got `%s`", jsonElement.toString()));
}
actualAdapter = adapter{{#sanitizeGeneric}}{{{dataType}}}{{/sanitizeGeneric}};
{{/isPrimitiveType}}
{{/isNumber}}
{{^isNumber}}
{{^isPrimitiveType}}
{{{dataType}}}.validateJsonElement(jsonElement);
actualAdapter = adapter{{#sanitizeGeneric}}{{{dataType}}}{{/sanitizeGeneric}};
{{/isPrimitiveType}}
{{/isNumber}}
{{#isArray}}
if (!jsonElement.isJsonArray()) {
throw new IllegalArgumentException(String.format("Expected json element to be a array type in the JSON string but got `%s`", jsonElement.toString()));
}
JsonArray array = jsonElement.getAsJsonArray();
// validate array items
for(JsonElement element : array) {
{{#items}}
{{#isNumber}}
if(!jsonElement.getAsJsonPrimitive().isNumber()) {
throw new IllegalArgumentException(String.format("Expected json element to be of type Number in the JSON string but got `%s`", jsonElement.toString()));
}
actualAdapter = adapter{{{dataType}}};
{{/isNumber}}
{{^isNumber}}
{{#isPrimitiveType}}
if(!element.getAsJsonPrimitive().is{{#isBoolean}}Boolean{{/isBoolean}}{{#isString}}String{{/isString}}{{^isString}}{{^isBoolean}}Number{{/isBoolean}}{{/isString}}()) {
throw new IllegalArgumentException(String.format("Expected array items to be of type {{#isBoolean}}Boolean{{/isBoolean}}{{#isString}}String{{/isString}}{{^isString}}{{^isBoolean}}Number{{/isBoolean}}{{/isString}} in the JSON string but got `%s`", jsonElement.toString()));
}
{{/isPrimitiveType}}
{{^isPrimitiveType}}
{{{dataType}}}.validateJsonElement(element);
{{/isPrimitiveType}}
{{/isNumber}}
{{/items}}
}
actualAdapter = adapter{{{complexType}}}List;
{{/isArray}}
match++;
log.log(Level.FINER, "Input data matches schema '{{{dataType}}}'");
{{#isArray}}
if (!jsonElement.isJsonArray()) {
throw new IllegalArgumentException(String.format("Expected json element to be a array type in the JSON string but got `%s`", jsonElement.toString()));
}
JsonArray array = jsonElement.getAsJsonArray();
// validate array items
for(JsonElement element : array) {
{{#items}}
{{#isNumber}}
if (!jsonElement.getAsJsonPrimitive().isNumber()) {
throw new IllegalArgumentException(String.format("Expected json element to be of type Number in the JSON string but got `%s`", jsonElement.toString()));
}
{{/isNumber}}
{{^isNumber}}
{{#isPrimitiveType}}
if (!element.getAsJsonPrimitive().is{{#isBoolean}}Boolean{{/isBoolean}}{{#isString}}String{{/isString}}{{^isString}}{{^isBoolean}}Number{{/isBoolean}}{{/isString}}()) {
throw new IllegalArgumentException(String.format("Expected array items to be of type {{#isBoolean}}Boolean{{/isBoolean}}{{#isString}}String{{/isString}}{{^isString}}{{^isBoolean}}Number{{/isBoolean}}{{/isString}} in the JSON string but got `%s`", jsonElement.toString()));
}
{{/isPrimitiveType}}
{{/isNumber}}
{{^isNumber}}
{{^isPrimitiveType}}
{{{dataType}}}.validateJsonElement(element);
{{/isPrimitiveType}}
{{/isNumber}}
{{/items}}
}
actualAdapter = adapter{{#sanitizeGeneric}}{{{dataType}}}{{/sanitizeGeneric}};
{{/isArray}}
match++;
log.log(Level.FINER, "Input data matches schema '{{{dataType}}}'");
} catch (Exception e) {
// deserialization failed, continue
errorMessages.add(String.format("Deserialization for {{{dataType}}} failed with `%s`.", e.getMessage()));
log.log(Level.FINER, "Input data does not match schema '{{{dataType}}}'", e);
// deserialization failed, continue
errorMessages.add(String.format("Deserialization for {{{dataType}}} failed with `%s`.", e.getMessage()));
log.log(Level.FINER, "Input data does not match schema '{{{dataType}}}'", e);
}
{{/hasVars}}
{{#hasVars}}
@@ -278,10 +283,10 @@ public class {{classname}} extends AbstractOpenApiSchema{{#vendorExtensions.x-im
if (instance instanceof {{#isArray}}List<?>{{/isArray}}{{^isArray}}{{{dataType}}}{{/isArray}}) {
{{#isArray}}
List<?> list = (List<?>) instance;
if(list.get(0) instanceof {{complexType}}) {
super.setActualInstance(instance);
return;
}
if (list.get(0) instanceof {{{items.dataType}}}) {
super.setActualInstance(instance);
return;
}
{{/isArray}}
{{^isArray}}
super.setActualInstance(instance);
@@ -301,6 +306,7 @@ public class {{classname}} extends AbstractOpenApiSchema{{#vendorExtensions.x-im
*
* @return The actual instance ({{#oneOf}}{{{.}}}{{^-last}}, {{/-last}}{{/oneOf}})
*/
@SuppressWarnings("unchecked")
@Override
public Object getActualInstance() {
return super.getActualInstance();
@@ -316,107 +322,111 @@ public class {{classname}} extends AbstractOpenApiSchema{{#vendorExtensions.x-im
* @return The actual instance of `{{{dataType}}}`
* @throws ClassCastException if the instance is not `{{{dataType}}}`
*/
public {{{dataType}}} get{{#isArray}}{{complexType}}List{{/isArray}}{{^isArray}}{{{dataType}}}{{/isArray}}() throws ClassCastException {
public {{{dataType}}} get{{#isArray}}{{#sanitizeGeneric}}{{{dataType}}}{{/sanitizeGeneric}}{{/isArray}}{{^isArray}}{{{dataType}}}{{/isArray}}() throws ClassCastException {
return ({{{dataType}}})super.getActualInstance();
}
{{/vendorExtensions.x-duplicated-data-type}}
{{/oneOf}}
{{/composedSchemas}}
/**
* Validates the JSON Element and throws an exception if issues found
*
* @param jsonElement JSON Element
* @throws IOException if the JSON Element is invalid with respect to {{classname}}
*/
public static void validateJsonElement(JsonElement jsonElement) throws IOException {
// validate oneOf schemas one by one
int validCount = 0;
ArrayList<String> errorMessages = new ArrayList<>();
{{#composedSchemas}}
{{#oneOf}}
{{^vendorExtensions.x-duplicated-data-type}}
// validate the json string with {{{dataType}}}
try {
{{^hasVars}}
{{#isNumber}}
if(!jsonElement.getAsJsonPrimitive().isNumber()) {
throw new IllegalArgumentException(String.format("Expected json element to be of type Number in the JSON string but got `%s`", jsonElement.toString()));
}
{{/isNumber}}
{{^isNumber}}
{{#isPrimitiveType}}
if(!jsonElement.getAsJsonPrimitive().is{{#isBoolean}}Boolean{{/isBoolean}}{{#isString}}String{{/isString}}{{^isString}}{{^isBoolean}}Number{{/isBoolean}}{{/isString}}()) {
throw new IllegalArgumentException(String.format("Expected json element to be of type {{#isBoolean}}Boolean{{/isBoolean}}{{#isString}}String{{/isString}}{{^isString}}{{^isBoolean}}Number{{/isBoolean}}{{/isString}} in the JSON string but got `%s`", jsonElement.toString()));
}
{{/isPrimitiveType}}
{{^isPrimitiveType}}
{{^isArray}}
{{{dataType}}}.validateJsonElement(jsonElement);
{{/isArray}}
{{/isPrimitiveType}}
{{/isNumber}}
{{#isArray}}
if (!jsonElement.isJsonArray()) {
throw new IllegalArgumentException(String.format("Expected json element to be a array type in the JSON string but got `%s`", jsonElement.toString()));
}
JsonArray array = jsonElement.getAsJsonArray();
// validate array items
for(JsonElement element : array) {
{{#items}}
/**
* Validates the JSON Element and throws an exception if issues found
*
* @param jsonElement JSON Element
* @throws IOException if the JSON Element is invalid with respect to {{classname}}
*/
public static void validateJsonElement(JsonElement jsonElement) throws IOException {
// validate oneOf schemas one by one
int validCount = 0;
ArrayList<String> errorMessages = new ArrayList<>();
{{#composedSchemas}}
{{#oneOf}}
{{^vendorExtensions.x-duplicated-data-type}}
// validate the json string with {{{dataType}}}
try {
{{^hasVars}}
{{^isArray}}
{{#isNumber}}
if(!jsonElement.getAsJsonPrimitive().isNumber()) {
throw new IllegalArgumentException(String.format("Expected json element to be of type Number in the JSON string but got `%s`", jsonElement.toString()));
}
if (!jsonElement.getAsJsonPrimitive().isNumber()) {
throw new IllegalArgumentException(String.format("Expected json element to be of type Number in the JSON string but got `%s`", jsonElement.toString()));
}
{{/isNumber}}
{{^isNumber}}
{{#isPrimitiveType}}
if(!element.getAsJsonPrimitive().is{{#isBoolean}}Boolean{{/isBoolean}}{{#isString}}String{{/isString}}{{^isString}}{{^isBoolean}}Number{{/isBoolean}}{{/isString}}()) {
throw new IllegalArgumentException(String.format("Expected array items to be of type {{#isBoolean}}Boolean{{/isBoolean}}{{#isString}}String{{/isString}}{{^isString}}{{^isBoolean}}Number{{/isBoolean}}{{/isString}} in the JSON string but got `%s`", jsonElement.toString()));
}
{{/isPrimitiveType}}
{{^isPrimitiveType}}
{{{dataType}}}.validateJsonElement(element);
if (!jsonElement.getAsJsonPrimitive().is{{#isBoolean}}Boolean{{/isBoolean}}{{#isString}}String{{/isString}}{{^isString}}{{^isBoolean}}Number{{/isBoolean}}{{/isString}}()) {
throw new IllegalArgumentException(String.format("Expected json element to be of type {{#isBoolean}}Boolean{{/isBoolean}}{{#isString}}String{{/isString}}{{^isString}}{{^isBoolean}}Number{{/isBoolean}}{{/isString}} in the JSON string but got `%s`", jsonElement.toString()));
}
{{/isPrimitiveType}}
{{/isNumber}}
{{/items}}
}
{{/isArray}}
{{/hasVars}}
{{#hasVars}}
{{{.}}}.validateJsonElement(jsonElement);
validCount++;
{{/hasVars}}
validCount++;
} catch (Exception e) {
errorMessages.add(String.format("Deserialization for {{{dataType}}} failed with `%s`.", e.getMessage()));
// continue to the next one
{{^isNumber}}
{{^isPrimitiveType}}
{{{dataType}}}.validateJsonElement(jsonElement);
{{/isPrimitiveType}}
{{/isNumber}}
{{/isArray}}
{{#isArray}}
if (!jsonElement.isJsonArray()) {
throw new IllegalArgumentException(String.format("Expected json element to be a array type in the JSON string but got `%s`", jsonElement.toString()));
}
JsonArray array = jsonElement.getAsJsonArray();
// validate array items
for(JsonElement element : array) {
{{#items}}
{{#isNumber}}
if (!jsonElement.getAsJsonPrimitive().isNumber()) {
throw new IllegalArgumentException(String.format("Expected json element to be of type Number in the JSON string but got `%s`", jsonElement.toString()));
}
{{/isNumber}}
{{^isNumber}}
{{#isPrimitiveType}}
if (!element.getAsJsonPrimitive().is{{#isBoolean}}Boolean{{/isBoolean}}{{#isString}}String{{/isString}}{{^isString}}{{^isBoolean}}Number{{/isBoolean}}{{/isString}}()) {
throw new IllegalArgumentException(String.format("Expected array items to be of type {{#isBoolean}}Boolean{{/isBoolean}}{{#isString}}String{{/isString}}{{^isString}}{{^isBoolean}}Number{{/isBoolean}}{{/isString}} in the JSON string but got `%s`", jsonElement.toString()));
}
{{/isPrimitiveType}}
{{/isNumber}}
{{^isNumber}}
{{^isPrimitiveType}}
{{{dataType}}}.validateJsonElement(element);
{{/isPrimitiveType}}
{{/isNumber}}
{{/items}}
}
{{/isArray}}
{{/hasVars}}
{{#hasVars}}
{{{.}}}.validateJsonElement(jsonElement);
validCount++;
{{/hasVars}}
validCount++;
} catch (Exception e) {
errorMessages.add(String.format("Deserialization for {{{dataType}}} failed with `%s`.", e.getMessage()));
// continue to the next one
}
{{/vendorExtensions.x-duplicated-data-type}}
{{/oneOf}}
{{/composedSchemas}}
if (validCount != 1) {
throw new IOException(String.format("The JSON string is invalid for {{classname}} with oneOf schemas: {{#oneOf}}{{{.}}}{{^-last}}, {{/-last}}{{/oneOf}}. %d class(es) match the result, expected 1. Detailed failure message for oneOf schemas: %s. JSON: %s", validCount, errorMessages, jsonElement.toString()));
}
}
{{/vendorExtensions.x-duplicated-data-type}}
{{/oneOf}}
{{/composedSchemas}}
if (validCount != 1) {
throw new IOException(String.format("The JSON string is invalid for {{classname}} with oneOf schemas: {{#oneOf}}{{{.}}}{{^-last}}, {{/-last}}{{/oneOf}}. %d class(es) match the result, expected 1. Detailed failure message for oneOf schemas: %s. JSON: %s", validCount, errorMessages, jsonElement.toString()));
/**
* Create an instance of {{classname}} given an JSON string
*
* @param jsonString JSON string
* @return An instance of {{classname}}
* @throws IOException if the JSON string is invalid with respect to {{classname}}
*/
public static {{{classname}}} fromJson(String jsonString) throws IOException {
return JSON.getGson().fromJson(jsonString, {{{classname}}}.class);
}
}
/**
* Create an instance of {{classname}} given an JSON string
*
* @param jsonString JSON string
* @return An instance of {{classname}}
* @throws IOException if the JSON string is invalid with respect to {{classname}}
*/
public static {{{classname}}} fromJson(String jsonString) throws IOException {
return JSON.getGson().fromJson(jsonString, {{{classname}}}.class);
}
/**
* Convert an instance of {{classname}} to an JSON string
*
* @return JSON string
*/
public String toJson() {
return JSON.getGson().toJson(this);
}
/**
* Convert an instance of {{classname}} to an JSON string
*
* @return JSON string
*/
public String toJson() {
return JSON.getGson().toJson(this);
}
}

View File

@@ -260,7 +260,7 @@ public interface {{classname}} {
}
// Override this method
{{#jdk8-default-interface}}default {{/jdk8-default-interface}} {{>responseType}} {{operationId}}({{#allParams}}{{^isFile}}{{^isBodyParam}}{{>optionalDataType}}{{/isBodyParam}}{{#isBodyParam}}{{^reactive}}{{{dataType}}}{{/reactive}}{{#reactive}}{{^isArray}}Mono<{{{dataType}}}>{{/isArray}}{{#isArray}}Flux<{{{baseType}}}>{{/isArray}}{{/reactive}}{{/isBodyParam}}{{/isFile}}{{#isFile}}{{#reactive}}Flux<Part>{{/reactive}}{{^reactive}}MultipartFile{{/reactive}}{{/isFile}} {{paramName}}{{^-last}}, {{/-last}}{{/allParams}}{{#reactive}}{{#hasParams}}, {{/hasParams}}{{#springFoxDocumentationProvider}}@ApiIgnore{{/springFoxDocumentationProvider}} final ServerWebExchange exchange{{/reactive}}{{#vendorExtensions.x-spring-paginated}}{{#hasParams}}, {{/hasParams}}{{^hasParams}}{{#reactive}}, {{/reactive}}{{/hasParams}}{{#springFoxDocumentationProvider}}@ApiIgnore{{/springFoxDocumentationProvider}}final Pageable pageable{{/vendorExtensions.x-spring-paginated}}){{#unhandledException}} throws Exception{{/unhandledException}} {
{{#jdk8-default-interface}}default {{/jdk8-default-interface}} {{>responseType}} {{operationId}}({{#allParams}}{{^isFile}}{{^isBodyParam}}{{>optionalDataType}}{{/isBodyParam}}{{#isBodyParam}}{{^reactive}}{{>optionalDataType}}{{/reactive}}{{#reactive}}{{^isArray}}Mono<{{{dataType}}}>{{/isArray}}{{#isArray}}Flux<{{{baseType}}}>{{/isArray}}{{/reactive}}{{/isBodyParam}}{{/isFile}}{{#isFile}}{{#reactive}}Flux<Part>{{/reactive}}{{^reactive}}MultipartFile{{/reactive}}{{/isFile}} {{paramName}}{{^-last}}, {{/-last}}{{/allParams}}{{#reactive}}{{#hasParams}}, {{/hasParams}}{{#springFoxDocumentationProvider}}@ApiIgnore{{/springFoxDocumentationProvider}} final ServerWebExchange exchange{{/reactive}}{{#vendorExtensions.x-spring-paginated}}{{#hasParams}}, {{/hasParams}}{{^hasParams}}{{#reactive}}, {{/reactive}}{{/hasParams}}{{#springFoxDocumentationProvider}}@ApiIgnore{{/springFoxDocumentationProvider}}final Pageable pageable{{/vendorExtensions.x-spring-paginated}}){{#unhandledException}} throws Exception{{/unhandledException}} {
{{/delegate-method}}
{{^isDelegate}}
{{>methodBody}}

View File

@@ -66,7 +66,7 @@ public interface {{classname}}Delegate {
{{#isDeprecated}}
@Deprecated
{{/isDeprecated}}
{{#jdk8-default-interface}}default {{/jdk8-default-interface}}{{>responseType}} {{operationId}}({{#allParams}}{{^isFile}}{{^isBodyParam}}{{>optionalDataType}}{{/isBodyParam}}{{#isBodyParam}}{{^reactive}}{{{dataType}}}{{/reactive}}{{#reactive}}{{^isArray}}Mono<{{{dataType}}}>{{/isArray}}{{#isArray}}Flux<{{{baseType}}}>{{/isArray}}{{/reactive}}{{/isBodyParam}}{{/isFile}}{{#isFile}}{{#isArray}}List<{{/isArray}}{{#reactive}}Flux<Part>{{/reactive}}{{^reactive}}MultipartFile{{/reactive}}{{#isArray}}>{{/isArray}}{{/isFile}} {{paramName}}{{^-last}},
{{#jdk8-default-interface}}default {{/jdk8-default-interface}}{{>responseType}} {{operationId}}({{#allParams}}{{^isFile}}{{^isBodyParam}}{{>optionalDataType}}{{/isBodyParam}}{{#isBodyParam}}{{^reactive}}{{>optionalDataType}}{{/reactive}}{{#reactive}}{{^isArray}}Mono<{{{dataType}}}>{{/isArray}}{{#isArray}}Flux<{{{baseType}}}>{{/isArray}}{{/reactive}}{{/isBodyParam}}{{/isFile}}{{#isFile}}{{#isArray}}List<{{/isArray}}{{#reactive}}Flux<Part>{{/reactive}}{{^reactive}}MultipartFile{{/reactive}}{{#isArray}}>{{/isArray}}{{/isFile}} {{paramName}}{{^-last}},
{{/-last}}{{/allParams}}{{#reactive}}{{#hasParams}},
{{/hasParams}}ServerWebExchange exchange{{/reactive}}{{#vendorExtensions.x-spring-paginated}}{{#hasParams}}, {{/hasParams}}{{^hasParams}}{{#reactive}}, {{/reactive}}{{/hasParams}}final Pageable pageable{{/vendorExtensions.x-spring-paginated}}){{#unhandledException}} throws Exception{{/unhandledException}}{{^jdk8-default-interface}};{{/jdk8-default-interface}}{{#jdk8-default-interface}} {
{{>methodBody}}

View File

@@ -115,6 +115,7 @@ org.openapitools.codegen.languages.RustClientCodegen
org.openapitools.codegen.languages.RustServerCodegen
org.openapitools.codegen.languages.ScalatraServerCodegen
org.openapitools.codegen.languages.ScalaAkkaClientCodegen
org.openapitools.codegen.languages.ScalaCaskServerCodegen
org.openapitools.codegen.languages.ScalaPekkoClientCodegen
org.openapitools.codegen.languages.ScalaAkkaHttpServerCodegen
org.openapitools.codegen.languages.ScalaFinchServerCodegen

View File

@@ -158,7 +158,7 @@ using System.Runtime.CompilerServices;
/// <param name="obj">The parameter (header, path, query, form).</param>
/// <param name="format">The DateTime serialization format.</param>
/// <returns>Formatted string.</returns>
public static string{{nrt?}} ParameterToString(object obj, string{{nrt?}} format = ISO8601_DATETIME_FORMAT)
public static string{{nrt?}} ParameterToString(object{{nrt?}} obj, string{{nrt?}} format = ISO8601_DATETIME_FORMAT)
{
if (obj is DateTime dateTime)
// Return a formatted date string - Can be customized with Configuration.DateTimeFormat

View File

@@ -423,9 +423,7 @@ namespace {{packageName}}.{{apiPackage}}
{{#-first}}
{{/-first}}
{{/required}}
{{#required}}
parseQueryStringLocalVar["{{baseName}}"] = {{paramName}}{{#isNullable}}{{nrt?}}{{^nrt}}{{#vendorExtensions.x-is-value-type}}?{{/vendorExtensions.x-is-value-type}}{{/nrt}}{{/isNullable}}.ToString();
parseQueryStringLocalVar["{{baseName}}"] = ClientUtils.ParameterToString({{paramName}});
{{/required}}
{{/queryParams}}
@@ -438,7 +436,8 @@ namespace {{packageName}}.{{apiPackage}}
{{#queryParams}}
{{^required}}
if ({{paramName}}.IsSet)
parseQueryStringLocalVar["{{baseName}}"] = {{paramName}}.Value{{#isNullable}}{{nrt?}}{{^nrt}}{{#vendorExtensions.x-is-value-type}}?{{/vendorExtensions.x-is-value-type}}{{/nrt}}{{/isNullable}}.ToString();
// here too
parseQueryStringLocalVar["{{baseName}}"] = ClientUtils.ParameterToString({{paramName}}.Value);
{{/required}}
{{#-last}}

View File

@@ -1,3 +1,5 @@
// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT.
/*
{{#appName}}
* {{{.}}}
@@ -13,5 +15,4 @@
{{#infoEmail}}
* Contact: {{{.}}}
{{/infoEmail}}
* Generated by: OpenAPI Generator (https://openapi-generator.tech)
*/

View File

@@ -3,16 +3,14 @@ var _ MappedNullable = &{{classname}}{}
// {{classname}} {{{description}}}{{^description}}struct for {{{classname}}}{{/description}}
type {{classname}} struct {
{{#parent}}
{{^isMap}}
{{#parentModel.name}}
{{^isArray}}
{{{parent}}}
{{{parentModel.name}}}
{{/isArray}}
{{/isMap}}
{{#isArray}}
Items {{{parent}}}
Items {{{parentModel.name}}}
{{/isArray}}
{{/parent}}
{{/parentModel.name}}
{{#vars}}
{{^-first}}
{{/-first}}

View File

@@ -445,48 +445,49 @@
<div class="tab-content" id="responses-{{baseName}}-{{nickname}}-{{code}}-wrapper" style='margin-bottom: 10px;'>
{{#schema}}
<div class="tab-pane active" id="responses-{{baseName}}-{{nickname}}-{{code}}-schema">
<div id="responses-{{baseName}}-{{nickname}}-schema-{{code}}" class="exampleStyle">
<script>
$(document).ready(function() {
var schemaWrapper = {{{jsonSchema}}};
var schema = findNode('schema',schemaWrapper).schema;
if (!schema) {
schema = schemaWrapper.schema;
}
if (schema.$ref != null) {
schema = defsParser.$refs.get(schema.$ref);
Object.keys(schema.properties).forEach( (item) => {
if (schema.properties[item].$ref != null) {
schema.properties[item] = defsParser.$refs.get(schema.properties[item].$ref);
}
});
} else if (schema.items != null && schema.items.$ref != null) {
schema.items = defsParser.$refs.get(schema.items.$ref);
} else {
schemaWrapper.definitions = Object.assign({}, defs);
$RefParser.dereference(schemaWrapper).catch(function(err) {
console.log(err);
});
}
<div class="tab-pane active" id="responses-{{baseName}}-{{nickname}}-{{code}}-schema">
<div id="responses-{{baseName}}-{{nickname}}-schema-{{code}}" class="exampleStyle">
<script>
$(document).ready(function() {
var schemaWrapper = {{{jsonSchema}}};
var schema = findNode('schema',schemaWrapper).schema;
if (!schema) {
schema = schemaWrapper.schema;
}
if (schema == null) {
return;
}
if (schema.$ref != null) {
schema = defsParser.$refs.get(schema.$ref);
Object.keys(schema.properties).forEach( (item) => {
if (schema.properties[item].$ref != null) {
schema.properties[item] = defsParser.$refs.get(schema.properties[item].$ref);
}
});
} else if (schema.items != null && schema.items.$ref != null) {
schema.items = defsParser.$refs.get(schema.items.$ref);
} else {
schemaWrapper.definitions = Object.assign({}, defs);
$RefParser.dereference(schemaWrapper).catch(function(err) {
console.log(err);
});
}
var view = new JSONSchemaView(schema, 3);
$('#responses-{{baseName}}-{{nickname}}-{{code}}-schema-data').val(JSON.stringify(schema));
var result = $('#responses-{{baseName}}-{{nickname}}-schema-{{code}}');
result.empty();
result.append(view.render());
});
</script>
</div>
<input id='responses-{{baseName}}-{{nickname}}-{{code}}-schema-data' type='hidden' value=''></input>
var view = new JSONSchemaView(schema, 3);
$('#responses-{{baseName}}-{{nickname}}-{{code}}-schema-data').val(JSON.stringify(schema));
var result = $('#responses-{{baseName}}-{{nickname}}-schema-{{code}}');
result.empty();
result.append(view.render());
});
</script>
</div>
{{#examples}}
<div class="tab-pane" id="examples-{{baseName}}-{{nickname}}-{{code}}-example">
<pre class="prettyprint"><code class="json">{{example}}</code></pre>
</div>
{{/examples}}
{{/schema}}
<input id='responses-{{baseName}}-{{nickname}}-{{code}}-schema-data' type='hidden' value=''></input>
</div>
{{#examples}}
<div class="tab-pane" id="examples-{{baseName}}-{{nickname}}-{{code}}-example">
<pre class="prettyprint"><code class="json">{{example}}</code></pre>
</div>
{{/examples}}
{{#hasHeaders}}
<div class="tab-pane" id="responses-{{nickname}}-{{code}}-headers">
<table>

View File

@@ -30,7 +30,7 @@ interface {{classname}}Delegate {
/**
* @see {{classname}}#{{operationId}}
*/
{{#reactive}}{{^isArray}}suspend {{/isArray}}{{/reactive}}fun {{operationId}}({{#allParams}}{{paramName}}: {{^isFile}}{{^reactive}}{{>optionalDataType}}{{/reactive}}{{#reactive}}{{^isArray}}{{>optionalDataType}}{{/isArray}}{{#isArray}}{{#isBodyParam}}Flow<{{{baseType}}}>{{/isBodyParam}}{{^isBodyParam}}{{>optionalDataType}}{{/isBodyParam}}{{/isArray}}{{/reactive}}{{/isFile}}{{#isFile}}Resource?{{/isFile}}{{^-last}},
{{#reactive}}{{^isArray}}suspend {{/isArray}}{{/reactive}}fun {{operationId}}({{#allParams}}{{{paramName}}}: {{^isFile}}{{^reactive}}{{>optionalDataType}}{{/reactive}}{{#reactive}}{{^isArray}}{{>optionalDataType}}{{/isArray}}{{#isArray}}{{#isBodyParam}}Flow<{{{baseType}}}>{{/isBodyParam}}{{^isBodyParam}}{{>optionalDataType}}{{/isBodyParam}}{{/isArray}}{{/reactive}}{{/isFile}}{{#isFile}}Resource?{{/isFile}}{{^-last}},
{{/-last}}{{/allParams}}): {{#responseWrapper}}{{.}}<{{/responseWrapper}}ResponseEntity<{{>returnTypes}}>{{#responseWrapper}}>{{/responseWrapper}} {
{{>methodBody}}
}

View File

@@ -107,7 +107,7 @@ interface {{classname}} {
return {{>returnValue}}
{{/isDelegate}}
{{#isDelegate}}
return getDelegate().{{operationId}}({{#allParams}}{{paramName}}{{^-last}}, {{/-last}}{{/allParams}})
return getDelegate().{{operationId}}({{#allParams}}{{{paramName}}}{{^-last}}, {{/-last}}{{/allParams}})
{{/isDelegate}}
}{{/skipDefaultInterface}}
{{/operation}}

View File

@@ -1 +1 @@
{{#isCookieParam}}{{#useBeanValidation}}{{>beanValidationQueryParams}}{{/useBeanValidation}}@CookieValue(name = "{{baseName}}"{{^required}}, required = false{{/required}}{{#defaultValue}}, defaultValue = "{{{.}}}"{{/defaultValue}}) {{paramName}}: {{>optionalDataType}}{{/isCookieParam}}
{{#isCookieParam}}{{#useBeanValidation}}{{>beanValidationQueryParams}}{{/useBeanValidation}}@CookieValue(name = "{{baseName}}"{{^required}}, required = false{{/required}}{{#defaultValue}}, defaultValue = "{{{.}}}"{{/defaultValue}}) {{{paramName}}}: {{>optionalDataType}}{{/isCookieParam}}

View File

@@ -5,6 +5,9 @@
{{/vars}}
*/{{#discriminator}}
{{>typeInfoAnnotation}}{{/discriminator}}
{{#additionalModelTypeAnnotations}}
{{{.}}}
{{/additionalModelTypeAnnotations}}
{{#discriminator}}interface {{classname}}{{/discriminator}}{{^discriminator}}{{#hasVars}}data {{/hasVars}}class {{classname}}(
{{#requiredVars}}
{{>dataClassReqVar}}{{^-last}},

View File

@@ -1 +1 @@
{{#isFormParam}}{{^isFile}}{{#swagger2AnnotationLibrary}}@Parameter(description = "{{{description}}}"{{#required}}, required = true{{/required}}{{#allowableValues}}{{#defaultValue}}, schema = Schema(allowableValues = [{{#values}}"{{{.}}}"{{^-last}}, {{/-last}}{{/values}}]{{^isContainer}}, defaultValue = {{^isString}}"{{/isString}}{{#isString}}{{#isEnum}}"{{/isEnum}}{{/isString}}{{{defaultValue}}}{{^isString}}"{{/isString}}{{#isString}}{{#isEnum}}"{{/isEnum}}{{/isString}}{{/isContainer}}){{/defaultValue}}{{/allowableValues}}{{#allowableValues}}{{^defaultValue}}, schema = Schema(allowableValues = [{{#values}}"{{{.}}}"{{^-last}}, {{/-last}}{{/values}}]){{/defaultValue}}{{/allowableValues}}{{^allowableValues}}{{#defaultValue}}{{^isContainer}}, schema = Schema(defaultValue = {{^isString}}"{{/isString}}{{#isString}}{{#isEnum}}"{{/isEnum}}{{/isString}}{{{defaultValue}}}{{^isString}}"{{/isString}}{{#isString}}{{#isEnum}}"{{/isEnum}}{{/isString}}){{/isContainer}}{{/defaultValue}}{{/allowableValues}}){{/swagger2AnnotationLibrary}}{{#swagger1AnnotationLibrary}}@ApiParam(value = "{{{description}}}"{{#required}}, required = true{{/required}}{{#allowableValues}}, allowableValues = "{{#values}}{{{.}}}{{^-last}}, {{/-last}}{{/values}}"{{/allowableValues}}{{#defaultValue}}, defaultValue = "{{{.}}}"{{/defaultValue}}){{/swagger1AnnotationLibrary}} @RequestParam(value = "{{baseName}}"{{#required}}, required = true{{/required}}{{^required}}, required = false{{/required}}) {{paramName}}: {{>optionalDataType}} {{/isFile}}{{#isFile}}{{#swagger2AnnotationLibrary}}@Parameter(description = "{{{description}}}"){{/swagger2AnnotationLibrary}}{{#swagger1AnnotationLibrary}}@ApiParam(value = "file detail"){{/swagger1AnnotationLibrary}} {{#useBeanValidation}}@Valid{{/useBeanValidation}} @RequestPart("{{baseName}}"{{#required}}, required = true{{/required}}{{^required}}, required = false{{/required}}) {{paramName}}: {{>optionalDataType}}{{/isFile}}{{/isFormParam}}
{{#isFormParam}}{{^isFile}}{{#swagger2AnnotationLibrary}}@Parameter(description = "{{{description}}}"{{#required}}, required = true{{/required}}{{#allowableValues}}{{#defaultValue}}, schema = Schema(allowableValues = [{{#values}}"{{{.}}}"{{^-last}}, {{/-last}}{{/values}}]{{^isContainer}}, defaultValue = {{^isString}}"{{/isString}}{{#isString}}{{#isEnum}}"{{/isEnum}}{{/isString}}{{{defaultValue}}}{{^isString}}"{{/isString}}{{#isString}}{{#isEnum}}"{{/isEnum}}{{/isString}}{{/isContainer}}){{/defaultValue}}{{/allowableValues}}{{#allowableValues}}{{^defaultValue}}, schema = Schema(allowableValues = [{{#values}}"{{{.}}}"{{^-last}}, {{/-last}}{{/values}}]){{/defaultValue}}{{/allowableValues}}{{^allowableValues}}{{#defaultValue}}{{^isContainer}}, schema = Schema(defaultValue = {{^isString}}"{{/isString}}{{#isString}}{{#isEnum}}"{{/isEnum}}{{/isString}}{{{defaultValue}}}{{^isString}}"{{/isString}}{{#isString}}{{#isEnum}}"{{/isEnum}}{{/isString}}){{/isContainer}}{{/defaultValue}}{{/allowableValues}}){{/swagger2AnnotationLibrary}}{{#swagger1AnnotationLibrary}}@ApiParam(value = "{{{description}}}"{{#required}}, required = true{{/required}}{{#allowableValues}}, allowableValues = "{{#values}}{{{.}}}{{^-last}}, {{/-last}}{{/values}}"{{/allowableValues}}{{#defaultValue}}, defaultValue = "{{{.}}}"{{/defaultValue}}){{/swagger1AnnotationLibrary}} @RequestParam(value = "{{baseName}}"{{#required}}, required = true{{/required}}{{^required}}, required = false{{/required}}) {{{paramName}}}: {{>optionalDataType}} {{/isFile}}{{#isFile}}{{#swagger2AnnotationLibrary}}@Parameter(description = "{{{description}}}"){{/swagger2AnnotationLibrary}}{{#swagger1AnnotationLibrary}}@ApiParam(value = "file detail"){{/swagger1AnnotationLibrary}} {{#useBeanValidation}}@Valid{{/useBeanValidation}} @RequestPart("{{baseName}}"{{#required}}, required = true{{/required}}{{^required}}, required = false{{/required}}) {{{paramName}}}: {{>optionalDataType}}{{/isFile}}{{/isFormParam}}

View File

@@ -1 +1 @@
{{#isHeaderParam}}{{#useBeanValidation}}{{>beanValidationCore}}{{/useBeanValidation}}{{#swagger2AnnotationLibrary}}@Parameter(description = "{{{description}}}", `in` = ParameterIn.HEADER{{#required}}, required = true{{/required}}{{#allowableValues}}{{#defaultValue}}, schema = Schema(allowableValues = [{{#values}}"{{{.}}}"{{^-last}}, {{/-last}}{{/values}}]{{^isContainer}}, defaultValue = {{^isString}}"{{/isString}}{{#isString}}{{#isEnum}}"{{/isEnum}}{{/isString}}{{{defaultValue}}}{{^isString}}"{{/isString}}{{#isString}}{{#isEnum}}"{{/isEnum}}{{/isString}}{{/isContainer}}){{/defaultValue}}{{/allowableValues}}{{#allowableValues}}{{^defaultValue}}, schema = Schema(allowableValues = [{{#values}}"{{{.}}}"{{^-last}}, {{/-last}}{{/values}}]){{/defaultValue}}{{/allowableValues}}{{^allowableValues}}{{#defaultValue}}{{^isContainer}}, schema = Schema(defaultValue = {{^isString}}"{{/isString}}{{#isString}}{{#isEnum}}"{{/isEnum}}{{/isString}}{{{defaultValue}}}{{^isString}}"{{/isString}}{{#isString}}{{#isEnum}}"{{/isEnum}}{{/isString}}){{/isContainer}}{{/defaultValue}}{{/allowableValues}}){{/swagger2AnnotationLibrary}}{{#swagger1AnnotationLibrary}}@ApiParam(value = "{{{description}}}"{{#required}}, required = true{{/required}}{{#allowableValues}}, allowableValues = "{{#values}}{{{.}}}{{^-last}}, {{/-last}}{{/values}}"{{/allowableValues}}{{#defaultValue}}, defaultValue = "{{{.}}}"{{/defaultValue}}){{/swagger1AnnotationLibrary}} @RequestHeader(value = "{{baseName}}", required = {{#required}}true{{/required}}{{^required}}false{{/required}}) {{paramName}}: {{>optionalDataType}}{{/isHeaderParam}}
{{#isHeaderParam}}{{#useBeanValidation}}{{>beanValidationCore}}{{/useBeanValidation}}{{#swagger2AnnotationLibrary}}@Parameter(description = "{{{description}}}", `in` = ParameterIn.HEADER{{#required}}, required = true{{/required}}{{#allowableValues}}{{#defaultValue}}, schema = Schema(allowableValues = [{{#values}}"{{{.}}}"{{^-last}}, {{/-last}}{{/values}}]{{^isContainer}}, defaultValue = {{^isString}}"{{/isString}}{{#isString}}{{#isEnum}}"{{/isEnum}}{{/isString}}{{{defaultValue}}}{{^isString}}"{{/isString}}{{#isString}}{{#isEnum}}"{{/isEnum}}{{/isString}}{{/isContainer}}){{/defaultValue}}{{/allowableValues}}{{#allowableValues}}{{^defaultValue}}, schema = Schema(allowableValues = [{{#values}}"{{{.}}}"{{^-last}}, {{/-last}}{{/values}}]){{/defaultValue}}{{/allowableValues}}{{^allowableValues}}{{#defaultValue}}{{^isContainer}}, schema = Schema(defaultValue = {{^isString}}"{{/isString}}{{#isString}}{{#isEnum}}"{{/isEnum}}{{/isString}}{{{defaultValue}}}{{^isString}}"{{/isString}}{{#isString}}{{#isEnum}}"{{/isEnum}}{{/isString}}){{/isContainer}}{{/defaultValue}}{{/allowableValues}}){{/swagger2AnnotationLibrary}}{{#swagger1AnnotationLibrary}}@ApiParam(value = "{{{description}}}"{{#required}}, required = true{{/required}}{{#allowableValues}}, allowableValues = "{{#values}}{{{.}}}{{^-last}}, {{/-last}}{{/values}}"{{/allowableValues}}{{#defaultValue}}, defaultValue = "{{{.}}}"{{/defaultValue}}){{/swagger1AnnotationLibrary}} @RequestHeader(value = "{{baseName}}", required = {{#required}}true{{/required}}{{^required}}false{{/required}}) {{{paramName}}}: {{>optionalDataType}}{{/isHeaderParam}}

View File

@@ -1 +1 @@
{{#isPathParam}}{{#useBeanValidation}}{{>beanValidationPathParams}}{{/useBeanValidation}}{{#swagger2AnnotationLibrary}}@Parameter(description = "{{{description}}}"{{#required}}, required = true{{/required}}{{#allowableValues}}{{#defaultValue}}, schema = Schema(allowableValues = [{{#enumVars}}"{{#lambdaEscapeInNormalString}}{{{value}}}{{/lambdaEscapeInNormalString}}"{{^-last}}, {{/-last}}{{/enumVars}}]{{^isContainer}}, defaultValue = {{^isString}}"{{/isString}}{{#isString}}{{#isEnum}}"{{/isEnum}}{{/isString}}{{{defaultValue}}}{{^isString}}"{{/isString}}{{#isString}}{{#isEnum}}"{{/isEnum}}{{/isString}}{{/isContainer}}{{/defaultValue}}{{/allowableValues}}{{#allowableValues}}{{^defaultValue}}, schema = Schema(allowableValues = [{{#enumVars}}"{{#lambdaEscapeInNormalString}}{{{value}}}{{/lambdaEscapeInNormalString}}"{{^-last}}, {{/-last}}{{/enumVars}}]){{/defaultValue}}{{/allowableValues}}{{^allowableValues}}{{#defaultValue}}{{^isContainer}}, schema = Schema(defaultValue = {{^isString}}"{{/isString}}{{#isString}}{{#isEnum}}"{{/isEnum}}{{/isString}}{{{defaultValue}}}{{^isString}}"{{/isString}}{{#isString}}{{#isEnum}}"{{/isEnum}}{{/isString}}{{/isContainer}}{{/defaultValue}}{{/allowableValues}}){{/swagger2AnnotationLibrary}}{{#swagger1AnnotationLibrary}}@ApiParam(value = "{{{description}}}"{{#required}}, required = true{{/required}}{{#allowableValues}}, allowableValues = "{{#enumVars}}{{#lambda.escapeDoubleQuote}}{{{value}}}{{/lambda.escapeDoubleQuote}}{{^-last}}, {{/-last}}{{/enumVars}}"{{/allowableValues}}{{#defaultValue}}, defaultValue = "{{{.}}}"{{/defaultValue}}){{/swagger1AnnotationLibrary}} @PathVariable("{{baseName}}") {{paramName}}: {{>optionalDataType}}{{/isPathParam}}
{{#isPathParam}}{{#useBeanValidation}}{{>beanValidationPathParams}}{{/useBeanValidation}}{{#swagger2AnnotationLibrary}}@Parameter(description = "{{{description}}}"{{#required}}, required = true{{/required}}{{#allowableValues}}{{#defaultValue}}, schema = Schema(allowableValues = [{{#enumVars}}"{{#lambdaEscapeInNormalString}}{{{value}}}{{/lambdaEscapeInNormalString}}"{{^-last}}, {{/-last}}{{/enumVars}}]{{^isContainer}}, defaultValue = {{^isString}}"{{/isString}}{{#isString}}{{#isEnum}}"{{/isEnum}}{{/isString}}{{{defaultValue}}}{{^isString}}"{{/isString}}{{#isString}}{{#isEnum}}"{{/isEnum}}{{/isString}}{{/isContainer}}{{/defaultValue}}{{/allowableValues}}{{#allowableValues}}{{^defaultValue}}, schema = Schema(allowableValues = [{{#enumVars}}"{{#lambdaEscapeInNormalString}}{{{value}}}{{/lambdaEscapeInNormalString}}"{{^-last}}, {{/-last}}{{/enumVars}}]){{/defaultValue}}{{/allowableValues}}{{^allowableValues}}{{#defaultValue}}{{^isContainer}}, schema = Schema(defaultValue = {{^isString}}"{{/isString}}{{#isString}}{{#isEnum}}"{{/isEnum}}{{/isString}}{{{defaultValue}}}{{^isString}}"{{/isString}}{{#isString}}{{#isEnum}}"{{/isEnum}}{{/isString}}{{/isContainer}}{{/defaultValue}}{{/allowableValues}}){{/swagger2AnnotationLibrary}}{{#swagger1AnnotationLibrary}}@ApiParam(value = "{{{description}}}"{{#required}}, required = true{{/required}}{{#allowableValues}}, allowableValues = "{{#enumVars}}{{#lambda.escapeDoubleQuote}}{{{value}}}{{/lambda.escapeDoubleQuote}}{{^-last}}, {{/-last}}{{/enumVars}}"{{/allowableValues}}{{#defaultValue}}, defaultValue = "{{{.}}}"{{/defaultValue}}){{/swagger1AnnotationLibrary}} @PathVariable("{{baseName}}") {{{paramName}}}: {{>optionalDataType}}{{/isPathParam}}

View File

@@ -1 +1 @@
{{#isQueryParam}}{{#useBeanValidation}}{{>beanValidationQueryParams}}{{/useBeanValidation}}{{#swagger2AnnotationLibrary}}@Parameter(description = "{{{description}}}"{{#required}}, required = true{{/required}}{{#allowableValues}}{{#defaultValue}}, schema = Schema(allowableValues = [{{#values}}"{{{.}}}"{{^-last}}, {{/-last}}{{/values}}]{{^isContainer}}, defaultValue = {{^isString}}"{{/isString}}{{#isString}}{{#isEnum}}"{{/isEnum}}{{/isString}}{{{defaultValue}}}{{^isString}}"{{/isString}}{{#isString}}{{#isEnum}}"{{/isEnum}}{{/isString}}{{/isContainer}}){{/defaultValue}}{{/allowableValues}}{{#allowableValues}}{{^defaultValue}}, schema = Schema(allowableValues = [{{#values}}"{{{.}}}"{{^-last}}, {{/-last}}{{/values}}]){{/defaultValue}}{{/allowableValues}}{{^allowableValues}}{{#defaultValue}}{{^isContainer}}, schema = Schema(defaultValue = {{^isString}}"{{/isString}}{{#isString}}{{#isEnum}}"{{/isEnum}}{{/isString}}{{{defaultValue}}}{{^isString}}"{{/isString}}{{#isString}}{{#isEnum}}"{{/isEnum}}{{/isString}}){{/isContainer}}{{/defaultValue}}{{/allowableValues}}){{/swagger2AnnotationLibrary}}{{#swagger1AnnotationLibrary}}@ApiParam(value = "{{{description}}}"{{#required}}, required = true{{/required}}{{#allowableValues}}, allowableValues = "{{#values}}{{{.}}}{{^-last}}, {{/-last}}{{/values}}"{{/allowableValues}}{{^isContainer}}{{#defaultValue}}, defaultValue = {{^isString}}"{{/isString}}{{#isString}}{{#isEnum}}"{{/isEnum}}{{/isString}}{{{defaultValue}}}{{^isString}}"{{/isString}}{{#isString}}{{#isEnum}}"{{/isEnum}}{{/isString}}{{/defaultValue}}{{/isContainer}}){{/swagger1AnnotationLibrary}}{{#useBeanValidation}} @Valid{{/useBeanValidation}}{{^isModel}} @RequestParam(value = "{{baseName}}"{{#required}}, required = true{{/required}}{{^required}}, required = false{{/required}}{{^isContainer}}{{#defaultValue}}, defaultValue = {{^isString}}"{{/isString}}{{#isString}}{{#isEnum}}"{{/isEnum}}{{/isString}}{{{defaultValue}}}{{^isString}}"{{/isString}}{{#isString}}{{#isEnum}}"{{/isEnum}}{{/isString}}{{/defaultValue}}{{/isContainer}}){{/isModel}}{{#isDate}} @org.springframework.format.annotation.DateTimeFormat(iso = org.springframework.format.annotation.DateTimeFormat.ISO.DATE){{/isDate}}{{#isDateTime}} @org.springframework.format.annotation.DateTimeFormat(iso = org.springframework.format.annotation.DateTimeFormat.ISO.DATE_TIME){{/isDateTime}} {{paramName}}: {{>optionalDataType}}{{/isQueryParam}}
{{#isQueryParam}}{{#useBeanValidation}}{{>beanValidationQueryParams}}{{/useBeanValidation}}{{#swagger2AnnotationLibrary}}@Parameter(description = "{{{description}}}"{{#required}}, required = true{{/required}}{{#allowableValues}}{{#defaultValue}}, schema = Schema(allowableValues = [{{#values}}"{{{.}}}"{{^-last}}, {{/-last}}{{/values}}]{{^isContainer}}, defaultValue = {{^isString}}"{{/isString}}{{#isString}}{{#isEnum}}"{{/isEnum}}{{/isString}}{{{defaultValue}}}{{^isString}}"{{/isString}}{{#isString}}{{#isEnum}}"{{/isEnum}}{{/isString}}{{/isContainer}}){{/defaultValue}}{{/allowableValues}}{{#allowableValues}}{{^defaultValue}}, schema = Schema(allowableValues = [{{#values}}"{{{.}}}"{{^-last}}, {{/-last}}{{/values}}]){{/defaultValue}}{{/allowableValues}}{{^allowableValues}}{{#defaultValue}}{{^isContainer}}, schema = Schema(defaultValue = {{^isString}}"{{/isString}}{{#isString}}{{#isEnum}}"{{/isEnum}}{{/isString}}{{{defaultValue}}}{{^isString}}"{{/isString}}{{#isString}}{{#isEnum}}"{{/isEnum}}{{/isString}}){{/isContainer}}{{/defaultValue}}{{/allowableValues}}){{/swagger2AnnotationLibrary}}{{#swagger1AnnotationLibrary}}@ApiParam(value = "{{{description}}}"{{#required}}, required = true{{/required}}{{#allowableValues}}, allowableValues = "{{#values}}{{{.}}}{{^-last}}, {{/-last}}{{/values}}"{{/allowableValues}}{{^isContainer}}{{#defaultValue}}, defaultValue = {{^isString}}"{{/isString}}{{#isString}}{{#isEnum}}"{{/isEnum}}{{/isString}}{{{defaultValue}}}{{^isString}}"{{/isString}}{{#isString}}{{#isEnum}}"{{/isEnum}}{{/isString}}{{/defaultValue}}{{/isContainer}}){{/swagger1AnnotationLibrary}}{{#useBeanValidation}} @Valid{{/useBeanValidation}}{{^isModel}} @RequestParam(value = "{{baseName}}"{{#required}}, required = true{{/required}}{{^required}}, required = false{{/required}}{{^isContainer}}{{#defaultValue}}, defaultValue = {{^isString}}"{{/isString}}{{#isString}}{{#isEnum}}"{{/isEnum}}{{/isString}}{{{defaultValue}}}{{^isString}}"{{/isString}}{{#isString}}{{#isEnum}}"{{/isEnum}}{{/isString}}{{/defaultValue}}{{/isContainer}}){{/isModel}}{{#isDate}} @org.springframework.format.annotation.DateTimeFormat(iso = org.springframework.format.annotation.DateTimeFormat.ISO.DATE){{/isDate}}{{#isDateTime}} @org.springframework.format.annotation.DateTimeFormat(iso = org.springframework.format.annotation.DateTimeFormat.ISO.DATE_TIME){{/isDateTime}} {{{paramName}}}: {{>optionalDataType}}{{/isQueryParam}}

View File

@@ -11,7 +11,7 @@ import org.springframework.stereotype.Service
class {{classname}}ServiceImpl : {{classname}}Service {
{{#operation}}
override {{#reactive}}{{^isArray}}suspend {{/isArray}}{{/reactive}}fun {{operationId}}({{#allParams}}{{paramName}}: {{^isBodyParam}}{{>optionalDataType}}{{/isBodyParam}}{{#isBodyParam}}{{^reactive}}{{>optionalDataType}}{{/reactive}}{{#reactive}}{{^isArray}}{{>optionalDataType}}{{/isArray}}{{#isArray}}Flow<{{{baseType}}}>{{/isArray}}{{/reactive}}{{/isBodyParam}}{{^-last}}, {{/-last}}{{/allParams}}): {{>returnTypes}} {
override {{#reactive}}{{^isArray}}suspend {{/isArray}}{{/reactive}}fun {{operationId}}({{#allParams}}{{{paramName}}}: {{^isBodyParam}}{{>optionalDataType}}{{/isBodyParam}}{{#isBodyParam}}{{^reactive}}{{>optionalDataType}}{{/reactive}}{{#reactive}}{{^isArray}}{{>optionalDataType}}{{/isArray}}{{#isArray}}Flow<{{{baseType}}}>{{/isArray}}{{/reactive}}{{/isBodyParam}}{{^-last}}, {{/-last}}{{/allParams}}): {{>returnTypes}} {
TODO("Implement me")
}
{{/operation}}

View File

@@ -377,7 +377,6 @@ class ObjectSerializer
* @param mixed $data object or primitive to be deserialized
* @param string $class class name is passed as a string
* @param string[]|null $httpHeaders HTTP headers
* @param string|null $discriminator discriminator if polymorphism is used
*
* @return mixed a single or an array of $class instances
*/

View File

@@ -92,7 +92,7 @@ class Controller extends AbstractController
$json = $this->exceptionToArray($exception);
$json['statusCode'] = $statusCode;
return new Response(json_encode($json, 15, 512), $statusCode, $headers);
return new Response(json_encode($json, 15), $statusCode, $headers);
}
/**
@@ -219,7 +219,7 @@ class Controller extends AbstractController
public static function isContentTypeAllowed(Request $request, array $consumes = []): bool
{
if (!empty($consumes) && $consumes[0] !== '*/*') {
$currentFormat = $request->getContentType();
$currentFormat = $request->getContentTypeFormat();
foreach ($consumes as $mimeType) {
// canonize mime type
if (is_string($mimeType) && false !== $pos = strpos($mimeType, ';')) {
@@ -230,7 +230,7 @@ class Controller extends AbstractController
// add custom format to request
$format = $mimeType;
$request->setFormat($format, $format);
$currentFormat = $request->getContentType();
$currentFormat = $request->getContentTypeFormat();
}
if ($format === $currentFormat) {

View File

@@ -101,6 +101,10 @@ class {{controllerName}} extends Controller
// HTTP basic authentication required
$security{{name}} = $request->headers->get('authorization');
{{/isBasicBasic}}
{{#isBasicBearer}}
// HTTP bearer authentication required
$security{{name}} = $request->headers->get('authorization');
{{/isBasicBearer}}
{{#isOAuth}}
// Oauth required
$security{{name}} = $request->headers->get('authorization');
@@ -148,7 +152,7 @@ class {{controllerName}} extends Controller
{{#allParams}}
{{^isFile}}
{{#isBodyParam}}
$inputFormat = $request->getMimeType($request->getContentType());
$inputFormat = $request->getMimeType($request->getContentTypeFormat());
${{paramName}} = $this->deserialize(${{paramName}}, '{{#isContainer}}{{#items}}array<{{dataType}}>{{/items}}{{/isContainer}}{{^isContainer}}{{#isEnumRef}}\{{modelPackage}}\{{dataType}}{{/isEnumRef}}{{^isEnumRef}}{{dataType}}{{/isEnumRef}}{{/isContainer}}', $inputFormat);
{{/isBodyParam}}
{{^isBodyParam}}
@@ -178,17 +182,12 @@ class {{controllerName}} extends Controller
{{#returnType}}$result = {{/returnType}}$handler->{{operationId}}({{#allParams}}${{paramName}}, {{/allParams}}$responseCode, $responseHeaders);
// Find default response message
$message = '{{#responses}}{{#isDefault}}{{message}}{{/isDefault}}{{/responses}}';
// Find a more specific message, if available
switch ($responseCode) {
$message = match($responseCode) {
{{#responses}}
case {{code}}:
$message = '{{message}}';
break;
{{code}} => '{{message}}',
{{/responses}}
}
default => '{{#responses}}{{#isDefault}}{{message}}{{/isDefault}}{{/responses}}',
};
return new Response(
{{#returnType}}$result !== null ?$this->serialize($result, $responseFormat):''{{/returnType}}{{^returnType}}''{{/returnType}},

View File

@@ -24,19 +24,19 @@
}
],
"require": {
"php": ">=7.4.0|>=8.0.2",
"php": ">=8.1",
"ext-curl": "*",
"ext-json": "*",
"ext-mbstring": "*",
"symfony/validator": "^5.0|^6.0",
"jms/serializer-bundle": "^4.0",
"symfony/framework-bundle": "^5.0|^6.0"
"symfony/validator": "^6.4|^7.0",
"jms/serializer-bundle": "^5.4",
"symfony/framework-bundle": "^6.4|^7.0"
},
"require-dev": {
"phpunit/phpunit": "^9.5",
"friendsofphp/php-cs-fixer": "^2.16.3",
"symfony/browser-kit": "^5.0|^6.0",
"symfony/yaml": "^5.0|^6.0",
"phpunit/phpunit": "^10.5|^11.0",
"friendsofphp/php-cs-fixer": "*",
"symfony/browser-kit": "^6.4|7.0",
"symfony/yaml": "^6.4|^7.0",
"hoa/regex": "~1.0"
},
"autoload": {

View File

@@ -47,14 +47,11 @@ class JmsSerializer implements SerializerInterface
private function convertFormat(string $format): ?string
{
switch ($format) {
case 'application/json':
return 'json';
case 'application/xml':
return 'xml';
}
return null;
return match($format) {
'application/json' => 'json',
'application/xml' => 'xml',
default => null,
};
}
private function deserializeString($data, string $type)
@@ -132,22 +129,13 @@ class JmsSerializer implements SerializerInterface
}
// Parse the string using the correct separator
switch ($format) {
case 'csv':
$data = explode(',', $data);
break;
case 'ssv':
$data = explode(' ', $data);
break;
case 'tsv':
$data = explode("\t", $data);
break;
case 'pipes':
$data = explode('|', $data);
break;
default;
$data = [];
}
$data = match($format) {
'csv' => explode(',', $data),
'ssv' => explode(' ', $data),
'tsv' => explode("\t", $data),
'pipes' => explode('|', $data),
default => [],
};
// Deserialize each of the array elements
foreach ($data as $key => $item) {

View File

@@ -55,7 +55,7 @@ class ControllerTest extends TestCase
);
}
public function dataProviderIsContentTypeAllowed(): array
public static function dataProviderIsContentTypeAllowed(): array
{
return [
'usual JSON content type' => [

View File

@@ -387,7 +387,6 @@ class ObjectSerializer
* @param mixed $data object or primitive to be deserialized
* @param string $class class name is passed as a string
* @param string[] $httpHeaders HTTP headers
* @param string $discriminator discriminator if polymorphism is used
*
* @return object|array|null a single or an array of $class instances
*/

View File

@@ -26,7 +26,7 @@ print {{classname}}.to_json()
# convert the object into a dict
{{#lambda.snakecase}}{{classname}}{{/lambda.snakecase}}_dict = {{#lambda.snakecase}}{{classname}}{{/lambda.snakecase}}_instance.to_dict()
# create an instance of {{classname}} from a dict
{{#lambda.snakecase}}{{classname}}{{/lambda.snakecase}}_form_dict = {{#lambda.snakecase}}{{classname}}{{/lambda.snakecase}}.from_dict({{#lambda.snakecase}}{{classname}}{{/lambda.snakecase}}_dict)
{{#lambda.snakecase}}{{classname}}{{/lambda.snakecase}}_from_dict = {{classname}}.from_dict({{#lambda.snakecase}}{{classname}}{{/lambda.snakecase}}_dict)
```
{{/isEnum}}
[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md)

View File

@@ -5,7 +5,7 @@ async-generator==1.10
certifi==2023.7.22
chardet==4.0.0
click==7.1.2
dnspython==2.1.0
dnspython==2.6.1
email-validator==2.0.0
fastapi==0.109.2
graphene==2.1.8
@@ -14,7 +14,7 @@ graphql-relay==2.0.1
h11==0.12.0
httptools==0.1.2
httpx==0.24.1
idna==2.10
idna==3.7
itsdangerous==1.1.0
Jinja2==2.11.3
MarkupSafe==2.0.1

View File

@@ -25,7 +25,7 @@ print {{classname}}.to_json()
# convert the object into a dict
{{#lambda.snakecase}}{{classname}}{{/lambda.snakecase}}_dict = {{#lambda.snakecase}}{{classname}}{{/lambda.snakecase}}_instance.to_dict()
# create an instance of {{classname}} from a dict
{{#lambda.snakecase}}{{classname}}{{/lambda.snakecase}}_form_dict = {{#lambda.snakecase}}{{classname}}{{/lambda.snakecase}}.from_dict({{#lambda.snakecase}}{{classname}}{{/lambda.snakecase}}_dict)
{{#lambda.snakecase}}{{classname}}{{/lambda.snakecase}}_from_dict = {{classname}}.from_dict({{#lambda.snakecase}}{{classname}}{{/lambda.snakecase}}_dict)
```
{{/isEnum}}
[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md)

View File

@@ -358,6 +358,8 @@ class ApiClient:
"""
if obj is None:
return None
elif isinstance(obj, Enum):
return obj.value
elif isinstance(obj, SecretStr):
return obj.get_secret_value()
elif isinstance(obj, self.PRIMITIVE_TYPES):

View File

@@ -26,7 +26,7 @@ print({{classname}}.to_json())
# convert the object into a dict
{{#lambda.snakecase}}{{classname}}{{/lambda.snakecase}}_dict = {{#lambda.snakecase}}{{classname}}{{/lambda.snakecase}}_instance.to_dict()
# create an instance of {{classname}} from a dict
{{#lambda.snakecase}}{{classname}}{{/lambda.snakecase}}_form_dict = {{#lambda.snakecase}}{{classname}}{{/lambda.snakecase}}.from_dict({{#lambda.snakecase}}{{classname}}{{/lambda.snakecase}}_dict)
{{#lambda.snakecase}}{{classname}}{{/lambda.snakecase}}_from_dict = {{classname}}.from_dict({{#lambda.snakecase}}{{classname}}{{/lambda.snakecase}}_dict)
```
{{/isEnum}}
[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md)

View File

@@ -42,7 +42,7 @@ conversion = [
async-trait = "0.1"
axum = { version = "0.7" }
axum-extra = { version = "0.9", features = ["cookie", "multipart"] }
base64 = "0.21"
base64 = "0.22"
bytes = "1"
chrono = { version = "0.4", features = ["serde"] }
frunk = { version = "0.4", optional = true }
@@ -62,7 +62,7 @@ tokio = { version = "1", default-features = false, features = [
] }
tracing = { version = "0.1", features = ["attributes"] }
uuid = { version = "1", features = ["serde"] }
validator = { version = "0.16", features = ["derive"] }
validator = { version = "0.18", features = ["derive"] }
[dev-dependencies]
tracing-subscriber = "0.3"

View File

@@ -1,5 +1,13 @@
#![allow(missing_docs, trivial_casts, unused_variables, unused_mut, unused_imports, unused_extern_crates, non_camel_case_types)]
#![allow(unused_imports, unused_attributes)]
#![allow(
missing_docs,
trivial_casts,
unused_variables,
unused_mut,
unused_extern_crates,
non_camel_case_types,
unused_imports,
unused_attributes
)]
#![allow(clippy::derive_partial_eq_without_eq, clippy::disallowed_names)]
use async_trait::async_trait;

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