Merge remote-tracking branch 'origin/5.1.x' into 6.0.x

This commit is contained in:
William Cheng 2021-01-28 16:47:55 +08:00
commit 694b10e41c
2073 changed files with 30070 additions and 34204 deletions

View File

@ -1244,6 +1244,30 @@
"Client: TypeScript"
]
},
{
"input": "typescript-nestjs-v6-petstore-not-provided-in-root-with-npm.sh",
"matches": [
"Client: TypeScript"
]
},
{
"input": "typescript-nestjs-v6-petstore-not-provided-in-root.sh",
"matches": [
"Client: TypeScript"
]
},
{
"input": "typescript-nestjs-v6-petstore-provided-in-root-with-npm.sh",
"matches": [
"Client: TypeScript"
]
},
{
"input": "typescript-nestjs-v6-petstore-provided-in-root.sh",
"matches": [
"Client: TypeScript"
]
},
{
"input": "typescript-node-petstore-with-npm.sh",
"matches": [

1
.gitignore vendored
View File

@ -31,6 +31,7 @@ packages/
.vscode/
**/.vs
.factorypath
.metals/*
.settings

View File

@ -2,6 +2,11 @@ kind: pipeline
name: default
steps:
# test nim client
- name: nim-client-test
image: nimlang/nim
commands:
- (cd samples/client/petstore/nim/ && nim c sample_client.nim)
# test protobuf schema generator
- name: protobuf-schema-test
image: nanoservice/protobuf-go

View File

@ -63,6 +63,7 @@ If you find OpenAPI Generator useful for work, please consider asking your compa
[<img src="https://openapi-generator.tech/img/companies/docspring.png" width="128" height="128">](https://docspring.com/?utm_source=openapi_generator&utm_medium=github_webpage&utm_campaign=sponsor)
[<img src="https://openapi-generator.tech/img/companies/datadog.png" width="128" height="128">](https://datadoghq.com/?utm_source=openapi_generator&utm_medium=github_webpage&utm_campaign=sponsor)
[<img src="https://openapi-generator.tech/img/companies/thales.jpg" width="128" height="128">](https://cpl.thalesgroup.com/?utm_source=openapi_generator&utm_medium=github_webpage&utm_campaign=sponsor)
[<img src="https://openapi-generator.tech/img/companies/apideck.jpg" width="128" height="128">](https://www.apideck.com/?utm_source=openapi_generator&utm_medium=github_webpage&utm_campaign=sponsor)
#### Thank you GoDaddy for sponsoring the domain names, Linode for sponsoring the VPS and Checkly for sponsoring the API monitoring
@ -76,7 +77,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.0, .NET Core 2.0), **C++** (cpp-restsdk, Qt5, Tizen), **Clojure**, **Crystal**, **Dart**, **Elixir**, **Elm**, **Eiffel**, **Erlang**, **Go**, **Groovy**, **Haskell** (http-client, Servant), **Java** (Jersey1.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), **k6**, **Kotlin**, **Lua**, **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** (rust, rust-server), **Scala** (akka, http4s, scalaz, sttp, swagger-async-httpclient), **Swift** (2.x, 3.x, 4.x, 5.x), **Typescript** (AngularJS, Angular (2.x - 8.x), Aurelia, Axios, Fetch, Inversify, jQuery, Node, Rxjs) |
| **API clients** | **ActionScript**, **Ada**, **Apex**, **Bash**, **C**, **C#** (.net 2.0, 3.5 or later, .NET Standard 1.3 - 2.0, .NET Core 2.0), **C++** (cpp-restsdk, Qt5, Tizen), **Clojure**, **Crystal**, **Dart**, **Elixir**, **Elm**, **Eiffel**, **Erlang**, **Go**, **Groovy**, **Haskell** (http-client, Servant), **Java** (Jersey1.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), **k6**, **Kotlin**, **Lua**, **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** (rust, rust-server), **Scala** (akka, http4s, scalaz, sttp, swagger-async-httpclient), **Swift** (2.x, 3.x, 4.x, 5.x), **Typescript** (AngularJS, Angular (2.x - 8.x), Aurelia, Axios, Fetch, Inversify, jQuery, Nestjs, Node, Rxjs) |
| **Server stubs** | **Ada**, **C#** (ASP.NET Core, NancyFx), **C++** (Pistache, Restbed, Qt5 QHTTPEngine), **Erlang**, **F#** (Giraffe), **Go** (net/http, Gin), **Haskell** (Servant), **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/)), **Kotlin** (Spring Boot, Ktor, Vertx), **PHP** (Laravel, Lumen, Slim, Silex, [Symfony](https://symfony.com/), [Zend Expressive](https://github.com/zendframework/zend-expressive)), **Python** (Flask), **NodeJS**, **Ruby** (Sinatra, Rails5), **Rust** (rust-server), **Scala** (Akka, [Finch](https://github.com/finagle/finch), [Lagom](https://github.com/lagom/lagom), [Play](https://www.playframework.com/), Scalatra) |
| **API documentation generators** | **HTML**, **Confluence Wiki**, **Asciidoc** |
| **Configuration files** | [**Apache2**](https://httpd.apache.org/) |
@ -671,6 +672,7 @@ Here are some companies/projects (alphabetical order) using OpenAPI Generator in
- [Vouchery.io](https://vouchery.io)
- [Xero](https://www.xero.com/)
- [Yahoo Japan](https://www.yahoo.co.jp/)
- [viadee](https://www.viadee.de/)
- [Vonage](https://vonage.com)
- [YITU Technology](https://www.yitutech.com/)
- [Yelp](https://www.yelp.com/)
@ -809,6 +811,7 @@ Here are some companies/projects (alphabetical order) using OpenAPI Generator in
- 2020-12-09 - [プロジェクトにOpenAPI Generatorで自動生成された型付きAPI Clientを導入した話](https://qiita.com/yoshifujiT/items/905c18700ede23f40840) by [@yoshifujiT](https://github.com/yoshifujiT)
- 2020-12-15 - [Next.js + NestJS + GraphQLで変化に追従するフロントエンドへ 〜 ショッピングクーポンの事例紹介](https://techblog.yahoo.co.jp/entry/2020121530052952/) by [小倉 陸](https://github.com/ogugu9) at [Yahoo! JAPAN Tech Blog](https://techblog.yahoo.co.jp/)
- 2021-01-08 - [Hello, New API Part 1](https://www.nginx.com/blog/hello-new-api-part-1/) by [Jeremy Schulman](https://www.nginx.com/people/jeremy-schulman/) at [Major League Baseball](https://www.mlb.com)
- 2021-01-18 - [「アプリ開発あるある」を疑うことから始まった、API Clientコードの自動生成【デブスト2020】](https://codezine.jp/article/detail/13406?p=2) by [CodeZine編集部](https://codezine.jp/author/1)
## [6 - About Us](#table-of-contents)
@ -902,10 +905,11 @@ Here is a list of template creators:
* TypeScript (Angular7): @topce
* TypeScript (Axios): @nicokoenig
* TypeScript (Fetch): @leonyu
* TypeScript (Inversify): @gualtierim
* TypeScript (jQuery): @bherila
* TypeScript (Nestjs): @vfrank66
* TypeScript (Node): @mhardorf
* TypeScript (Rxjs): @denyo
* TypeScript (Inversify): @gualtierim
* TypeScript (redux-query): @petejohansonxo
* Server Stubs
* Ada: @stcarrez

View File

@ -46,6 +46,8 @@ build_script:
- dotnet build samples\client\petstore\csharp-netcore\OpenAPIClientCore\Org.OpenAPITools.sln
# build C# API client (.net framework 4.7)
- dotnet build samples\client\petstore\csharp-netcore\OpenAPIClient-net47\Org.OpenAPITools.sln
# build C# API client (.net 5.0)
- dotnet build samples\client\petstore\csharp-netcore\OpenAPIClient-net5.0\Org.OpenAPITools.sln
# build C# API client
- nuget restore samples\client\petstore\csharp\OpenAPIClient\Org.OpenAPITools.sln
- msbuild samples\client\petstore\csharp\OpenAPIClient\Org.OpenAPITools.sln /logger:"C:\Program Files\AppVeyor\BuildAgent\Appveyor.MSBuildLogger.dll"
@ -65,6 +67,8 @@ test_script:
- dotnet test samples\client\petstore\csharp-netcore\OpenAPIClient\src\Org.OpenAPITools.Test\Org.OpenAPITools.Test.csproj
# test C# API client (.net framework 4.7)
- dotnet test samples\client\petstore\csharp-netcore\OpenAPIClient-net47\src\Org.OpenAPITools.Test\Org.OpenAPITools.Test.csproj
# test C# API client (.net 5.0)
- dotnet test samples\client\petstore\csharp-netcore\OpenAPIClient-net5.0\src\Org.OpenAPITools.Test\Org.OpenAPITools.Test.csproj
# test c# API client
- nunit3-console samples\client\petstore\csharp\OpenAPIClient\src\Org.OpenAPITools.Test\bin\Debug\Org.OpenAPITools.Test.dll --result=myresults.xml;format=AppVeyor
# test c# API client (with PropertyChanged)

View File

@ -0,0 +1,13 @@
# for .net standard
generatorName: csharp-netcore
outputDir: samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0
# TODO switch to http signature spec after fixing compilation issues
#inputSpec: modules/openapi-generator/src/test/resources/3_0/java/petstore-with-fake-endpoints-models-for-testing-with-http-signature.yaml
inputSpec: modules/openapi-generator/src/test/resources/3_0/petstore.yaml
templateDir: modules/openapi-generator/src/main/resources/csharp-netcore
additionalProperties:
packageGuid: '{321C8C3F-0156-40C1-AE42-D59761FB9B6C}'
useCompareNetObjects: true
disallowAdditionalPropertiesIfNotPresent: false
useOneOfDiscriminatorLookup: true
targetFramework: net5.0

View File

@ -1,6 +1,6 @@
generatorName: elixir
outputDir: samples/client/petstore/elixir
inputSpec: modules/openapi-generator/src/test/resources/2_0/petstore-with-fake-endpoints-models-for-testing.yaml
inputSpec: modules/openapi-generator/src/test/resources/3_0/petstore-with-fake-endpoints-models-for-testing.yaml
templateDir: modules/openapi-generator/src/main/resources/elixir
additionalProperties:
invokerPackage: OpenapiPetstore

View File

@ -0,0 +1,9 @@
generatorName: typescript-nestjs
outputDir: samples/client/petstore/typescript-nestjs-v6-provided-in-root/builds/default
inputSpec: modules/openapi-generator/src/test/resources/3_0/petstore.yaml
additionalProperties:
nestVersion: 6.0.0
"npmName": "@openapitools/typescript-nestjs-petstore"
"npmVersion": "1.0.0"
"npmRepository" : "https://skimdb.npmjs.com/registry"
"snapshot" : false

View File

@ -1,22 +0,0 @@
set executable=.\modules\openapi-generator-cli\target\openapi-generator-cli.jar
If Not Exist %executable% (
mvn clean package
)
REM set JAVA_OPTS=%JAVA_OPTS% -Xmx1024M
set args=generate -i modules\openapi-generator\src\test\resources\3_0\petstore.yaml -g typescript -o samples\openapi3\client\petstore\typescript\builds\default --additional-properties=platform=node,npmName=ts-petstore-client
java %JAVA_OPTS% -jar %executable% %args%
args=generate -i modules\openapi-generator\src\test\resources\3_0\petstore.yaml -g typescript -o samples\openapi3\client\petstore\typescript\builds\jquery --additional-properties=framework=jquery,npmName=ts-petstore-client
java %JAVA_OPTS% -jar %executable% %args%
set args=generate -i modules\openapi-generator\src\test\resources\3_0\petstore.yaml -g typescript -o samples\openapi3\client\petstore\typescript\builds\object_params --additional-properties=platform=node,npmName=ts-petstore-client,useObjectParameters
java %JAVA_OPTS% -jar %executable% %args%
set args=generate -i modules\openapi-generator\src\test\resources\3_0\petstore.yaml -g typescript -o samples\openapi3\client\petstore\typescript\builds\inversify --additional-properties=platform=node,npmName=ts-petstore-client,useInversify
java %JAVA_OPTS% -jar %executable% %args%
set args=generate -i modules\openapi-generator\src\test\resources\3_0\petstore.yaml -g typescript -o samples\openapi3\client\petstore\typescript\builds\deno --additional-properties=platform=deno
java %JAVA_OPTS% -jar %executable% %args%

View File

@ -11,7 +11,7 @@ workflows:
primary:
steps:
- git-clone@4.0.17: {}
- brew-install@0.10.2:
- brew-install@0.11.0:
inputs:
- packages: maven
- script@1.1.6:
@ -30,15 +30,6 @@ workflows:
mvn --no-snapshot-updates package -Dorg.slf4j.simpleLogger.defaultLogLevel=error
title: Build openapi-generator
- script@1.1.6:
title: Update Swift samples
inputs:
- content: |
#!/usr/bin/env bash
set -e
bin/generate-samples.sh ./bin/configs/other/swift5-*
- script@1.1.6:
title: Run Swift5 tests
inputs:
@ -47,5 +38,5 @@ workflows:
set -e
./samples/client/test/swift5/swift5_test_all.sh
./samples/client/petstore/swift5/swift5_test_all.sh

View File

@ -69,6 +69,7 @@ The following generators are available:
* [typescript-fetch](generators/typescript-fetch.md)
* [typescript-inversify](generators/typescript-inversify.md)
* [typescript-jquery](generators/typescript-jquery.md)
* [typescript-nestjs (experimental)](generators/typescript-nestjs.md)
* [typescript-node](generators/typescript-node.md)
* [typescript-redux-query](generators/typescript-redux-query.md)
* [typescript-rxjs](generators/typescript-rxjs.md)

View File

@ -232,10 +232,10 @@ These options may be applied as additional-properties (cli) or configOptions (pl
### Security Feature
| Name | Supported | Defined By |
| ---- | --------- | ---------- |
|BasicAuth||OAS2,OAS3
|ApiKey||OAS2,OAS3
|BasicAuth||OAS2,OAS3
|ApiKey||OAS2,OAS3
|OpenIDConnect|✗|OAS3
|BearerToken||OAS3
|BearerToken||OAS3
|OAuth2_Implicit|✗|OAS2,OAS3
|OAuth2_Password|✗|OAS2,OAS3
|OAuth2_ClientCredentials|✗|OAS2,OAS3

View File

@ -28,10 +28,10 @@ These options may be applied as additional-properties (cli) or configOptions (pl
|returnICollection|Return ICollection&lt;T&gt; instead of the concrete type.| |false|
|sortParamsByRequiredFlag|Sort method arguments to place required parameters before optional parameters.| |true|
|sourceFolder|source folder for generated code| |src|
|targetFramework|The target .NET framework version.|<dl><dt>**netstandard1.3**</dt><dd>.NET Standard 1.3 compatible</dd><dt>**netstandard1.4**</dt><dd>.NET Standard 1.4 compatible</dd><dt>**netstandard1.5**</dt><dd>.NET Standard 1.5 compatible</dd><dt>**netstandard1.6**</dt><dd>.NET Standard 1.6 compatible</dd><dt>**netstandard2.0**</dt><dd>.NET Standard 2.0 compatible</dd><dt>**netstandard2.1**</dt><dd>.NET Standard 2.1 compatible</dd><dt>**netcoreapp2.0**</dt><dd>.NET Core 2.0 compatible</dd><dt>**netcoreapp2.1**</dt><dd>.NET Core 2.1 compatible</dd><dt>**netcoreapp3.0**</dt><dd>.NET Core 3.0 compatible</dd><dt>**netcoreapp3.1**</dt><dd>.NET Core 3.1 compatible</dd><dt>**net47**</dt><dd>.NET Framework 4.7 compatible</dd></dl>|netstandard2.0|
|targetFramework|The target .NET framework version.|<dl><dt>**netstandard1.3**</dt><dd>.NET Standard 1.3 compatible</dd><dt>**netstandard1.4**</dt><dd>.NET Standard 1.4 compatible</dd><dt>**netstandard1.5**</dt><dd>.NET Standard 1.5 compatible</dd><dt>**netstandard1.6**</dt><dd>.NET Standard 1.6 compatible</dd><dt>**netstandard2.0**</dt><dd>.NET Standard 2.0 compatible</dd><dt>**netstandard2.1**</dt><dd>.NET Standard 2.1 compatible</dd><dt>**netcoreapp2.0**</dt><dd>.NET Core 2.0 compatible</dd><dt>**netcoreapp2.1**</dt><dd>.NET Core 2.1 compatible</dd><dt>**netcoreapp3.0**</dt><dd>.NET Core 3.0 compatible</dd><dt>**netcoreapp3.1**</dt><dd>.NET Core 3.1 compatible</dd><dt>**net47**</dt><dd>.NET Framework 4.7 compatible</dd><dt>**net5.0**</dt><dd>.NET 5.0 compatible</dd></dl>|netstandard2.0|
|useCollection|Deserialize array types to Collection&lt;T&gt; instead of List&lt;T&gt;.| |false|
|useDateTimeOffset|Use DateTimeOffset to model date-time properties| |false|
|useOneOfDiscriminatorLookup|Use the discriminator's mapping in oneOf to speed up the model lookup. IMPORTANT: Validation (e.g. one and onlye one match in oneOf's schemas) will be skipped.| |false|
|useOneOfDiscriminatorLookup|Use the discriminator's mapping in oneOf to speed up the model lookup. IMPORTANT: Validation (e.g. one and only one match in oneOf's schemas) will be skipped.| |false|
|validatable|Generates self-validatable models.| |true|
## IMPORT MAPPING

View File

@ -36,6 +36,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl
<li>Atom</li>
<li>Boolean</li>
<li>DateTime</li>
<li>Decimal</li>
<li>Float</li>
<li>Integer</li>
<li>List</li>
@ -43,6 +44,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl
<li>PID</li>
<li>String</li>
<li>Tuple</li>
<li>map()</li>
</ul>
## RESERVED WORDS

View File

@ -16,7 +16,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl
|packageVersion|Go package version.| |1.0.0|
|prependFormOrBodyParameters|Add form or body parameters to the beginning of the parameter list.| |false|
|structPrefix|whether to prefix struct with the class name. e.g. DeletePetOpts =&gt; PetApiDeletePetOpts| |false|
|useOneOfDiscriminatorLookup|Use the discriminator's mapping in oneOf to speed up the model lookup. IMPORTANT: Validation (e.g. one and onlye one match in oneOf's schemas) will be skipped.| |false|
|useOneOfDiscriminatorLookup|Use the discriminator's mapping in oneOf to speed up the model lookup. IMPORTANT: Validation (e.g. one and only one match in oneOf's schemas) will be skipped.| |false|
|withAWSV4Signature|whether to include AWS v4 signature support| |false|
|withXml|whether to include support for application/xml content type and include XML annotations in the model (works with libraries that provide support for JSON and XML)| |false|

View File

@ -35,7 +35,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl
|invokerPackage|root package for generated code| |org.openapitools.client|
|java8|Use Java8 classes instead of third party equivalents. Starting in 5.x, JDK8 is the default and the support for JDK7, JDK6 has been dropped|<dl><dt>**true**</dt><dd>Use Java 8 classes such as Base64</dd><dt>**false**</dt><dd>Various third party libraries as needed</dd></dl>|true|
|legacyDiscriminatorBehavior|Set to true 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|
|library|library template (sub-template) to use|<dl><dt>**jersey1**</dt><dd>HTTP client: Jersey client 1.19.x. JSON processing: Jackson 2.9.x. Enable Java6 support using '-DsupportJava6=true'. Enable gzip request encoding using '-DuseGzipFeature=true'. IMPORTANT NOTE: jersey 1.x is no longer actively maintained so please upgrade to 'jersey2' or other HTTP libaries instead.</dd><dt>**jersey2**</dt><dd>HTTP client: Jersey client 2.25.1. JSON processing: Jackson 2.9.x</dd><dt>**feign**</dt><dd>HTTP client: OpenFeign 10.x. JSON processing: Jackson 2.9.x.</dd><dt>**okhttp-gson**</dt><dd>[DEFAULT] HTTP client: OkHttp 3.x. JSON processing: Gson 2.8.x. Enable Parcelable models on Android using '-DparcelableModel=true'. Enable gzip request encoding using '-DuseGzipFeature=true'.</dd><dt>**retrofit2**</dt><dd>HTTP client: OkHttp 3.x. JSON processing: Gson 2.x (Retrofit 2.3.0). Enable the RxJava adapter using '-DuseRxJava[2/3]=true'. (RxJava 1.x or 2.x or 3.x)</dd><dt>**resttemplate**</dt><dd>HTTP client: Spring RestTemplate 4.x. JSON processing: Jackson 2.9.x</dd><dt>**webclient**</dt><dd>HTTP client: Spring WebClient 5.x. JSON processing: Jackson 2.9.x</dd><dt>**resteasy**</dt><dd>HTTP client: Resteasy client 3.x. JSON processing: Jackson 2.9.x</dd><dt>**vertx**</dt><dd>HTTP client: VertX client 3.x. JSON processing: Jackson 2.9.x</dd><dt>**google-api-client**</dt><dd>HTTP client: Google API client 1.x. JSON processing: Jackson 2.9.x</dd><dt>**rest-assured**</dt><dd>HTTP client: rest-assured : 4.x. JSON processing: Gson 2.x or Jackson 2.10.x. Only for Java 8</dd><dt>**native**</dt><dd>HTTP client: Java native HttpClient. JSON processing: Jackson 2.9.x. Only for Java11+</dd><dt>**microprofile**</dt><dd>HTTP client: Microprofile client 1.x. JSON processing: Jackson 2.9.x</dd></dl>|okhttp-gson|
|library|library template (sub-template) to use|<dl><dt>**jersey1**</dt><dd>HTTP client: Jersey client 1.19.x. JSON processing: Jackson 2.9.x. Enable gzip request encoding using '-DuseGzipFeature=true'. IMPORTANT NOTE: jersey 1.x is no longer actively maintained so please upgrade to 'jersey2' or other HTTP libaries instead.</dd><dt>**jersey2**</dt><dd>HTTP client: Jersey client 2.25.1. JSON processing: Jackson 2.9.x</dd><dt>**feign**</dt><dd>HTTP client: OpenFeign 10.x. JSON processing: Jackson 2.9.x.</dd><dt>**okhttp-gson**</dt><dd>[DEFAULT] HTTP client: OkHttp 3.x. JSON processing: Gson 2.8.x. Enable Parcelable models on Android using '-DparcelableModel=true'. Enable gzip request encoding using '-DuseGzipFeature=true'.</dd><dt>**retrofit2**</dt><dd>HTTP client: OkHttp 3.x. JSON processing: Gson 2.x (Retrofit 2.3.0). Enable the RxJava adapter using '-DuseRxJava[2/3]=true'. (RxJava 1.x or 2.x or 3.x)</dd><dt>**resttemplate**</dt><dd>HTTP client: Spring RestTemplate 4.x. JSON processing: Jackson 2.9.x</dd><dt>**webclient**</dt><dd>HTTP client: Spring WebClient 5.x. JSON processing: Jackson 2.9.x</dd><dt>**resteasy**</dt><dd>HTTP client: Resteasy client 3.x. JSON processing: Jackson 2.9.x</dd><dt>**vertx**</dt><dd>HTTP client: VertX client 3.x. JSON processing: Jackson 2.9.x</dd><dt>**google-api-client**</dt><dd>HTTP client: Google API client 1.x. JSON processing: Jackson 2.9.x</dd><dt>**rest-assured**</dt><dd>HTTP client: rest-assured : 4.x. JSON processing: Gson 2.x or Jackson 2.10.x. Only for Java 8</dd><dt>**native**</dt><dd>HTTP client: Java native HttpClient. JSON processing: Jackson 2.9.x. Only for Java11+</dd><dt>**microprofile**</dt><dd>HTTP client: Microprofile client 1.x. JSON processing: Jackson 2.9.x</dd></dl>|okhttp-gson|
|licenseName|The name of the license| |Unlicense|
|licenseUrl|The URL of the license| |http://unlicense.org|
|microprofileFramework|Framework for microprofile. Possible values &quot;kumuluzee&quot;| |null|
@ -57,7 +57,6 @@ These options may be applied as additional-properties (cli) or configOptions (pl
|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| |src/main/java|
|supportJava6|Whether to support Java6 with the Jersey1 library. This option has been deprecated and will be removed in the 5.x release| |false|
|useAbstractionForFiles|Use alternative types instead of java.io.File to allow passing bytes without a file on disk. Available on resttemplate library| |false|
|useBeanValidation|Use BeanValidation API annotations| |false|
|useGzipFeature|Send gzip-encoded requests| |false|

View File

@ -21,7 +21,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl
|releaseNotes|Release notes of the generated PowerShell module| |null|
|skipVerbParsing|Set skipVerbParsing to not try get powershell verbs of operation names| |null|
|tags|Tags applied to the generated PowerShell module. These help with module discovery in online galleries| |null|
|useOneOfDiscriminatorLookup|Use the discriminator's mapping in oneOf to speed up the model lookup. IMPORTANT: Validation (e.g. one and onlye one match in oneOf's schemas) will be skipped.| |null|
|useOneOfDiscriminatorLookup|Use the discriminator's mapping in oneOf to speed up the model lookup. IMPORTANT: Validation (e.g. one and only one match in oneOf's schemas) will be skipped.| |null|
## IMPORT MAPPING

View File

@ -186,7 +186,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl
| Name | Supported | Defined By |
| ---- | --------- | ---------- |
|Simple|✓|OAS2,OAS3
|Composite||OAS2,OAS3
|Composite||OAS2,OAS3
|Polymorphism|✗|OAS2,OAS3
|Union|✗|OAS3

View File

@ -0,0 +1,254 @@
---
title: Config Options for typescript-nestjs
sidebar_label: typescript-nestjs
---
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|
|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|
|enumNameSuffix|Suffix that will be appended to all enum names.| |Enum|
|enumPropertyNaming|Naming convention for enum properties: 'camelCase', 'PascalCase', 'snake_case', 'UPPERCASE', and 'original'| |PascalCase|
|fileNaming|Naming convention for the output files: 'camelCase', 'kebab-case'.| |camelCase|
|legacyDiscriminatorBehavior|Set to true 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|
|modelFileSuffix|The suffix of the file of the generated model (model&lt;suffix&gt;.ts).| |null|
|modelPropertyNaming|Naming convention for the property: 'camelCase', 'PascalCase', 'snake_case' and 'original', which keeps the original name. Only change it if you provide your own run-time code for (de-)serialization of models| |original|
|modelSuffix|The suffix of the generated model.| |null|
|nestVersion|The version of Nestjs.| |6.0.0|
|npmName|The name under which you want to publish generated npm package. Required to generate a full package| |null|
|npmRepository|Use this property to set an url your private npmRepo in the package.json| |null|
|npmVersion|The version of your npm package. If not provided, using the version from the OpenAPI specification file.| |1.0.0|
|nullSafeAdditionalProps|Set to make additional properties types declare that their indexer may return undefined| |false|
|prependFormOrBodyParameters|Add form or body parameters to the beginning of the parameter list.| |false|
|serviceFileSuffix|The suffix of the file of the generated service (service&lt;suffix&gt;.ts).| |.service|
|serviceSuffix|The suffix of the generated service.| |Service|
|snapshot|When setting this property to true, the version will be suffixed with -SNAPSHOT.yyyyMMddHHmm| |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|
|stringEnums|Generate string enums instead of objects for enum values.| |false|
|supportsES6|Generate code that conforms to ES6.| |false|
|taggedUnions|Use discriminators to create tagged unions instead of extending interfaces.| |false|
|withInterfaces|Setting this property to true will generate interfaces next to the default class implementations.| |false|
## IMPORT MAPPING
| Type/Alias | Imports |
| ---------- | ------- |
## INSTANTIATION TYPES
| Type/Alias | Instantiated By |
| ---------- | --------------- |
|array|Array|
## LANGUAGE PRIMITIVES
<ul class="column-ul">
<li>Array</li>
<li>Blob</li>
<li>Boolean</li>
<li>Date</li>
<li>Double</li>
<li>Error</li>
<li>File</li>
<li>Float</li>
<li>Integer</li>
<li>Long</li>
<li>Map</li>
<li>Object</li>
<li>ReadonlyArray</li>
<li>Set</li>
<li>String</li>
<li>any</li>
<li>boolean</li>
<li>number</li>
<li>object</li>
<li>string</li>
</ul>
## RESERVED WORDS
<ul class="column-ul">
<li>abstract</li>
<li>await</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>debugger</li>
<li>default</li>
<li>delete</li>
<li>do</li>
<li>double</li>
<li>else</li>
<li>enum</li>
<li>export</li>
<li>extends</li>
<li>false</li>
<li>final</li>
<li>finally</li>
<li>float</li>
<li>for</li>
<li>formParams</li>
<li>function</li>
<li>goto</li>
<li>headerParams</li>
<li>if</li>
<li>implements</li>
<li>import</li>
<li>in</li>
<li>instanceof</li>
<li>int</li>
<li>interface</li>
<li>let</li>
<li>long</li>
<li>native</li>
<li>new</li>
<li>null</li>
<li>package</li>
<li>private</li>
<li>protected</li>
<li>public</li>
<li>queryParameters</li>
<li>requestOptions</li>
<li>return</li>
<li>short</li>
<li>static</li>
<li>super</li>
<li>switch</li>
<li>synchronized</li>
<li>this</li>
<li>throw</li>
<li>transient</li>
<li>true</li>
<li>try</li>
<li>typeof</li>
<li>useFormData</li>
<li>var</li>
<li>varLocalDeferred</li>
<li>varLocalPath</li>
<li>void</li>
<li>volatile</li>
<li>while</li>
<li>with</li>
<li>yield</li>
</ul>
## FEATURE SET
### Client Modification Feature
| Name | Supported | Defined By |
| ---- | --------- | ---------- |
|BasePath|✓|ToolingExtension
|Authorizations|✗|ToolingExtension
|UserAgent|✗|ToolingExtension
|MockServer|✗|ToolingExtension
### Data Type Feature
| Name | Supported | Defined By |
| ---- | --------- | ---------- |
|Custom|✗|OAS2,OAS3
|Int32|✓|OAS2,OAS3
|Int64|✓|OAS2,OAS3
|Float|✓|OAS2,OAS3
|Double|✓|OAS2,OAS3
|Decimal|✓|ToolingExtension
|String|✓|OAS2,OAS3
|Byte|✓|OAS2,OAS3
|Binary|✓|OAS2,OAS3
|Boolean|✓|OAS2,OAS3
|Date|✓|OAS2,OAS3
|DateTime|✓|OAS2,OAS3
|Password|✓|OAS2,OAS3
|File|✓|OAS2
|Array|✓|OAS2,OAS3
|Maps|✓|ToolingExtension
|CollectionFormat|✓|OAS2
|CollectionFormatMulti|✓|OAS2
|Enum|✓|OAS2,OAS3
|ArrayOfEnum|✓|ToolingExtension
|ArrayOfModel|✓|ToolingExtension
|ArrayOfCollectionOfPrimitives|✓|ToolingExtension
|ArrayOfCollectionOfModel|✓|ToolingExtension
|ArrayOfCollectionOfEnum|✓|ToolingExtension
|MapOfEnum|✓|ToolingExtension
|MapOfModel|✓|ToolingExtension
|MapOfCollectionOfPrimitives|✓|ToolingExtension
|MapOfCollectionOfModel|✓|ToolingExtension
|MapOfCollectionOfEnum|✓|ToolingExtension
### Documentation Feature
| Name | Supported | Defined By |
| ---- | --------- | ---------- |
|Readme|✓|ToolingExtension
|Model|✓|ToolingExtension
|Api|✓|ToolingExtension
### Global Feature
| Name | Supported | Defined By |
| ---- | --------- | ---------- |
|Host|✓|OAS2,OAS3
|BasePath|✓|OAS2,OAS3
|Info|✓|OAS2,OAS3
|Schemes|✗|OAS2,OAS3
|PartialSchemes|✓|OAS2,OAS3
|Consumes|✓|OAS2
|Produces|✓|OAS2
|ExternalDocumentation|✓|OAS2,OAS3
|Examples|✓|OAS2,OAS3
|XMLStructureDefinitions|✗|OAS2,OAS3
|MultiServer|✗|OAS3
|ParameterizedServer|✗|OAS3
|ParameterStyling|✗|OAS3
|Callbacks|✗|OAS3
|LinkObjects|✗|OAS3
### Parameter Feature
| Name | Supported | Defined By |
| ---- | --------- | ---------- |
|Path|✓|OAS2,OAS3
|Query|✓|OAS2,OAS3
|Header|✓|OAS2,OAS3
|Body|✓|OAS2
|FormUnencoded|✓|OAS2
|FormMultipart|✓|OAS2
|Cookie|✓|OAS3
### Schema Support Feature
| Name | Supported | Defined By |
| ---- | --------- | ---------- |
|Simple|✓|OAS2,OAS3
|Composite|✓|OAS2,OAS3
|Polymorphism|✓|OAS2,OAS3
|Union|✗|OAS3
### Security Feature
| Name | Supported | Defined By |
| ---- | --------- | ---------- |
|BasicAuth|✗|OAS2,OAS3
|ApiKey|✗|OAS2,OAS3
|OpenIDConnect|✗|OAS3
|BearerToken|✗|OAS3
|OAuth2_Implicit|✗|OAS2,OAS3
|OAuth2_Password|✗|OAS2,OAS3
|OAuth2_ClientCredentials|✗|OAS2,OAS3
|OAuth2_AuthorizationCode|✗|OAS2,OAS3
### Wire Format Feature
| Name | Supported | Defined By |
| ---- | --------- | ---------- |
|JSON|✓|OAS2,OAS3
|XML|✓|OAS2,OAS3
|PROTOBUF|✗|ToolingExtension
|Custom|✗|OAS2,OAS3

View File

@ -15,7 +15,7 @@ Add to your `build->plugins` section (default phase is `generate-sources` phase)
<plugin>
<groupId>org.openapitools</groupId>
<artifactId>openapi-generator-maven-plugin</artifactId>
<version>4.3.1</version>
<version>5.0.0</version>
<executions>
<execution>
<goals>
@ -76,7 +76,7 @@ buildscript {
maven { url "https://repo1.maven.org/maven2" }
}
dependencies {
classpath "org.openapitools:openapi-generator-gradle-plugin:3.3.4"
classpath "org.openapitools:openapi-generator-gradle-plugin:5.0.0"
}
}
@ -111,9 +111,6 @@ openApiGenerate {
apiPackage = "org.openapi.example.api"
invokerPackage = "org.openapi.example.invoker"
modelPackage = "org.openapi.example.model"
modelFilesConstrainedTo = [
"Error"
]
configOptions = [
dateLibrary: "java8"
]

View File

@ -59,7 +59,7 @@ Short term are focused on improving contributor and user productivity (part of t
* SPI plugins
* Templating engine
* Language extensions
* Custom extensions (e.g. allowing users to load support for https://github.com/Azure/azure-rest-api-specs[azure-rest-api-specs])
* Custom extensions (e.g. allowing users to load support for [azure-rest-api-specs](https://github.com/Azure/azure-rest-api-specs))
* Customizable templating engines (handlebars support)
* Unit-testing templates (to previously mentioned explicit type as an interface to the template)
* Reduce coupling

View File

@ -551,7 +551,7 @@ BUILD SUCCESSFUL in 0s
=== openApiValidate
.in buid.gradle
.in build.gradle
[source,groovy]
----
openApiValidate {

View File

@ -44,7 +44,7 @@ APP_NAME="Gradle"
APP_BASE_NAME=`basename "$0"`
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
DEFAULT_JVM_OPTS='-Dfile.encoding=UTF-8 "-Xmx64m" "-Xms64m"'
# Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD="maximum"
@ -82,6 +82,7 @@ esac
CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
# Determine the Java command to use to start the JVM.
if [ -n "$JAVA_HOME" ] ; then
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
@ -129,6 +130,7 @@ fi
if [ "$cygwin" = "true" -o "$msys" = "true" ] ; then
APP_HOME=`cygpath --path --mixed "$APP_HOME"`
CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
JAVACMD=`cygpath --unix "$JAVACMD"`
# We build the pattern for arguments to be converted via cygpath
@ -154,19 +156,19 @@ if [ "$cygwin" = "true" -o "$msys" = "true" ] ; then
else
eval `echo args$i`="\"$arg\""
fi
i=$((i+1))
i=`expr $i + 1`
done
case $i in
(0) set -- ;;
(1) set -- "$args0" ;;
(2) set -- "$args0" "$args1" ;;
(3) set -- "$args0" "$args1" "$args2" ;;
(4) set -- "$args0" "$args1" "$args2" "$args3" ;;
(5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
(6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
(7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
(8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
(9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
0) set -- ;;
1) set -- "$args0" ;;
2) set -- "$args0" "$args1" ;;
3) set -- "$args0" "$args1" "$args2" ;;
4) set -- "$args0" "$args1" "$args2" "$args3" ;;
5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
esac
fi
@ -175,14 +177,9 @@ save () {
for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done
echo " "
}
APP_ARGS=$(save "$@")
APP_ARGS=`save "$@"`
# Collect all arguments for the java command, following the shell quoting and substitution rules
eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS"
# by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong
if [ "$(uname)" = "Darwin" ] && [ "$HOME" = "$PWD" ]; then
cd "$(dirname "$0")"
fi
exec "$JAVACMD" "$@"

View File

@ -1,100 +1,89 @@
@rem
@rem Copyright 2015 the original author or authors.
@rem
@rem Licensed under the Apache License, Version 2.0 (the "License");
@rem you may not use this file except in compliance with the License.
@rem You may obtain a copy of the License at
@rem
@rem https://www.apache.org/licenses/LICENSE-2.0
@rem
@rem Unless required by applicable law or agreed to in writing, software
@rem distributed under the License is distributed on an "AS IS" BASIS,
@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@rem See the License for the specific language governing permissions and
@rem limitations under the License.
@rem
@if "%DEBUG%" == "" @echo off
@rem ##########################################################################
@rem
@rem Gradle startup script for Windows
@rem
@rem ##########################################################################
@rem Set local scope for the variables with windows NT shell
if "%OS%"=="Windows_NT" setlocal
set DIRNAME=%~dp0
if "%DIRNAME%" == "" set DIRNAME=.
set APP_BASE_NAME=%~n0
set APP_HOME=%DIRNAME%
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
@rem Find java.exe
if defined JAVA_HOME goto findJavaFromJavaHome
set JAVA_EXE=java.exe
%JAVA_EXE% -version >NUL 2>&1
if "%ERRORLEVEL%" == "0" goto init
echo.
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:findJavaFromJavaHome
set JAVA_HOME=%JAVA_HOME:"=%
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
if exist "%JAVA_EXE%" goto init
echo.
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:init
@rem Get command-line arguments, handling Windows variants
if not "%OS%" == "Windows_NT" goto win9xME_args
:win9xME_args
@rem Slurp the command line arguments.
set CMD_LINE_ARGS=
set _SKIP=2
:win9xME_args_slurp
if "x%~1" == "x" goto execute
set CMD_LINE_ARGS=%*
:execute
@rem Setup the command line
set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
@rem Execute Gradle
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS%
:end
@rem End local scope for the variables with windows NT shell
if "%ERRORLEVEL%"=="0" goto mainEnd
:fail
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
rem the _cmd.exe /c_ return code!
if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
exit /b 1
:mainEnd
if "%OS%"=="Windows_NT" endlocal
:omega
@rem
@rem Copyright 2015 the original author or authors.
@rem
@rem Licensed under the Apache License, Version 2.0 (the "License");
@rem you may not use this file except in compliance with the License.
@rem You may obtain a copy of the License at
@rem
@rem https://www.apache.org/licenses/LICENSE-2.0
@rem
@rem Unless required by applicable law or agreed to in writing, software
@rem distributed under the License is distributed on an "AS IS" BASIS,
@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@rem See the License for the specific language governing permissions and
@rem limitations under the License.
@rem
@if "%DEBUG%" == "" @echo off
@rem ##########################################################################
@rem
@rem Gradle startup script for Windows
@rem
@rem ##########################################################################
@rem Set local scope for the variables with windows NT shell
if "%OS%"=="Windows_NT" setlocal
set DIRNAME=%~dp0
if "%DIRNAME%" == "" set DIRNAME=.
set APP_BASE_NAME=%~n0
set APP_HOME=%DIRNAME%
@rem Resolve any "." and ".." in APP_HOME to make it shorter.
for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
set DEFAULT_JVM_OPTS=-Dfile.encoding=UTF-8 "-Xmx64m" "-Xms64m"
@rem Find java.exe
if defined JAVA_HOME goto findJavaFromJavaHome
set JAVA_EXE=java.exe
%JAVA_EXE% -version >NUL 2>&1
if "%ERRORLEVEL%" == "0" goto execute
echo.
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:findJavaFromJavaHome
set JAVA_HOME=%JAVA_HOME:"=%
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
if exist "%JAVA_EXE%" goto execute
echo.
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:execute
@rem Setup the command line
set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
@rem Execute Gradle
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %*
:end
@rem End local scope for the variables with windows NT shell
if "%ERRORLEVEL%"=="0" goto mainEnd
:fail
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
rem the _cmd.exe /c_ return code!
if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
exit /b 1
:mainEnd
if "%OS%"=="Windows_NT" endlocal
:omega

View File

@ -1,3 +1,3 @@
# RELEASE_VERSION
openApiGeneratorVersion=5.0.0-SNAPSHOT
openApiGeneratorVersion=5.0.1-SNAPSHOT
# /RELEASE_VERSION

View File

@ -367,5 +367,5 @@ public class CodegenConstants {
"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.";
public static final String USE_ONEOF_DISCRIMINATOR_LOOKUP = "useOneOfDiscriminatorLookup";
public static final String USE_ONEOF_DISCRIMINATOR_LOOKUP_DESC = "Use the discriminator's mapping in oneOf to speed up the model lookup. IMPORTANT: Validation (e.g. one and onlye one match in oneOf's schemas) will be skipped.";
public static final String USE_ONEOF_DISCRIMINATOR_LOOKUP_DESC = "Use the discriminator's mapping in oneOf to speed up the model lookup. IMPORTANT: Validation (e.g. one and only one match in oneOf's schemas) will be skipped.";
}

View File

@ -79,7 +79,7 @@ public class CodegenModel implements IJsonSchemaValidationProperties {
public Set<String> allMandatory = new TreeSet<String>(); // with parent's required properties
public Set<String> imports = new TreeSet<String>();
public boolean hasVars, emptyVars, hasMoreModels, hasEnums, isEnum;
public boolean hasVars, emptyVars, hasMoreModels, hasEnums, isEnum, hasValidation;
/**
* Indicates the OAS schema specifies "nullable: true".
*/
@ -612,12 +612,11 @@ public class CodegenModel implements IJsonSchemaValidationProperties {
this.additionalProperties = additionalProperties;
}
// indicates if the model component has validation on the root level schema
// this will be true when minItems or minProperties is set
public boolean hasValidation() {
boolean val = (maxItems != null || minItems != null || minProperties != null || maxProperties != null || minLength != null || maxLength != null || multipleOf != null || pattern != null || minimum != null || maximum != null || Boolean.TRUE.equals(uniqueItems) || Boolean.TRUE.equals(exclusiveMaximum) || Boolean.TRUE.equals(exclusiveMinimum));
return val;
}
@Override
public boolean getHasValidation() { return hasValidation; }
@Override
public void setHasValidation(boolean hasValidation) { this.hasValidation = hasValidation; }
public List<CodegenProperty> getReadOnlyVars() {
return readOnlyVars;
@ -742,6 +741,7 @@ public class CodegenModel implements IJsonSchemaValidationProperties {
isDeprecated == that.isDeprecated &&
hasOnlyReadOnly == that.hasOnlyReadOnly &&
isNull == that.isNull &&
hasValidation == that.hasValidation &&
getUniqueItems() == that.getUniqueItems() &&
getExclusiveMinimum() == that.getExclusiveMinimum() &&
getExclusiveMaximum() == that.getExclusiveMaximum() &&
@ -806,7 +806,7 @@ public class CodegenModel implements IJsonSchemaValidationProperties {
getDescription(), getClassVarName(), getModelJson(), getDataType(), getXmlPrefix(), getXmlNamespace(),
getXmlName(), getClassFilename(), getUnescapedDescription(), getDiscriminator(), getDefaultValue(),
getArrayModelType(), isAlias, isString, isInteger, isLong, isNumber, isNumeric, isFloat, isDouble,
isDate, isDateTime, isNull,
isDate, isDateTime, isNull, hasValidation,
getVars(), getAllVars(), getRequiredVars(), getOptionalVars(), getReadOnlyVars(), getReadWriteVars(),
getParentVars(), getAllowableValues(), getMandatory(), getAllMandatory(), getImports(), hasVars,
isEmptyVars(), hasMoreModels, hasEnums, isEnum, isNullable, hasRequired, hasOptional, isArray,
@ -898,6 +898,7 @@ public class CodegenModel implements IJsonSchemaValidationProperties {
sb.append(", additionalProperties='").append(additionalProperties).append('\'');
sb.append(", isModel='").append(isModel).append('\'');
sb.append(", isNull='").append(isNull);
sb.append(", hasValidation='").append(hasValidation);
sb.append('}');
return sb.toString();
}

View File

@ -582,5 +582,11 @@ public class CodegenParameter implements IJsonSchemaValidationProperties {
public void setIsNull(boolean isNull) {
this.isNull = isNull;
}
@Override
public boolean getHasValidation() { return hasValidation; }
@Override
public void setHasValidation(boolean hasValidation) { this.hasValidation = hasValidation; }
}

View File

@ -687,6 +687,12 @@ public class CodegenProperty implements Cloneable, IJsonSchemaValidationProperti
this.isNull = isNull;
}
@Override
public boolean getHasValidation() { return hasValidation; }
@Override
public void setHasValidation(boolean hasValidation) { this.hasValidation = hasValidation; }
@Override
public String toString() {
final StringBuilder sb = new StringBuilder("CodegenProperty{");

View File

@ -78,6 +78,7 @@ public class CodegenResponse implements IJsonSchemaValidationProperties {
public CodegenProperty additionalProperties;
public List<CodegenProperty> vars = new ArrayList<CodegenProperty>(); // all properties (without parent's properties)
public List<CodegenProperty> requiredVars = new ArrayList<CodegenProperty>();
private boolean hasValidation;
@Override
public int hashCode() {
@ -85,7 +86,7 @@ public class CodegenResponse implements IJsonSchemaValidationProperties {
isString, isNumeric, isInteger, isLong, isNumber, isFloat, isDouble, isDecimal, isByteArray, isBoolean, isDate,
isDateTime, isUuid, isEmail, isModel, isFreeFormObject, isAnyType, isDefault, simpleType, primitiveType,
isMap, isArray, isBinary, isFile, schema, jsonSchema, vendorExtensions, items, additionalProperties,
vars, requiredVars, isNull,
vars, requiredVars, isNull, hasValidation,
getMaxProperties(), getMinProperties(), uniqueItems, getMaxItems(), getMinItems(), getMaxLength(),
getMinLength(), exclusiveMinimum, exclusiveMaximum, getMinimum(), getMaximum(), getPattern(),
is1xx, is2xx, is3xx, is4xx, is5xx);
@ -124,6 +125,7 @@ public class CodegenResponse implements IJsonSchemaValidationProperties {
items == that.items &&
additionalProperties == that.additionalProperties &&
isNull == that.isNull &&
hasValidation == that.hasValidation &&
is1xx == that.is1xx &&
is2xx == that.is2xx &&
is3xx == that.is3xx &&
@ -426,6 +428,7 @@ public class CodegenResponse implements IJsonSchemaValidationProperties {
sb.append(", vars='").append(vars).append('\'');
sb.append(", requiredVars='").append(requiredVars).append('\'');
sb.append(", isNull='").append(isNull);
sb.append(", hasValidation='").append(hasValidation);
sb.append('}');
return sb.toString();
}
@ -456,4 +459,10 @@ public class CodegenResponse implements IJsonSchemaValidationProperties {
public void setIsNull(boolean isNull) {
this.isNull = isNull;
}
@Override
public boolean getHasValidation() { return hasValidation; }
@Override
public void setHasValidation(boolean hasValidation) { this.hasValidation = hasValidation; }
}

View File

@ -2258,6 +2258,7 @@ public class DefaultCodegen implements CodegenConfig {
}
CodegenModel m = CodegenModelFactory.newInstance(CodegenModelType.MODEL);
ModelUtils.syncValidationProperties(schema, m);
if (reservedWords.contains(name)) {
m.name = escapeReservedWord(name);
@ -2305,7 +2306,6 @@ public class DefaultCodegen implements CodegenConfig {
m.setItems(arrayProperty.items);
m.arrayModelType = arrayProperty.complexType;
addParentContainer(m, name, schema);
ModelUtils.syncValidationProperties(schema, m);
} else if (ModelUtils.isNullType(schema)) {
m.isNull = true;
} else if (schema instanceof ComposedSchema) {
@ -2500,8 +2500,6 @@ public class DefaultCodegen implements CodegenConfig {
m.isMap = true;
} else if (ModelUtils.isIntegerSchema(schema)) { // integer type
// NOTE: Integral schemas as CodegenModel is a rare use case and may be removed at a later date.
// Sync of properties is done for consistency with other data types like CodegenParameter/CodegenProperty.
ModelUtils.syncValidationProperties(schema, m);
m.isNumeric = Boolean.TRUE;
if (ModelUtils.isLongSchema(schema)) { // int64/long format
@ -2511,23 +2509,15 @@ public class DefaultCodegen implements CodegenConfig {
}
} else if (ModelUtils.isDateTimeSchema(schema)) {
// NOTE: DateTime schemas as CodegenModel is a rare use case and may be removed at a later date.
// Sync of properties is done for consistency with other data types like CodegenParameter/CodegenProperty.
ModelUtils.syncValidationProperties(schema, m);
m.isDateTime = Boolean.TRUE;
} else if (ModelUtils.isDateSchema(schema)) {
// NOTE: Date schemas as CodegenModel is a rare use case and may be removed at a later date.
// Sync of properties is done for consistency with other data types like CodegenParameter/CodegenProperty.
ModelUtils.syncValidationProperties(schema, m);
m.isDate = Boolean.TRUE;
} else if (ModelUtils.isStringSchema(schema)) {
// NOTE: String schemas as CodegenModel is a rare use case and may be removed at a later date.
// Sync of properties is done for consistency with other data types like CodegenParameter/CodegenProperty.
ModelUtils.syncValidationProperties(schema, m);
m.isString = Boolean.TRUE;
} else if (ModelUtils.isNumberSchema(schema)) {
// NOTE: Number schemas as CodegenModel is a rare use case and may be removed at a later date.
// Sync of properties is done for consistency with other data types like CodegenParameter/CodegenProperty.
ModelUtils.syncValidationProperties(schema, m);
m.isNumeric = Boolean.TRUE;
if (ModelUtils.isFloatSchema(schema)) { // float
m.isFloat = Boolean.TRUE;
@ -2538,7 +2528,6 @@ public class DefaultCodegen implements CodegenConfig {
}
} else if (ModelUtils.isFreeFormObject(openAPI, schema)) {
addAdditionPropertiesToCodeGenModel(m, schema);
ModelUtils.syncValidationProperties(schema, m);
}
if (Boolean.TRUE.equals(schema.getNullable())) {
@ -3077,7 +3066,6 @@ public class DefaultCodegen implements CodegenConfig {
p = unaliasSchema(p, importMapping);
CodegenProperty property = CodegenModelFactory.newInstance(CodegenModelType.PROPERTY);
ModelUtils.syncValidationProperties(p, property);
property.name = toVarName(name);
@ -3144,27 +3132,6 @@ public class DefaultCodegen implements CodegenConfig {
property.isInteger = Boolean.TRUE;
}
if (p.getMinimum() != null) {
property.minimum = String.valueOf(p.getMinimum().longValue());
}
if (p.getMaximum() != null) {
property.maximum = String.valueOf(p.getMaximum().longValue());
}
if (p.getExclusiveMinimum() != null) {
property.exclusiveMinimum = p.getExclusiveMinimum();
}
if (p.getExclusiveMaximum() != null) {
property.exclusiveMaximum = p.getExclusiveMaximum();
}
if (p.getMultipleOf() != null) {
property.multipleOf = p.getMultipleOf();
}
// check if any validation rule defined
// exclusive* are noop without corresponding min/max
if (property.minimum != null || property.maximum != null || p.getMultipleOf() != null)
property.hasValidation = true;
} else if (ModelUtils.isBooleanSchema(p)) { // boolean type
property.isBoolean = true;
property.getter = toBooleanGetter(name);
@ -3177,27 +3144,6 @@ public class DefaultCodegen implements CodegenConfig {
property.isDateTime = true;
} else if (ModelUtils.isDecimalSchema(p)) { // type: string, format: number
property.isDecimal = true;
if (p.getMinimum() != null) {
property.minimum = String.valueOf(p.getMinimum());
}
if (p.getMaximum() != null) {
property.maximum = String.valueOf(p.getMaximum());
}
if (p.getExclusiveMinimum() != null) {
property.exclusiveMinimum = p.getExclusiveMinimum();
}
if (p.getExclusiveMaximum() != null) {
property.exclusiveMaximum = p.getExclusiveMaximum();
}
if (p.getMultipleOf() != null) {
property.multipleOf = p.getMultipleOf();
}
// check if any validation rule defined
// exclusive* are noop without corresponding min/max
if (property.minimum != null || property.maximum != null || p.getMultipleOf() != null) {
property.hasValidation = true;
}
} else if (ModelUtils.isStringSchema(p)) {
if (ModelUtils.isByteArraySchema(p)) {
property.isByteArray = true;
@ -3219,15 +3165,8 @@ public class DefaultCodegen implements CodegenConfig {
} else {
property.isString = true;
}
property.maxLength = p.getMaxLength();
property.minLength = p.getMinLength();
property.pattern = toRegularExpression(p.getPattern());
// check if any validation rule defined
if (property.pattern != null || property.minLength != null || property.maxLength != null)
property.hasValidation = true;
} else if (ModelUtils.isNumberSchema(p)) {
property.isNumeric = Boolean.TRUE;
if (ModelUtils.isFloatSchema(p)) { // float
@ -3238,28 +3177,6 @@ public class DefaultCodegen implements CodegenConfig {
property.isNumber = Boolean.TRUE;
}
if (p.getMinimum() != null) {
property.minimum = String.valueOf(p.getMinimum());
}
if (p.getMaximum() != null) {
property.maximum = String.valueOf(p.getMaximum());
}
if (p.getExclusiveMinimum() != null) {
property.exclusiveMinimum = p.getExclusiveMinimum();
}
if (p.getExclusiveMaximum() != null) {
property.exclusiveMaximum = p.getExclusiveMaximum();
}
if (p.getMultipleOf() != null) {
property.multipleOf = p.getMultipleOf();
}
// check if any validation rule defined
// exclusive* are noop without corresponding min/max
if (property.minimum != null || property.maximum != null || p.getMultipleOf() != null) {
property.hasValidation = true;
}
} else if (isFreeFormObject(p)) {
property.isFreeFormObject = true;
} else if (isAnyTypeSchema(p)) {
@ -3347,8 +3264,6 @@ public class DefaultCodegen implements CodegenConfig {
}
// handle inner property
property.maxItems = p.getMaxItems();
property.minItems = p.getMinItems();
String itemName = null;
if (p.getExtensions() != null && p.getExtensions().get("x-item-name") != null) {
itemName = p.getExtensions().get("x-item-name").toString();
@ -3365,6 +3280,7 @@ public class DefaultCodegen implements CodegenConfig {
property.isMap = true;
property.containerType = "map";
property.baseType = getSchemaType(p);
// TODO remove this hack in the future, code should use minProperties and maxProperties for object schemas
property.minItems = p.getMinProperties();
property.maxItems = p.getMaxProperties();
@ -3983,20 +3899,6 @@ public class DefaultCodegen implements CodegenConfig {
public CodegenResponse fromResponse(String responseCode, ApiResponse response) {
CodegenResponse r = CodegenModelFactory.newInstance(CodegenModelType.RESPONSE);
if (response.getContent() != null && response.getContent().size() > 0) {
// Ensure validation properties from a target schema are persisted on CodegenResponse.
// This ignores any edge case where different schemas have different validations because we don't
// have a way to indicate a preference for response schema and are effective 1:1.
Schema contentSchema = null;
for (MediaType mt : response.getContent().values()) {
if (contentSchema != null) break;
contentSchema = mt.getSchema();
}
if (contentSchema != null) {
ModelUtils.syncValidationProperties(contentSchema, r);
}
}
if ("default".equals(responseCode) || "defaultResponse".equals(responseCode)) {
r.code = "0";
r.isDefault = true;
@ -4030,8 +3932,11 @@ public class DefaultCodegen implements CodegenConfig {
responseSchema = ModelUtils.getSchemaFromResponse(response);
}
r.schema = responseSchema;
if (responseSchema != null && responseSchema.getPattern() != null) {
r.setPattern(toRegularExpression(responseSchema.getPattern()));
if (responseSchema != null) {
ModelUtils.syncValidationProperties(responseSchema, r);
if (responseSchema.getPattern() != null) {
r.setPattern(toRegularExpression(responseSchema.getPattern()));
}
}
r.message = escapeText(response.getDescription());
@ -4219,20 +4124,6 @@ public class DefaultCodegen implements CodegenConfig {
public CodegenParameter fromParameter(Parameter parameter, Set<String> imports) {
CodegenParameter codegenParameter = CodegenModelFactory.newInstance(CodegenModelType.PARAMETER);
if (parameter.getContent() != null && parameter.getContent().size() > 0) {
// Ensure validation properties from a target schema are persisted on CodegenParameter.
// This ignores any edge case where different schemas have different validations because we don't
// have a way to indicate a preference for parameter schema and are effective 1:1.
Schema contentSchema = null;
for (MediaType mt : parameter.getContent().values()) {
if (contentSchema != null) break;
contentSchema = mt.getSchema();
}
if (contentSchema != null) {
ModelUtils.syncValidationProperties(contentSchema, codegenParameter);
}
}
codegenParameter.baseName = parameter.getName();
codegenParameter.description = escapeText(parameter.getDescription());
codegenParameter.unescapedDescription = parameter.getDescription();
@ -4271,6 +4162,7 @@ public class DefaultCodegen implements CodegenConfig {
LOGGER.warn("warning! Schema not found for parameter \"" + parameter.getName() + "\", using String");
parameterSchema = new StringSchema().description("//TODO automatically added by openapi-generator due to missing type definition.");
}
ModelUtils.syncValidationProperties(parameterSchema, codegenParameter);
if (Boolean.TRUE.equals(parameterSchema.getNullable())) { // use nullable defined in the spec
codegenParameter.isNullable = true;
@ -5465,7 +5357,7 @@ public class DefaultCodegen implements CodegenConfig {
if (var.defaultValue != null) {
String enumName = null;
final String enumDefaultValue;
if ("string".equalsIgnoreCase(dataType)) {
if (isDataTypeString(dataType)) {
enumDefaultValue = toEnumValue(var.defaultValue, dataType);
} else {
enumDefaultValue = var.defaultValue;
@ -6029,9 +5921,10 @@ public class DefaultCodegen implements CodegenConfig {
if (StringUtils.isNotBlank(schema.get$ref())) {
name = ModelUtils.getSimpleRef(schema.get$ref());
}
Schema validationSchema = unaliasSchema(schema, importMapping);
schema = ModelUtils.getReferencedSchema(this.openAPI, schema);
ModelUtils.syncValidationProperties(schema, codegenParameter);
ModelUtils.syncValidationProperties(validationSchema, codegenParameter);
if (ModelUtils.isMapSchema(schema)) {
// Schema with additionalproperties: true (including composed schemas with additionalproperties: true)
@ -6159,12 +6052,6 @@ public class DefaultCodegen implements CodegenConfig {
codegenParameter.dataType = codegenProperty.dataType;
codegenParameter.description = codegenProperty.description;
codegenParameter.paramName = toParamName(codegenParameter.baseName);
codegenParameter.minimum = codegenProperty.minimum;
codegenParameter.maximum = codegenProperty.maximum;
codegenParameter.exclusiveMinimum = codegenProperty.exclusiveMinimum;
codegenParameter.exclusiveMaximum = codegenProperty.exclusiveMaximum;
codegenParameter.minLength = codegenProperty.minLength;
codegenParameter.maxLength = codegenProperty.maxLength;
codegenParameter.pattern = codegenProperty.pattern;
codegenParameter.isNullable = codegenProperty.isNullable;

View File

@ -266,9 +266,9 @@ public class DefaultGenerator implements Generator {
// TODO: Allow user to define _which_ servers object in the array to target.
// Configures contextPath/basePath according to api document's servers
URL url = URLPathUtils.getServerURL(openAPI, config.serverVariableOverrides());
contextPath = config.escapeText(url.getPath()).replaceAll("/$", ""); // for backward compatibility
contextPath = removeTrailingSlash(config.escapeText(url.getPath())); // for backward compatibility
basePathWithoutHost = contextPath;
basePath = config.escapeText(URLPathUtils.getHost(openAPI, config.serverVariableOverrides())).replaceAll("/$", "");
basePath = removeTrailingSlash(config.escapeText(URLPathUtils.getHost(openAPI, config.serverVariableOverrides())));
}
private void configureOpenAPIInfo() {
@ -552,7 +552,7 @@ public class DefaultGenerator implements Generator {
}
@SuppressWarnings("unchecked")
private void generateApis(List<File> files, List<Object> allOperations, List<Object> allModels) {
void generateApis(List<File> files, List<Object> allOperations, List<Object> allModels) {
if (!generateApis) {
// TODO: Process these anyway and present info via dryRun?
LOGGER.info("Skipping generation of APIs.");
@ -580,7 +580,7 @@ public class DefaultGenerator implements Generator {
Map<String, Object> operation = processOperations(config, tag, ops, allModels);
URL url = URLPathUtils.getServerURL(openAPI, config.serverVariableOverrides());
operation.put("basePath", basePath);
operation.put("basePathWithoutHost", config.encodePath(url.getPath()).replaceAll("/$", ""));
operation.put("basePathWithoutHost", removeTrailingSlash(config.encodePath(url.getPath())));
operation.put("contextPath", contextPath);
operation.put("baseName", tag);
operation.put("apiPackage", config.apiPackage());
@ -756,7 +756,7 @@ public class DefaultGenerator implements Generator {
}
@SuppressWarnings("unchecked")
private Map<String, Object> buildSupportFileBundle(List<Object> allOperations, List<Object> allModels) {
Map<String, Object> buildSupportFileBundle(List<Object> allOperations, List<Object> allModels) {
Map<String, Object> bundle = new HashMap<>(config.additionalProperties());
bundle.put("apiPackage", config.apiPackage());
@ -806,6 +806,7 @@ public class DefaultGenerator implements Generator {
List<CodegenServer> servers = config.fromServers(openAPI.getServers());
if (servers != null && !servers.isEmpty()) {
servers.forEach(server -> server.url = removeTrailingSlash(server.url));
bundle.put("servers", servers);
bundle.put("hasServers", true);
}
@ -1483,4 +1484,8 @@ public class DefaultGenerator implements Generator {
}
}
private String removeTrailingSlash(String value) {
return StringUtils.removeEnd(value, "/");
}
}

View File

@ -94,4 +94,8 @@ public interface IJsonSchemaValidationProperties {
boolean getIsNull();
void setIsNull(boolean isNull);
boolean getHasValidation();
void setHasValidation(boolean hasValidation);
}

View File

@ -378,38 +378,34 @@ public class InlineModelResolver {
ListIterator<Schema> listIterator = children.listIterator();
while (listIterator.hasNext()) {
Schema component = listIterator.next();
if (component instanceof ObjectSchema || // for inline schema with type:object
(component != null && component.getProperties() != null &&
!component.getProperties().isEmpty())) { // for inline schema without type:object
Schema op = component;
if (op.get$ref() == null && op.getProperties() != null && op.getProperties().size() > 0) {
// If a `title` attribute is defined in the inline schema, codegen uses it to name the
// inline schema. Otherwise, we'll use the default naming such as InlineObject1, etc.
// We know that this is not the best way to name the model.
//
// Such naming strategy may result in issues. If the value of the 'title' attribute
// happens to match a schema defined elsewhere in the specification, 'innerModelName'
// will be the same as that other schema.
//
// To have complete control of the model naming, one can define the model separately
// instead of inline.
String innerModelName = resolveModelName(op.getTitle(), key);
Schema innerModel = modelFromProperty(openAPI, op, innerModelName);
String existing = matchGenerated(innerModel);
if (existing == null) {
openAPI.getComponents().addSchemas(innerModelName, innerModel);
addGenerated(innerModelName, innerModel);
Schema schema = new Schema().$ref(innerModelName);
schema.setRequired(op.getRequired());
listIterator.set(schema);
} else {
Schema schema = new Schema().$ref(existing);
schema.setRequired(op.getRequired());
listIterator.set(schema);
}
if ((component != null) &&
(component.get$ref() == null) &&
((component.getProperties() != null && !component.getProperties().isEmpty()) ||
(component.getEnum() != null && !component.getEnum().isEmpty()))) {
// If a `title` attribute is defined in the inline schema, codegen uses it to name the
// inline schema. Otherwise, we'll use the default naming such as InlineObject1, etc.
// We know that this is not the best way to name the model.
//
// Such naming strategy may result in issues. If the value of the 'title' attribute
// happens to match a schema defined elsewhere in the specification, 'innerModelName'
// will be the same as that other schema.
//
// To have complete control of the model naming, one can define the model separately
// instead of inline.
String innerModelName = resolveModelName(component.getTitle(), key);
Schema innerModel = modelFromProperty(openAPI, component, innerModelName);
String existing = matchGenerated(innerModel);
if (existing == null) {
openAPI.getComponents().addSchemas(innerModelName, innerModel);
addGenerated(innerModelName, innerModel);
Schema schema = new Schema().$ref(innerModelName);
schema.setRequired(component.getRequired());
listIterator.set(schema);
} else {
Schema schema = new Schema().$ref(existing);
schema.setRequired(component.getRequired());
listIterator.set(schema);
}
} else {
// likely a reference to schema (not inline schema)
}
}
}
@ -540,7 +536,7 @@ public class InlineModelResolver {
*/
private String sanitizeName(final String name) {
return name
.replaceAll("^[0-9]", "_") // e.g. 12object => _2object
.replaceAll("^[0-9]", "_$0") // e.g. 12object => _12object
.replaceAll("[^A-Za-z0-9]", "_"); // e.g. io.schema.User name => io_schema_User_name
}
@ -671,6 +667,8 @@ public class InlineModelResolver {
model.setXml(xml);
model.setRequired(object.getRequired());
model.setNullable(object.getNullable());
model.setEnum(object.getEnum());
model.setType(object.getType());
model.setDiscriminator(object.getDiscriminator());
model.setWriteOnly(object.getWriteOnly());
model.setUniqueItems(object.getUniqueItems());

View File

@ -517,6 +517,7 @@ public abstract class AbstractJavaCodegen extends DefaultCodegen implements Code
importMapping.put("JsonReader", "com.google.gson.stream.JsonReader");
importMapping.put("JsonWriter", "com.google.gson.stream.JsonWriter");
importMapping.put("IOException", "java.io.IOException");
importMapping.put("Arrays", "java.util.Arrays");
importMapping.put("Objects", "java.util.Objects");
importMapping.put("StringUtil", invokerPackage + ".StringUtil");
// import JsonCreator if JsonProperty is imported

View File

@ -898,7 +898,8 @@ public abstract class AbstractKotlinCodegen extends DefaultCodegen implements Co
}
@Override
public String toDefaultValue(Schema p) {
public String toDefaultValue(Schema schema) {
Schema p = ModelUtils.getReferencedSchema(this.openAPI, schema);
if (ModelUtils.isBooleanSchema(p)) {
if (p.getDefault() != null) {
return p.getDefault().toString();
@ -921,8 +922,15 @@ public abstract class AbstractKotlinCodegen extends DefaultCodegen implements Co
}
} else if (ModelUtils.isStringSchema(p)) {
if (p.getDefault() != null) {
return "\"" + p.getDefault() + "\"";
String _default = (String) p.getDefault();
if (p.getEnum() == null) {
return "\"" + escapeText(_default) + "\"";
} else {
// convert to enum var name later in postProcessModels
return _default;
}
}
return null;
}
return null;

View File

@ -63,7 +63,8 @@ public class CSharpNetCoreClientCodegen extends AbstractCSharpCodegen {
FrameworkStrategy.NETCOREAPP_2_1,
FrameworkStrategy.NETCOREAPP_3_0,
FrameworkStrategy.NETCOREAPP_3_1,
FrameworkStrategy.NETFRAMEWORK_4_7
FrameworkStrategy.NETFRAMEWORK_4_7,
FrameworkStrategy.NET_5_0
);
private static FrameworkStrategy defaultFramework = FrameworkStrategy.NETSTANDARD_2_0;
protected final Map<String, String> frameworks;
@ -908,6 +909,8 @@ public class CSharpNetCoreClientCodegen extends AbstractCSharpCodegen {
};
static FrameworkStrategy NETFRAMEWORK_4_7 = new FrameworkStrategy("net47", ".NET Framework 4.7 compatible", "net47", Boolean.FALSE) {
};
static FrameworkStrategy NET_5_0 = new FrameworkStrategy("net5.0", ".NET 5.0 compatible", "net5.0", Boolean.FALSE) {
};
protected String name;
protected String description;
protected String testTargetFramework;

View File

@ -23,6 +23,7 @@ import org.openapitools.codegen.CodegenType;
import org.openapitools.codegen.SupportingFile;
import org.openapitools.codegen.meta.features.DocumentationFeature;
import org.openapitools.codegen.meta.features.GlobalFeature;
import org.openapitools.codegen.meta.features.SecurityFeature;
import java.io.File;
@ -42,6 +43,9 @@ public class CppQt5ClientCodegen extends CppQt5AbstractCodegen implements Codege
.includeDocumentationFeatures(DocumentationFeature.Readme)
.includeGlobalFeatures(GlobalFeature.ParameterizedServer)
.includeGlobalFeatures(GlobalFeature.MultiServer)
.includeSecurityFeatures(SecurityFeature.BasicAuth)
.includeSecurityFeatures(SecurityFeature.ApiKey)
.includeSecurityFeatures(SecurityFeature.BearerToken)
);
// set the output folder here

View File

@ -168,6 +168,7 @@ public class ElixirClientCodegen extends DefaultCodegen implements CodegenConfig
Arrays.asList(
"Integer",
"Float",
"Decimal",
"Boolean",
"String",
"List",
@ -175,7 +176,8 @@ public class ElixirClientCodegen extends DefaultCodegen implements CodegenConfig
"Map",
"Tuple",
"PID",
"DateTime"
"DateTime",
"map()" // This is a workaround, since the DefaultCodeGen uses our elixir TypeSpec datetype to evaluate the primitive
)
);
@ -510,8 +512,7 @@ public class ElixirClientCodegen extends DefaultCodegen implements CodegenConfig
} else if (ModelUtils.isDateTimeSchema(p)) {
return "DateTime.t";
} else if (ModelUtils.isObjectSchema(p)) {
// TODO How to map it?
return super.getTypeDeclaration(p);
return "map()";
} else if (ModelUtils.isIntegerSchema(p)) {
return "integer()";
} else if (ModelUtils.isNumberSchema(p)) {
@ -520,9 +521,8 @@ public class ElixirClientCodegen extends DefaultCodegen implements CodegenConfig
return "String.t";
} else if (ModelUtils.isBooleanSchema(p)) {
return "boolean()";
} else if (!StringUtils.isEmpty(p.get$ref())) { // model
// How to map it?
return super.getTypeDeclaration(p);
} else if (!StringUtils.isEmpty(p.get$ref())) {
return this.moduleName + ".Model." + super.getTypeDeclaration(p) + ".t";
} else if (ModelUtils.isFileSchema(p)) {
return "String.t";
} else if (ModelUtils.isStringSchema(p)) {
@ -593,12 +593,12 @@ public class ElixirClientCodegen extends DefaultCodegen implements CodegenConfig
this.isDefinedDefault = (this.code.equals("0") || this.code.equals("default"));
}
public String codeMappingKey(){
if(this.isDefinedDefault) {
public String codeMappingKey() {
if (this.isDefinedDefault) {
return ":default";
}
if(code.matches("^\\d{3}$")){
if (code.matches("^\\d{3}$")) {
return code;
}
@ -818,6 +818,23 @@ public class ElixirClientCodegen extends DefaultCodegen implements CodegenConfig
sb.append(".t");
}
}
private boolean getRequiresHttpcWorkaround() {
// Only POST/PATCH/PUT are affected from the httpc bug
if (!(this.httpMethod.equals("POST") || this.httpMethod.equals("PATCH") || this.httpMethod.equals("PUT"))) {
return false;
}
// If theres something required for the body, the workaround is not required
for (CodegenParameter requiredParam : this.requiredParams) {
if (requiredParam.isBodyParam || requiredParam.isFormParam) {
return false;
}
}
// In case there is nothing for the body, the operation requires the workaround
return true;
}
}
class ExtendedCodegenModel extends CodegenModel {

View File

@ -142,7 +142,6 @@ public class JavaClientCodegen extends AbstractJavaCodegen
cliOptions.add(CliOption.newBoolean(PARCELABLE_MODEL, "Whether to generate models for Android that implement Parcelable with the okhttp-gson library."));
cliOptions.add(CliOption.newBoolean(USE_PLAY_WS, "Use Play! Async HTTP client (Play WS API)"));
cliOptions.add(CliOption.newString(PLAY_VERSION, "Version of Play! Framework (possible values \"play24\" (Deprecated), \"play25\" (Deprecated), \"play26\" (Default))"));
cliOptions.add(CliOption.newBoolean(SUPPORT_JAVA6, "Whether to support Java6 with the Jersey1 library. This option has been deprecated and will be removed in the 5.x release"));
cliOptions.add(CliOption.newBoolean(USE_BEANVALIDATION, "Use BeanValidation API annotations"));
cliOptions.add(CliOption.newBoolean(PERFORM_BEANVALIDATION, "Perform BeanValidation"));
cliOptions.add(CliOption.newBoolean(USE_GZIP_FEATURE, "Send gzip-encoded requests"));
@ -154,7 +153,7 @@ public class JavaClientCodegen extends AbstractJavaCodegen
cliOptions.add(CliOption.newBoolean(USE_ABSTRACTION_FOR_FILES, "Use alternative types instead of java.io.File to allow passing bytes without a file on disk. Available on " + RESTTEMPLATE + " library"));
cliOptions.add(CliOption.newBoolean(DYNAMIC_OPERATIONS, "Generate operations dynamically at runtime from an OAS", this.dynamicOperations));
supportedLibraries.put(JERSEY1, "HTTP client: Jersey client 1.19.x. JSON processing: Jackson 2.9.x. Enable Java6 support using '-DsupportJava6=true'. Enable gzip request encoding using '-DuseGzipFeature=true'. IMPORTANT NOTE: jersey 1.x is no longer actively maintained so please upgrade to 'jersey2' or other HTTP libaries instead.");
supportedLibraries.put(JERSEY1, "HTTP client: Jersey client 1.19.x. JSON processing: Jackson 2.9.x. Enable gzip request encoding using '-DuseGzipFeature=true'. IMPORTANT NOTE: jersey 1.x is no longer actively maintained so please upgrade to 'jersey2' or other HTTP libaries instead.");
supportedLibraries.put(JERSEY2, "HTTP client: Jersey client 2.25.1. JSON processing: Jackson 2.9.x");
supportedLibraries.put(FEIGN, "HTTP client: OpenFeign 10.x. JSON processing: Jackson 2.9.x.");
supportedLibraries.put(OKHTTP_GSON, "[DEFAULT] HTTP client: OkHttp 3.x. JSON processing: Gson 2.8.x. Enable Parcelable models on Android using '-DparcelableModel=true'. Enable gzip request encoding using '-DuseGzipFeature=true'.");
@ -392,6 +391,10 @@ public class JavaClientCodegen extends AbstractJavaCodegen
forceSerializationLibrary(SERIALIZATION_LIBRARY_JACKSON);
supportingFiles.add(new SupportingFile("ParamExpander.mustache", invokerFolder, "ParamExpander.java"));
supportingFiles.add(new SupportingFile("EncodingUtils.mustache", invokerFolder, "EncodingUtils.java"));
supportingFiles.add(new SupportingFile("auth/DefaultApi20Impl.mustache", authFolder, "DefaultApi20Impl.java"));
supportingFiles.add(new SupportingFile("auth/OauthPasswordGrant.mustache", authFolder, "OauthPasswordGrant.java"));
supportingFiles.add(new SupportingFile("auth/OauthClientCredentialsGrant.mustache", authFolder, "OauthClientCredentialsGrant.java"));
} else if (OKHTTP_GSON.equals(getLibrary()) || StringUtils.isEmpty(getLibrary())) {
// the "okhttp-gson" library template requires "ApiCallback.mustache" for async call
supportingFiles.add(new SupportingFile("ApiCallback.mustache", invokerFolder, "ApiCallback.java"));
@ -851,35 +854,35 @@ public class JavaClientCodegen extends AbstractJavaCodegen
}
}
}
}
// add implements for serializable/parcelable to all models
for (Object _mo : models) {
Map<String, Object> mo = (Map<String, Object>) _mo;
CodegenModel cm = (CodegenModel) mo.get("model");
// add implements for serializable/parcelable to all models
for (Object _mo : models) {
Map<String, Object> mo = (Map<String, Object>) _mo;
CodegenModel cm = (CodegenModel) mo.get("model");
cm.getVendorExtensions().putIfAbsent("x-implements", new ArrayList<String>());
if (JERSEY2.equals(getLibrary()) || NATIVE.equals(getLibrary())) {
cm.getVendorExtensions().put("x-implements", new ArrayList<String>());
cm.getVendorExtensions().putIfAbsent("x-implements", new ArrayList<String>());
if (JERSEY2.equals(getLibrary()) || NATIVE.equals(getLibrary())) {
cm.getVendorExtensions().put("x-implements", new ArrayList<String>());
if (cm.oneOf != null && !cm.oneOf.isEmpty() && cm.oneOf.contains("ModelNull")) {
// if oneOf contains "null" type
cm.isNullable = true;
cm.oneOf.remove("ModelNull");
}
if (cm.anyOf != null && !cm.anyOf.isEmpty() && cm.anyOf.contains("ModelNull")) {
// if anyOf contains "null" type
cm.isNullable = true;
cm.anyOf.remove("ModelNull");
}
if (cm.oneOf != null && !cm.oneOf.isEmpty() && cm.oneOf.contains("ModelNull")) {
// if oneOf contains "null" type
cm.isNullable = true;
cm.oneOf.remove("ModelNull");
}
if (this.parcelableModel) {
((ArrayList<String>) cm.getVendorExtensions().get("x-implements")).add("Parcelable");
}
if (this.serializableModel) {
((ArrayList<String>) cm.getVendorExtensions().get("x-implements")).add("Serializable");
if (cm.anyOf != null && !cm.anyOf.isEmpty() && cm.anyOf.contains("ModelNull")) {
// if anyOf contains "null" type
cm.isNullable = true;
cm.anyOf.remove("ModelNull");
}
}
if (this.parcelableModel) {
((ArrayList<String>) cm.getVendorExtensions().get("x-implements")).add("Parcelable");
}
if (this.serializableModel) {
((ArrayList<String>) cm.getVendorExtensions().get("x-implements")).add("Serializable");
}
}
return objs;

View File

@ -106,6 +106,7 @@ public class JavaUndertowServerCodegen extends AbstractJavaCodegen {
// keep the yaml in config folder for framework validation.
supportingFiles.add(new SupportingFile("openapi.mustache", ("src.main.resources.config").replace(".", java.io.File.separator), "openapi.json"));
supportingFiles.add(new SupportingFile("interface.mustache", (String.format(Locale.ROOT, "src.main.java.%s", apiPackage)).replace(".", java.io.File.separator), "PathHandlerInterface.java"));
supportingFiles.add(new SupportingFile("handler.mustache", (String.format(Locale.ROOT, "src.main.java.%s", apiPackage)).replace(".", java.io.File.separator), "PathHandlerProvider.java"));
supportingFiles.add(new SupportingFile("service.mustache", ("src.main.resources.META-INF.services").replace(".", java.io.File.separator), "com.networknt.server.HandlerProvider"));

View File

@ -1082,7 +1082,12 @@ public class PowerShellClientCodegen extends DefaultCodegen implements CodegenCo
if (StringUtils.isEmpty(codegenParameter.example)) {
return "\"" + codegenParameter.example + "\"";
} else {
return "\"" + codegenParameter.paramName + "_example\"";
if (Boolean.TRUE.equals(codegenParameter.isEnum)) { // enum
List<Object> enumValues = (List<Object>) codegenParameter.allowableValues.get("values");
return "\"" + String.valueOf(enumValues.get(0)) + "\"";
} else {
return "\"" + codegenParameter.paramName + "_example\"";
}
}
} else if ("Boolean".equals(codegenParameter.dataType) ||
"System.Nullable[Boolean]".equals(codegenParameter.dataType)) { // boolean
@ -1124,7 +1129,12 @@ public class PowerShellClientCodegen extends DefaultCodegen implements CodegenCo
if (StringUtils.isEmpty(codegenProperty.example)) {
return "\"" + codegenProperty.example + "\"";
} else {
return "\"" + codegenProperty.name + "_example\"";
if (Boolean.TRUE.equals(codegenProperty.isEnum)) { // enum
List<Object> enumValues = (List<Object>) codegenProperty.allowableValues.get("values");
return "\"" + String.valueOf(enumValues.get(0)) + "\"";
} else {
return "\"" + codegenProperty.name + "_example\"";
}
}
} else if ("Boolean".equals(codegenProperty.dataType) ||
"System.Nullable[Boolean]".equals(codegenProperty.dataType)) { // boolean
@ -1173,7 +1183,7 @@ public class PowerShellClientCodegen extends DefaultCodegen implements CodegenCo
processedModelMap.put(model, 1);
}
example = "(Initialize-" + codegenModel.name;
example = "(Initialize-" + codegenModel.name + " ";
List<String> propertyExamples = new ArrayList<>();
for (CodegenProperty codegenProperty : codegenModel.allVars) {
propertyExamples.add("-" + codegenProperty.name + " " + constructExampleCode(codegenProperty, modelMaps, processedModelMap));

View File

@ -22,6 +22,7 @@ import io.swagger.v3.oas.models.OpenAPI;
import io.swagger.v3.oas.models.Operation;
import io.swagger.v3.oas.models.info.Info;
import io.swagger.v3.oas.models.media.ArraySchema;
import io.swagger.v3.oas.models.media.ComposedSchema;
import io.swagger.v3.oas.models.media.FileSchema;
import io.swagger.v3.oas.models.media.Schema;
import io.swagger.v3.oas.models.media.XML;
@ -96,14 +97,11 @@ public class RustServerCodegen extends DefaultCodegen implements CodegenConfig {
SecurityFeature.OAuth2_Implicit
))
.excludeGlobalFeatures(
GlobalFeature.XMLStructureDefinitions,
GlobalFeature.LinkObjects,
GlobalFeature.ParameterStyling
)
.excludeSchemaSupportFeatures(
SchemaSupportFeature.Polymorphism,
SchemaSupportFeature.Union,
SchemaSupportFeature.Composite
SchemaSupportFeature.Polymorphism
)
.excludeParameterFeatures(
ParameterFeature.Cookie
@ -400,7 +398,7 @@ public class RustServerCodegen extends DefaultCodegen implements CodegenConfig {
}
// model name starts with number
else if (name.matches("^\\d.*")) {
else if (camelizedName.matches("^\\d.*")) {
// e.g. 200Response => Model200Response (after camelize)
camelizedName = "Model" + camelizedName;
LOGGER.warn(name + " (model name starts with number) cannot be used as model name. Renamed to " + camelizedName);
@ -1191,8 +1189,11 @@ public class RustServerCodegen extends DefaultCodegen implements CodegenConfig {
@Override
public CodegenModel fromModel(String name, Schema model) {
LOGGER.trace("Creating model from schema: {}", model);
Map<String, Schema> allDefinitions = ModelUtils.getSchemas(this.openAPI);
CodegenModel mdl = super.fromModel(name, model);
mdl.vendorExtensions.put("x-upper-case-name", name.toUpperCase(Locale.ROOT));
if (!StringUtils.isEmpty(model.get$ref())) {
Schema schema = allDefinitions.get(ModelUtils.getSimpleRef(model.get$ref()));
@ -1233,6 +1234,8 @@ public class RustServerCodegen extends DefaultCodegen implements CodegenConfig {
} else {
mdl.arrayModelType = toModelName(mdl.arrayModelType);
}
} else if ((mdl.anyOf.size() > 0) || (mdl.oneOf.size() > 0)) {
mdl.dataType = getSchemaType(model);
}
if (mdl.xmlNamespace != null) {
@ -1245,6 +1248,8 @@ public class RustServerCodegen extends DefaultCodegen implements CodegenConfig {
mdl.additionalPropertiesType = getTypeDeclaration(additionalProperties);
}
LOGGER.trace("Created model: {}", mdl);
return mdl;
}
@ -1403,6 +1408,28 @@ public class RustServerCodegen extends DefaultCodegen implements CodegenConfig {
return defaultValue;
}
@Override
public String toOneOfName(List<String> names, ComposedSchema composedSchema) {
List<Schema> schemas = ModelUtils.getInterfaces(composedSchema);
List<String> types = new ArrayList<>();
for (Schema s : schemas) {
types.add(getTypeDeclaration(s));
}
return "swagger::OneOf" + types.size() + "<" + String.join(",", types) + ">";
}
@Override
public String toAnyOfName(List<String> names, ComposedSchema composedSchema) {
List<Schema> schemas = ModelUtils.getInterfaces(composedSchema);
List<String> types = new ArrayList<>();
for (Schema s : schemas) {
types.add(getTypeDeclaration(s));
}
return "swagger::AnyOf" + types.size() + "<" + String.join(",", types) + ">";
}
@Override
public void postProcessModelProperty(CodegenModel model, CodegenProperty property) {
super.postProcessModelProperty(model, property);
@ -1529,6 +1556,8 @@ public class RustServerCodegen extends DefaultCodegen implements CodegenConfig {
Map<String, Object> mo = (Map<String, Object>) _mo;
CodegenModel cm = (CodegenModel) mo.get("model");
LOGGER.trace("Post processing model: {}", cm);
if (cm.dataType != null && cm.dataType.equals("object")) {
// Object isn't a sensible default. Instead, we set it to
// 'null'. This ensures that we treat this model as a struct

View File

@ -833,6 +833,11 @@ public class SpringCodegen extends AbstractJavaCodegen
model.imports.add("JsonCreator");
}
}
// Add imports for java.util.Arrays
if (property.isByteArray) {
model.imports.add("Arrays");
}
}
@Override

View File

@ -540,9 +540,7 @@ public class TypeScriptAngularClientCodegen extends AbstractTypeScriptClientCode
for (String name : cm.imports) {
if (name.indexOf(" | ") >= 0) {
String[] parts = name.split(" \\| ");
for (String s : parts) {
newImports.add(s);
}
Collections.addAll(newImports, parts);
} else {
newImports.add(name);
}

View File

@ -104,6 +104,7 @@ public class TypeScriptAxiosClientCodegen extends AbstractTypeScriptClientCodege
supportingFiles.add(new SupportingFile("index.mustache", "", "index.ts"));
supportingFiles.add(new SupportingFile("baseApi.mustache", "", "base.ts"));
supportingFiles.add(new SupportingFile("common.mustache", "", "common.ts"));
supportingFiles.add(new SupportingFile("api.mustache", "", "api.ts"));
supportingFiles.add(new SupportingFile("configuration.mustache", "", "configuration.ts"));
supportingFiles.add(new SupportingFile("git_push.sh.mustache", "", "git_push.sh"));

View File

@ -0,0 +1,552 @@
/*
* 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
*
* http://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.media.Schema;
import org.openapitools.codegen.*;
import org.openapitools.codegen.meta.GeneratorMetadata;
import org.openapitools.codegen.meta.Stability;
import org.openapitools.codegen.meta.features.*;
import org.openapitools.codegen.utils.ModelUtils;
import org.openapitools.codegen.utils.SemVer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.util.*;
import static org.apache.commons.lang3.StringUtils.capitalize;
import static org.openapitools.codegen.utils.StringUtils.*;
public class TypeScriptNestjsClientCodegen extends AbstractTypeScriptClientCodegen {
private static final Logger LOGGER = LoggerFactory.getLogger(TypeScriptNestjsClientCodegen.class);
private static String CLASS_NAME_SUFFIX_PATTERN = "^[a-zA-Z0-9]*$";
private static String FILE_NAME_SUFFIX_PATTERN = "^[a-zA-Z0-9.-]*$";
public static final String NPM_REPOSITORY = "npmRepository";
public static final String WITH_INTERFACES = "withInterfaces";
public static final String TAGGED_UNIONS = "taggedUnions";
public static final String NEST_VERSION = "nestVersion";
public static final String SERVICE_SUFFIX = "serviceSuffix";
public static final String SERVICE_FILE_SUFFIX = "serviceFileSuffix";
public static final String MODEL_SUFFIX = "modelSuffix";
public static final String MODEL_FILE_SUFFIX = "modelFileSuffix";
public static final String FILE_NAMING = "fileNaming";
public static final String STRING_ENUMS = "stringEnums";
public static final String STRING_ENUMS_DESC = "Generate string enums instead of objects for enum values.";
protected String nestVersion = "6.0.0";
protected String npmRepository = null;
protected String serviceSuffix = "Service";
protected String serviceFileSuffix = ".service";
protected String modelSuffix = "";
protected String modelFileSuffix = "";
protected String fileNaming = "camelCase";
protected Boolean stringEnums = false;
private boolean taggedUnions = false;
public TypeScriptNestjsClientCodegen() {
super();
generatorMetadata = GeneratorMetadata.newBuilder(generatorMetadata)
.stability(Stability.EXPERIMENTAL)
.build();
this.outputFolder = "generated-code/typescript-nestjs";
supportsMultipleInheritance = true;
embeddedTemplateDir = templateDir = "typescript-nestjs";
modelTemplateFiles.put("model.mustache", ".ts");
apiTemplateFiles.put("api.service.mustache", ".ts");
languageSpecificPrimitives.add("Blob");
typeMapping.put("file", "Blob");
apiPackage = "api";
modelPackage = "model";
this.cliOptions.add(new CliOption(NPM_REPOSITORY,
"Use this property to set an url your private npmRepo in the package.json"));
this.cliOptions.add(CliOption.newBoolean(WITH_INTERFACES,
"Setting this property to true will generate interfaces next to the default class implementations.",
false));
this.cliOptions.add(CliOption.newBoolean(TAGGED_UNIONS,
"Use discriminators to create tagged unions instead of extending interfaces.",
this.taggedUnions));
this.cliOptions.add(new CliOption(NEST_VERSION, "The version of Nestjs.").defaultValue(this.nestVersion));
this.cliOptions.add(new CliOption(SERVICE_SUFFIX, "The suffix of the generated service.").defaultValue(this.serviceSuffix));
this.cliOptions.add(new CliOption(SERVICE_FILE_SUFFIX, "The suffix of the file of the generated service (service<suffix>.ts).").defaultValue(this.serviceFileSuffix));
this.cliOptions.add(new CliOption(MODEL_SUFFIX, "The suffix of the generated model."));
this.cliOptions.add(new CliOption(MODEL_FILE_SUFFIX, "The suffix of the file of the generated model (model<suffix>.ts)."));
this.cliOptions.add(new CliOption(FILE_NAMING, "Naming convention for the output files: 'camelCase', 'kebab-case'.").defaultValue(this.fileNaming));
this.cliOptions.add(new CliOption(STRING_ENUMS, STRING_ENUMS_DESC).defaultValue(String.valueOf(this.stringEnums)));
}
@Override
protected void addAdditionPropertiesToCodeGenModel(CodegenModel codegenModel, Schema schema) {
codegenModel.additionalPropertiesType = getTypeDeclaration(getAdditionalProperties(schema));
addImport(codegenModel, codegenModel.additionalPropertiesType);
}
@Override
public String getName() {
return "typescript-nestjs";
}
@Override
public String getHelp() {
return "Generates a TypeScript Nestjs 6.x client library.";
}
@Override
public void processOpts() {
super.processOpts();
supportingFiles.add(
new SupportingFile("models.mustache", modelPackage().replace('.', File.separatorChar), "models.ts"));
supportingFiles
.add(new SupportingFile("apis.mustache", apiPackage().replace('.', File.separatorChar), "api.ts"));
supportingFiles.add(new SupportingFile("index.mustache", getIndexDirectory(), "index.ts"));
supportingFiles.add(new SupportingFile("api.module.mustache", getIndexDirectory(), "api.module.ts"));
supportingFiles.add(new SupportingFile("configuration.mustache", getIndexDirectory(), "configuration.ts"));
supportingFiles.add(new SupportingFile("variables.mustache", getIndexDirectory(), "variables.ts"));
//supportingFiles.add(new SupportingFile("encoder.mustache", getIndexDirectory(), "encoder.ts"));
supportingFiles.add(new SupportingFile("gitignore", "", ".gitignore"));
supportingFiles.add(new SupportingFile("git_push.sh.mustache", "", "git_push.sh"));
supportingFiles.add(new SupportingFile("README.mustache", getIndexDirectory(), "README.md"));
// determine Nestjs version
SemVer nestVersion;
if (additionalProperties.containsKey(NEST_VERSION)) {
nestVersion = new SemVer(additionalProperties.get(NEST_VERSION).toString());
} else {
nestVersion = new SemVer(this.nestVersion);
LOGGER.info("generating code for Nestjs {} ...", nestVersion);
LOGGER.info(" (you can select the nestjs version by setting the additionalProperty nestVersion)");
}
if (additionalProperties.containsKey(NPM_NAME)) {
addNpmPackageGeneration(nestVersion);
}
if (additionalProperties.containsKey(STRING_ENUMS)) {
setStringEnums(Boolean.valueOf(additionalProperties.get(STRING_ENUMS).toString()));
additionalProperties.put("stringEnums", getStringEnums());
if (getStringEnums()) {
enumSuffix = "";
classEnumSeparator = "";
}
}
if (additionalProperties.containsKey(WITH_INTERFACES)) {
boolean withInterfaces = Boolean.parseBoolean(additionalProperties.get(WITH_INTERFACES).toString());
if (withInterfaces) {
apiTemplateFiles.put("apiInterface.mustache", "Interface.ts");
}
}
if (additionalProperties.containsKey(TAGGED_UNIONS)) {
taggedUnions = Boolean.parseBoolean(additionalProperties.get(TAGGED_UNIONS).toString());
}
additionalProperties.put(NEST_VERSION, nestVersion);
additionalProperties.put("injectionToken", nestVersion.atLeast("4.0.0") ? "InjectionToken" : "OpaqueToken");
additionalProperties.put("injectionTokenTyped", nestVersion.atLeast("4.0.0"));
additionalProperties.put("useHttpClient", nestVersion.atLeast("4.3.0"));
if (additionalProperties.containsKey(SERVICE_SUFFIX)) {
serviceSuffix = additionalProperties.get(SERVICE_SUFFIX).toString();
validateClassSuffixArgument("Service", serviceSuffix);
}
if (additionalProperties.containsKey(SERVICE_FILE_SUFFIX)) {
serviceFileSuffix = additionalProperties.get(SERVICE_FILE_SUFFIX).toString();
validateFileSuffixArgument("Service", serviceFileSuffix);
}
if (additionalProperties.containsKey(MODEL_SUFFIX)) {
modelSuffix = additionalProperties.get(MODEL_SUFFIX).toString();
validateClassSuffixArgument("Model", modelSuffix);
}
if (additionalProperties.containsKey(MODEL_FILE_SUFFIX)) {
modelFileSuffix = additionalProperties.get(MODEL_FILE_SUFFIX).toString();
validateFileSuffixArgument("Model", modelFileSuffix);
}
if (additionalProperties.containsKey(FILE_NAMING)) {
this.setFileNaming(additionalProperties.get(FILE_NAMING).toString());
}
}
private void addNpmPackageGeneration(SemVer nestVersion) {
if (additionalProperties.containsKey(NPM_REPOSITORY)) {
this.setNpmRepository(additionalProperties.get(NPM_REPOSITORY).toString());
}
additionalProperties.put("tsVersion", ">=3.6.0. <4.0.0");
//Files for building our lib
supportingFiles.add(new SupportingFile("package.mustache", getIndexDirectory(), "package.json"));
supportingFiles.add(new SupportingFile("tsconfig.build.mustache", getIndexDirectory(), "tsconfig.build.json"));
supportingFiles.add(new SupportingFile("tsconfig.mustache", getIndexDirectory(), "tsconfig.json"));
supportingFiles.add(new SupportingFile("tslint.mustache", getIndexDirectory(), "tslint.json"));
}
private String getIndexDirectory() {
String indexPackage = modelPackage.substring(0, Math.max(0, modelPackage.lastIndexOf('.')));
return indexPackage.replace('.', File.separatorChar);
}
public void setStringEnums(boolean value) {
stringEnums = value;
}
public Boolean getStringEnums() {
return stringEnums;
}
@Override
public boolean isDataTypeFile(final String dataType) {
return dataType != null && dataType.equals("Blob");
}
@Override
public String getTypeDeclaration(Schema p) {
if (ModelUtils.isFileSchema(p)) {
return "Blob";
} else {
return super.getTypeDeclaration(p);
}
}
@Override
public String getSchemaType(Schema p) {
String openAPIType = super.getSchemaType(p);
if (isLanguagePrimitive(openAPIType) || isLanguageGenericType(openAPIType)) {
return openAPIType;
}
applyLocalTypeMapping(openAPIType);
return openAPIType;
}
private String applyLocalTypeMapping(String type) {
if (typeMapping.containsKey(type)) {
type = typeMapping.get(type);
}
return type;
}
private boolean isLanguagePrimitive(String type) {
return languageSpecificPrimitives.contains(type);
}
private boolean isLanguageGenericType(String type) {
for (String genericType : languageGenericTypes) {
if (type.startsWith(genericType + "<")) {
return true;
}
}
return false;
}
@Override
public void postProcessParameter(CodegenParameter parameter) {
super.postProcessParameter(parameter);
parameter.dataType = applyLocalTypeMapping(parameter.dataType);
}
@Override
public Map<String, Object> postProcessOperationsWithModels(Map<String, Object> operations, List<Object> allModels) {
Map<String, Object> objs = (Map<String, Object>) operations.get("operations");
// Add filename information for api imports
objs.put("apiFilename", getApiFilenameFromClassname(objs.get("classname").toString()));
List<CodegenOperation> ops = (List<CodegenOperation>) objs.get("operation");
boolean hasSomeFormParams = false;
for (CodegenOperation op : ops) {
if (op.getHasFormParams()) {
hasSomeFormParams = true;
}
op.httpMethod = op.httpMethod.toLowerCase(Locale.ENGLISH);
// Prep a string buffer where we're going to set up our new version of the string.
StringBuilder pathBuffer = new StringBuilder();
StringBuilder parameterName = new StringBuilder();
int insideCurly = 0;
// Iterate through existing string, one character at a time.
for (int i = 0; i < op.path.length(); i++) {
switch (op.path.charAt(i)) {
case '{':
// We entered curly braces, so track that.
insideCurly++;
// Add the more complicated component instead of just the brace.
pathBuffer.append("${encodeURIComponent(String(");
break;
case '}':
// We exited curly braces, so track that.
insideCurly--;
// Add the more complicated component instead of just the brace.
CodegenParameter parameter = findPathParameterByName(op, parameterName.toString());
pathBuffer.append(toVarName(parameterName.toString()));
if (parameter != null && parameter.isDateTime) {
pathBuffer.append(".toISOString()");
}
pathBuffer.append("))}");
parameterName.setLength(0);
break;
default:
char nextChar = op.path.charAt(i);
if (insideCurly > 0) {
parameterName.append(nextChar);
} else {
pathBuffer.append(nextChar);
}
break;
}
}
// Overwrite path to TypeScript template string, after applying everything we just did.
op.path = pathBuffer.toString();
}
operations.put("hasSomeFormParams", hasSomeFormParams);
// Add additional filename information for model imports in the services
List<Map<String, Object>> imports = (List<Map<String, Object>>) operations.get("imports");
for (Map<String, Object> im : imports) {
im.put("filename", im.get("import"));
im.put("classname", im.get("classname"));
}
return operations;
}
/**
* Finds and returns a path parameter of an operation by its name
*
* @param operation the operation
* @param parameterName the name of the parameter
* @return param
*/
private CodegenParameter findPathParameterByName(CodegenOperation operation, String parameterName) {
for (CodegenParameter param : operation.pathParams) {
if (param.baseName.equals(parameterName)) {
return param;
}
}
return null;
}
@Override
public Map<String, Object> postProcessModels(Map<String, Object> objs) {
Map<String, Object> result = super.postProcessModels(objs);
return postProcessModelsEnum(result);
}
@Override
public Map<String, Object> postProcessAllModels(Map<String, Object> objs) {
Map<String, Object> result = super.postProcessAllModels(objs);
for (Map.Entry<String, Object> entry : result.entrySet()) {
Map<String, Object> inner = (Map<String, Object>) entry.getValue();
List<Map<String, Object>> models = (List<Map<String, Object>>) inner.get("models");
for (Map<String, Object> mo : models) {
CodegenModel cm = (CodegenModel) mo.get("model");
if (taggedUnions) {
mo.put(TAGGED_UNIONS, true);
if (cm.discriminator != null && cm.children != null) {
for (CodegenModel child : cm.children) {
cm.imports.add(child.classname);
}
}
if (cm.parent != null) {
cm.imports.remove(cm.parent);
}
}
// Add additional filename information for imports
Set<String> parsedImports = parseImports(cm);
mo.put("tsImports", toTsImports(cm, parsedImports));
}
}
return result;
}
/**
* Parse imports
*/
private Set<String> parseImports(CodegenModel cm) {
Set<String> newImports = new HashSet<String>();
if (cm.imports.size() > 0) {
for (String name : cm.imports) {
if (name.indexOf(" | ") >= 0) {
String[] parts = name.split(" \\| ");
for (String s : parts) {
newImports.add(s);
}
} else {
newImports.add(name);
}
}
}
return newImports;
}
private List<Map<String, String>> toTsImports(CodegenModel cm, Set<String> imports) {
List<Map<String, String>> tsImports = new ArrayList<>();
for (String im : imports) {
if (!im.equals(cm.classname)) {
HashMap<String, String> tsImport = new HashMap<>();
// TVG: This is used as class name in the import statements of the model file
tsImport.put("classname", im);
tsImport.put("filename", toModelFilename(removeModelPrefixSuffix(im)));
tsImports.add(tsImport);
}
}
return tsImports;
}
@Override
public String toApiName(String name) {
if (name.length() == 0) {
return "DefaultService";
}
return camelize(name) + serviceSuffix;
}
@Override
public String toApiFilename(String name) {
if (name.length() == 0) {
return "default.service";
}
return this.convertUsingFileNamingConvention(name) + serviceFileSuffix;
}
@Override
public String toApiImport(String name) {
return apiPackage() + "/" + toApiFilename(name);
}
@Override
public String toModelFilename(String name) {
return this.convertUsingFileNamingConvention(this.sanitizeName(name)) + modelFileSuffix;
}
@Override
public String toModelImport(String name) {
return modelPackage() + "/" + toModelFilename(name);
}
public String getNpmRepository() {
return npmRepository;
}
public void setNpmRepository(String npmRepository) {
this.npmRepository = npmRepository;
}
private String getApiFilenameFromClassname(String classname) {
String name = classname.substring(0, classname.length() - serviceSuffix.length());
return toApiFilename(name);
}
@Override
public String toModelName(String name) {
String modelName = super.toModelName(name);
if (modelSuffix.length() == 0 || modelName.endsWith(modelSuffix)) {
return modelName;
}
return modelName + modelSuffix;
}
public String removeModelPrefixSuffix(String name) {
String result = name;
if (modelSuffix.length() > 0 && result.endsWith(modelSuffix)) {
result = result.substring(0, result.length() - modelSuffix.length());
}
String prefix = capitalize(this.modelNamePrefix);
String suffix = capitalize(this.modelNameSuffix);
if (prefix.length() > 0 && result.startsWith(prefix)) {
result = result.substring(prefix.length());
}
if (suffix.length() > 0 && result.endsWith(suffix)) {
result = result.substring(0, result.length() - suffix.length());
}
return result;
}
/**
* Validates that the given string value only contains '-', '.' and alpha numeric characters.
* Throws an IllegalArgumentException, if the string contains any other characters.
*
* @param argument The name of the argument being validated. This is only used for displaying an error message.
* @param value The value that is being validated.
*/
private void validateFileSuffixArgument(String argument, String value) {
if (!value.matches(FILE_NAME_SUFFIX_PATTERN)) {
throw new IllegalArgumentException(
String.format(Locale.ROOT, "%s file suffix only allows '.', '-' and alphanumeric characters.", argument)
);
}
}
/**
* Validates that the given string value only contains alpha numeric characters.
* Throws an IllegalArgumentException, if the string contains any other characters.
*
* @param argument The name of the argument being validated. This is only used for displaying an error message.
* @param value The value that is being validated.
*/
private void validateClassSuffixArgument(String argument, String value) {
if (!value.matches(CLASS_NAME_SUFFIX_PATTERN)) {
throw new IllegalArgumentException(
String.format(Locale.ROOT, "%s class suffix only allows alphanumeric characters.", argument)
);
}
}
/**
* Set the file naming type.
*
* @param fileNaming the file naming to use
*/
private void setFileNaming(String fileNaming) {
if ("camelCase".equals(fileNaming) || "kebab-case".equals(fileNaming)) {
this.fileNaming = fileNaming;
} else {
throw new IllegalArgumentException("Invalid file naming '" +
fileNaming + "'. Must be 'camelCase' or 'kebab-case'");
}
}
/**
* Converts the original name according to the current <code>fileNaming</code> strategy.
*
* @param originalName the original name to transform
* @return the transformed name
*/
private String convertUsingFileNamingConvention(String originalName) {
String name = this.removeModelPrefixSuffix(originalName);
if ("kebab-case".equals(fileNaming)) {
name = dashize(underscore(name));
} else {
name = camelize(name, true);
}
return name;
}
}

View File

@ -1489,30 +1489,89 @@ public class ModelUtils {
public static void syncValidationProperties(Schema schema, IJsonSchemaValidationProperties target) {
if (schema != null && target != null) {
target.setPattern(schema.getPattern());
BigDecimal minimum = schema.getMinimum();
BigDecimal maximum = schema.getMaximum();
Boolean exclusiveMinimum = schema.getExclusiveMinimum();
Boolean exclusiveMaximum = schema.getExclusiveMaximum();
Integer minLength = schema.getMinLength();
Integer maxLength = schema.getMaxLength();
if (isNullType(schema) || schema.get$ref() != null || isBooleanSchema(schema)) {
return;
}
boolean isAnyType = (schema.getClass().equals(Schema.class) && schema.get$ref() == null && schema.getType() == null &&
(schema.getProperties() == null || schema.getProperties().isEmpty()) &&
schema.getAdditionalProperties() == null && schema.getNot() == null &&
schema.getEnum() == null);
if (isAnyType) {
return;
}
Integer minItems = schema.getMinItems();
Integer maxItems = schema.getMaxItems();
Boolean uniqueItems = schema.getUniqueItems();
Integer minProperties = schema.getMinProperties();
Integer maxProperties = schema.getMaxProperties();
Integer minLength = schema.getMinLength();
Integer maxLength = schema.getMaxLength();
String pattern = schema.getPattern();
BigDecimal multipleOf = schema.getMultipleOf();
BigDecimal minimum = schema.getMinimum();
BigDecimal maximum = schema.getMaximum();
Boolean exclusiveMinimum = schema.getExclusiveMinimum();
Boolean exclusiveMaximum = schema.getExclusiveMaximum();
if (minimum != null) target.setMinimum(String.valueOf(minimum));
if (maximum != null) target.setMaximum(String.valueOf(maximum));
if (isArraySchema(schema)) {
setArrayValidations(minItems, maxItems, uniqueItems, target);
} else if (isMapSchema(schema) || isObjectSchema(schema)) {
setObjectValidations(minProperties, maxProperties, target);
} else if (isStringSchema(schema)) {
setStringValidations(minLength, maxLength, pattern, target);
if (isDecimalSchema(schema)) {
setNumericValidations(schema, multipleOf, minimum, maximum, exclusiveMinimum, exclusiveMaximum, target);
}
} else if (isNumberSchema(schema) || isIntegerSchema(schema)) {
setNumericValidations(schema, multipleOf, minimum, maximum, exclusiveMinimum, exclusiveMaximum, target);
} else if (isComposedSchema(schema)) {
// this could be composed out of anything so set all validations here
setArrayValidations(minItems, maxItems, uniqueItems, target);
setObjectValidations(minProperties, maxProperties, target);
setStringValidations(minLength, maxLength, pattern, target);
setNumericValidations(schema, multipleOf, minimum, maximum, exclusiveMinimum, exclusiveMaximum, target);
}
if (maxItems != null || minItems != null || minProperties != null || maxProperties != null || minLength != null || maxLength != null || multipleOf != null || pattern != null || minimum != null || maximum != null || exclusiveMinimum != null || exclusiveMaximum != null || uniqueItems != null) {
target.setHasValidation(true);
}
}
}
private static void setArrayValidations(Integer minItems, Integer maxItems, Boolean uniqueItems, IJsonSchemaValidationProperties target) {
if (minItems != null) target.setMinItems(minItems);
if (maxItems != null) target.setMaxItems(maxItems);
if (uniqueItems != null) target.setUniqueItems(uniqueItems);
}
private static void setObjectValidations(Integer minProperties, Integer maxProperties, IJsonSchemaValidationProperties target) {
if (minProperties != null) target.setMinProperties(minProperties);
if (maxProperties != null) target.setMaxProperties(maxProperties);
}
private static void setStringValidations(Integer minLength, Integer maxLength, String pattern, IJsonSchemaValidationProperties target) {
if (minLength != null) target.setMinLength(minLength);
if (maxLength != null) target.setMaxLength(maxLength);
if (pattern != null) target.setPattern(pattern);
}
private static void setNumericValidations(Schema schema, BigDecimal multipleOf, BigDecimal minimum, BigDecimal maximum, Boolean exclusiveMinimum, Boolean exclusiveMaximum, IJsonSchemaValidationProperties target) {
if (multipleOf != null) target.setMultipleOf(multipleOf);
if (minimum != null) {
if (isIntegerSchema(schema)) {
target.setMinimum(String.valueOf(minimum.longValue()));
} else {
target.setMinimum(String.valueOf(minimum));
}
if (exclusiveMinimum != null) target.setExclusiveMinimum(exclusiveMinimum);
}
if (maximum != null) {
if (isIntegerSchema(schema)) {
target.setMaximum(String.valueOf(maximum.longValue()));
} else {
target.setMaximum(String.valueOf(maximum));
}
if (exclusiveMaximum != null) target.setExclusiveMaximum(exclusiveMaximum);
if (minLength != null) target.setMinLength(minLength);
if (maxLength != null) target.setMaxLength(maxLength);
if (minItems != null) target.setMinItems(minItems);
if (maxItems != null) target.setMaxItems(maxItems);
if (uniqueItems != null) target.setUniqueItems(uniqueItems);
if (minProperties != null) target.setMinProperties(minProperties);
if (maxProperties != null) target.setMaxProperties(maxProperties);
}
}

View File

@ -20,7 +20,7 @@
Building the API client library requires:
1. Java {{#supportJava6}}1.6{{/supportJava6}}{{^supportJava6}}{{#java8}}1.8{{/java8}}{{^java8}}1.7{{/java8}}{{/supportJava6}}+
1. Java {{#java8}}1.8{{/java8}}{{^java8}}1.7{{/java8}}+
2. Maven/Gradle
## Installation

View File

@ -2,6 +2,10 @@
package {{invokerPackage}}.auth;
{{>generatedAnnotation}}
public enum OAuthFlow {
accessCode, implicit, password, application
accessCode, //called authorizationCode in OpenAPI 3.0
implicit,
password,
application //called clientCredentials in OpenAPI 3.0
}

View File

@ -34,11 +34,6 @@ if(hasProperty('target') && target == 'android') {
}
compileOptions {
{{#supportJava6}}
sourceCompatibility JavaVersion.VERSION_1_6
targetCompatibility JavaVersion.VERSION_1_6
{{/supportJava6}}
{{^supportJava6}}
{{#java8}}
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
@ -47,7 +42,6 @@ if(hasProperty('target') && target == 'android') {
sourceCompatibility JavaVersion.VERSION_1_7
targetCompatibility JavaVersion.VERSION_1_7
{{/java8}}
{{/supportJava6}}
}
// Rename the aar correctly
@ -92,11 +86,6 @@ if(hasProperty('target') && target == 'android') {
apply plugin: 'java'
apply plugin: 'maven'
{{#supportJava6}}
sourceCompatibility = JavaVersion.VERSION_1_6
targetCompatibility = JavaVersion.VERSION_1_6
{{/supportJava6}}
{{^supportJava6}}
{{#java8}}
sourceCompatibility = JavaVersion.VERSION_1_8
targetCompatibility = JavaVersion.VERSION_1_8
@ -105,7 +94,6 @@ if(hasProperty('target') && target == 'android') {
sourceCompatibility = JavaVersion.VERSION_1_7
targetCompatibility = JavaVersion.VERSION_1_7
{{/java8}}
{{/supportJava6}}
install {
repositories.mavenInstaller {

View File

@ -2,15 +2,13 @@ package {{invokerPackage}};
import java.util.LinkedHashMap;
import java.util.Map;
{{#hasOAuthMethods}}
import org.apache.oltu.oauth2.client.request.OAuthClientRequest.AuthenticationRequestBuilder;
import org.apache.oltu.oauth2.client.request.OAuthClientRequest.TokenRequestBuilder;
{{/hasOAuthMethods}}
import java.util.logging.Level;
import java.util.logging.Logger;
{{#threetenbp}}
import org.threeten.bp.*;
{{/threetenbp}}
import feign.okhttp.OkHttpClient;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
@ -41,6 +39,8 @@ import {{invokerPackage}}.auth.OAuth.AccessTokenListener;
{{>generatedAnnotation}}
public class ApiClient {
private static final Logger log = Logger.getLogger(ApiClient.class.getName());
public interface Api {}
protected ObjectMapper objectMapper;
@ -52,6 +52,7 @@ public class ApiClient {
objectMapper = createObjectMapper();
apiAuthorizations = new LinkedHashMap<String, RequestInterceptor>();
feignBuilder = Feign.builder()
.client(new OkHttpClient())
.encoder(new FormEncoder(new JacksonEncoder(objectMapper)))
.decoder(new JacksonDecoder(objectMapper))
.logger(new Slf4jLogger());
@ -60,6 +61,7 @@ public class ApiClient {
public ApiClient(String[] authNames) {
this();
for(String authName : authNames) {
log.log(Level.FINE, "Creating authentication {0}", authName);
{{#hasAuthMethods}}
RequestInterceptor auth;
{{#authMethods}}if ("{{name}}".equals(authName)) {
@ -75,7 +77,7 @@ public class ApiClient {
auth = new ApiKeyAuth({{#isKeyInHeader}}"header"{{/isKeyInHeader}}{{#isKeyInQuery}}"query"{{/isKeyInQuery}}{{#isKeyInCookie}}"cookie"{{/isKeyInCookie}}, "{{keyParamName}}");
{{/isApiKey}}
{{#isOAuth}}
auth = new OAuth(OAuthFlow.{{flow}}, "{{authorizationUrl}}", "{{tokenUrl}}", "{{#scopes}}{{scope}}{{^-last}}, {{/-last}}{{/scopes}}");
auth = buildOauthRequestInterceptor(OAuthFlow.{{flow}}, "{{authorizationUrl}}", "{{tokenUrl}}", "{{#scopes}}{{scope}}{{^-last}}, {{/-last}}{{/scopes}}");
{{/isOAuth}}
} else {{/authMethods}}{
throw new RuntimeException("auth name \"" + authName + "\" not found in available auth names");
@ -106,36 +108,6 @@ public class ApiClient {
this.setApiKey(apiKey);
}
/**
* Helper constructor for single basic auth or password oauth2
* @param authName
* @param username
* @param password
*/
public ApiClient(String authName, String username, String password) {
this(authName);
this.setCredentials(username, password);
}
{{#hasOAuthMethods}}
/**
* Helper constructor for single password oauth2
* @param authName
* @param clientId
* @param secret
* @param username
* @param password
*/
public ApiClient(String authName, String clientId, String secret, String username, String password) {
this(authName);
this.getTokenEndPoint()
.setClientId(clientId)
.setClientSecret(secret)
.setUsername(username)
.setPassword(password);
}
{{/hasOAuthMethods}}
public String getBasePath() {
return basePath;
}
@ -190,10 +162,25 @@ public class ApiClient {
return objectMapper;
}
private RequestInterceptor buildOauthRequestInterceptor(OAuthFlow flow, String authorizationUrl, String tokenUrl, String scopes) {
switch (flow) {
case password:
return new OauthPasswordGrant(tokenUrl, scopes);
case application:
return new OauthClientCredentialsGrant(authorizationUrl, tokenUrl, scopes);
default:
throw new RuntimeException("Oauth flow \"" + flow + "\" is not implemented");
}
}
public ObjectMapper getObjectMapper(){
return objectMapper;
}
public void setObjectMapper(ObjectMapper objectMapper) {
this.objectMapper = objectMapper;
}
/**
* Creates a feign client for given API interface.
*
@ -240,19 +227,13 @@ public class ApiClient {
return contentTypes[0];
}
/**
* Helper method to configure the bearer token.
* @param bearerToken the bearer token.
*/
public void setBearerToken(String bearerToken) {
for(RequestInterceptor apiAuthorization : apiAuthorizations.values()) {
if (apiAuthorization instanceof HttpBearerAuth) {
((HttpBearerAuth) apiAuthorization).setBearerToken(bearerToken);
return;
}
}
throw new RuntimeException("No Bearer authentication configured!");
HttpBearerAuth apiAuthorization = getAuthorization(HttpBearerAuth.class);
apiAuthorization.setBearerToken(bearerToken);
}
/**
@ -260,66 +241,39 @@ public class ApiClient {
* @param apiKey API key
*/
public void setApiKey(String apiKey) {
for(RequestInterceptor apiAuthorization : apiAuthorizations.values()) {
if (apiAuthorization instanceof ApiKeyAuth) {
ApiKeyAuth keyAuth = (ApiKeyAuth) apiAuthorization;
keyAuth.setApiKey(apiKey);
return ;
}
}
throw new RuntimeException("No API key authentication configured!");
ApiKeyAuth apiAuthorization = getAuthorization(ApiKeyAuth.class);
apiAuthorization.setApiKey(apiKey);
}
/**
* Helper method to configure the username/password for basic auth or password OAuth
* Helper method to configure the username/password for basic auth
* @param username Username
* @param password Password
*/
public void setCredentials(String username, String password) {
for(RequestInterceptor apiAuthorization : apiAuthorizations.values()) {
if (apiAuthorization instanceof HttpBasicAuth) {
HttpBasicAuth basicAuth = (HttpBasicAuth) apiAuthorization;
basicAuth.setCredentials(username, password);
return;
}
{{#hasOAuthMethods}}
if (apiAuthorization instanceof OAuth) {
OAuth oauth = (OAuth) apiAuthorization;
oauth.getTokenRequestBuilder().setUsername(username).setPassword(password);
return;
}
{{/hasOAuthMethods}}
}
throw new RuntimeException("No Basic authentication or OAuth configured!");
HttpBasicAuth apiAuthorization = getAuthorization(HttpBasicAuth.class);
apiAuthorization.setCredentials(username, password);
}
{{#hasOAuthMethods}}
/**
* Helper method to configure the token endpoint of the first oauth found in the apiAuthorizations (there should be only one)
* @return Token request builder
* Helper method to configure the client credentials for Oauth
* @param username Username
* @param password Password
*/
public TokenRequestBuilder getTokenEndPoint() {
for(RequestInterceptor apiAuthorization : apiAuthorizations.values()) {
if (apiAuthorization instanceof OAuth) {
OAuth oauth = (OAuth) apiAuthorization;
return oauth.getTokenRequestBuilder();
}
}
return null;
public void setClientCredentials(String clientId, String clientSecret) {
OauthClientCredentialsGrant authorization = getAuthorization(OauthClientCredentialsGrant.class);
authorization.configure(clientId, clientSecret);
}
/**
* Helper method to configure authorization endpoint of the first oauth found in the apiAuthorizations (there should be only one)
* @return Authentication request builder
* Helper method to configure the username/password for Oauth password grant
* @param username Username
* @param password Password
*/
public AuthenticationRequestBuilder getAuthorizationEndPoint() {
for(RequestInterceptor apiAuthorization : apiAuthorizations.values()) {
if (apiAuthorization instanceof OAuth) {
OAuth oauth = (OAuth) apiAuthorization;
return oauth.getAuthenticationRequestBuilder();
}
}
return null;
public void setOauthPassword(String username, String password, String clientId, String clientSecret) {
OauthPasswordGrant apiAuthorization = getAuthorization(OauthPasswordGrant.class);
apiAuthorization.configure(username, password, clientId, clientSecret);
}
/**
@ -327,14 +281,9 @@ public class ApiClient {
* @param accessToken Access Token
* @param expiresIn Validity period in seconds
*/
public void setAccessToken(String accessToken, Long expiresIn) {
for(RequestInterceptor apiAuthorization : apiAuthorizations.values()) {
if (apiAuthorization instanceof OAuth) {
OAuth oauth = (OAuth) apiAuthorization;
oauth.setAccessToken(accessToken, expiresIn);
return;
}
}
public void setAccessToken(String accessToken, Integer expiresIn) {
OAuth apiAuthorization = getAuthorization(OAuth.class);
apiAuthorization.setAccessToken(accessToken, expiresIn);
}
/**
@ -344,19 +293,7 @@ public class ApiClient {
* @param redirectURI Redirect URI
*/
public void configureAuthorizationFlow(String clientId, String clientSecret, String redirectURI) {
for(RequestInterceptor apiAuthorization : apiAuthorizations.values()) {
if (apiAuthorization instanceof OAuth) {
OAuth oauth = (OAuth) apiAuthorization;
oauth.getTokenRequestBuilder()
.setClientId(clientId)
.setClientSecret(clientSecret)
.setRedirectURI(redirectURI);
oauth.getAuthenticationRequestBuilder()
.setClientId(clientId)
.setRedirectURI(redirectURI);
return;
}
}
throw new RuntimeException("Not implemented");
}
/**
@ -364,13 +301,8 @@ public class ApiClient {
* @param accessTokenListener Acesss token listener
*/
public void registerAccessTokenListener(AccessTokenListener accessTokenListener) {
for(RequestInterceptor apiAuthorization : apiAuthorizations.values()) {
if (apiAuthorization instanceof OAuth) {
OAuth oauth = (OAuth) apiAuthorization;
oauth.registerAccessTokenListener(accessTokenListener);
return;
}
}
OAuth apiAuthorization = getAuthorization(OAuth.class);
apiAuthorization.registerAccessTokenListener(accessTokenListener);
}
{{/hasOAuthMethods}}
@ -396,4 +328,11 @@ public class ApiClient {
feignBuilder.requestInterceptor(authorization);
}
private <T extends RequestInterceptor> T getAuthorization(Class<T> type) {
return (T) apiAuthorizations.values()
.stream()
.filter(requestInterceptor -> type.isAssignableFrom(requestInterceptor.getClass()))
.findFirst()
.orElseThrow(() -> new RuntimeException("No Oauth authentication or OAuth configured!"));
}
}

View File

@ -32,6 +32,41 @@ After the client library is installed/deployed, you can use it in your Maven pro
```
And to use the api you can follow the examples bellow:
```java
//Set bearer token manually
ApiClient apiClient = new ApiClient("petstore_auth_client");
apiClient.setBasePath("https://localhost:8243/petstore/1/");
apiClient.setAccessToken("TOKEN", 10000);
//Use api key
ApiClient apiClient = new ApiClient("api_key", "API KEY");
apiClient.setBasePath("https://localhost:8243/petstore/1/");
//Use http basic authentication
ApiClient apiClient = new ApiClient("basicAuth");
apiClient.setBasePath("https://localhost:8243/petstore/1/");
apiClient.setCredentials("username", "password");
//Oauth password
ApiClient apiClient = new ApiClient("oauth_password");
apiClient.setBasePath("https://localhost:8243/petstore/1/");
apiClient.setOauthPassword("username", "password", "client_id", "client_secret");
//Oauth client credentials flow
ApiClient apiClient = new ApiClient("oauth_client_credentials");
apiClient.setBasePath("https://localhost:8243/petstore/1/");
apiClient.setClientCredentials("client_id", "client_secret");
PetApi petApi = apiClient.buildClient(PetApi.class);
Pet petById = petApi.getPetById(12345L);
System.out.println(petById);
}
```
## Recommendation
It's recommended to create an instance of `ApiClient` per thread in a multithreaded environment to avoid any potential issues.
@ -40,4 +75,3 @@ It's recommended to create an instance of `ApiClient` per thread in a multithrea
{{#apiInfo}}{{#apis}}{{#-last}}{{infoEmail}}
{{/-last}}{{/apis}}{{/apiInfo}}

View File

@ -3,8 +3,8 @@ package {{package}};
import {{invokerPackage}}.ApiClient;
{{#imports}}import {{import}};
{{/imports}}
import org.junit.Before;
import org.junit.Test;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.BeforeEach;
{{^fullJavaUtil}}
import java.util.ArrayList;
@ -16,11 +16,11 @@ import java.util.Map;
/**
* API tests for {{classname}}
*/
public class {{classname}}Test {
class {{classname}}Test {
private {{classname}} api;
@Before
@BeforeEach
public void setup() {
api = new ApiClient().buildClient({{classname}}.class);
}
@ -32,7 +32,7 @@ public class {{classname}}Test {
* {{notes}}
*/
@Test
public void {{operationId}}Test() {
void {{operationId}}Test() {
{{#allParams}}
{{{dataType}}} {{paramName}} = null;
{{/allParams}}
@ -51,7 +51,7 @@ public class {{classname}}Test {
* listing them out individually.
*/
@Test
public void {{operationId}}TestQueryMap() {
void {{operationId}}TestQueryMap() {
{{#allParams}}
{{^isQueryParam}}
{{{dataType}}} {{paramName}} = null;

View File

@ -0,0 +1,47 @@
package {{invokerPackage}}.auth;
import com.github.scribejava.core.builder.api.DefaultApi20;
import com.github.scribejava.core.extractors.OAuth2AccessTokenJsonExtractor;
import com.github.scribejava.core.extractors.TokenExtractor;
import com.github.scribejava.core.model.OAuth2AccessToken;
import com.github.scribejava.core.oauth2.bearersignature.BearerSignature;
import com.github.scribejava.core.oauth2.bearersignature.BearerSignatureURIQueryParameter;
import com.github.scribejava.core.oauth2.clientauthentication.ClientAuthentication;
import com.github.scribejava.core.oauth2.clientauthentication.RequestBodyAuthenticationScheme;
{{>generatedAnnotation}}
public class DefaultApi20Impl extends DefaultApi20 {
private final String accessTokenEndpoint;
private final String authorizationBaseUrl;
protected DefaultApi20Impl(String authorizationBaseUrl, String accessTokenEndpoint) {
this.authorizationBaseUrl = authorizationBaseUrl;
this.accessTokenEndpoint = accessTokenEndpoint;
}
@Override
public String getAccessTokenEndpoint() {
return accessTokenEndpoint;
}
@Override
protected String getAuthorizationBaseUrl() {
return authorizationBaseUrl;
}
@Override
public BearerSignature getBearerSignature() {
return BearerSignatureURIQueryParameter.instance();
}
@Override
public ClientAuthentication getClientAuthentication() {
return RequestBodyAuthenticationScheme.instance();
}
@Override
public TokenExtractor<OAuth2AccessToken> getAccessTokenExtractor() {
return OAuth2AccessTokenJsonExtractor.instance();
}
}

View File

@ -1,198 +1,81 @@
package {{invokerPackage}}.auth;
import java.io.IOException;
import java.util.Collection;
import java.util.Map;
import java.util.Map.Entry;
import org.apache.oltu.oauth2.client.HttpClient;
import org.apache.oltu.oauth2.client.OAuthClient;
import org.apache.oltu.oauth2.client.request.OAuthClientRequest;
import org.apache.oltu.oauth2.client.request.OAuthClientRequest.AuthenticationRequestBuilder;
import org.apache.oltu.oauth2.client.request.OAuthClientRequest.TokenRequestBuilder;
import org.apache.oltu.oauth2.client.response.OAuthClientResponse;
import org.apache.oltu.oauth2.client.response.OAuthClientResponseFactory;
import org.apache.oltu.oauth2.client.response.OAuthJSONAccessTokenResponse;
import org.apache.oltu.oauth2.common.exception.OAuthProblemException;
import org.apache.oltu.oauth2.common.exception.OAuthSystemException;
import org.apache.oltu.oauth2.common.message.types.GrantType;
import org.apache.oltu.oauth2.common.token.BasicOAuthToken;
import feign.Client;
import com.github.scribejava.core.model.OAuth2AccessToken;
import com.github.scribejava.core.oauth.OAuth20Service;
import feign.Request.HttpMethod;
import feign.Request.Options;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import feign.Response;
import feign.RetryableException;
import feign.Util;
import {{invokerPackage}}.StringUtil;
{{>generatedAnnotation}}
public abstract class OAuth implements RequestInterceptor {
public class OAuth implements RequestInterceptor {
static final int MILLIS_PER_SECOND = 1000;
static final int MILLIS_PER_SECOND = 1000;
public interface AccessTokenListener {
void notify(OAuth2AccessToken token);
}
public interface AccessTokenListener {
void notify(BasicOAuthToken token);
private volatile String accessToken;
private Long expirationTimeMillis;
private AccessTokenListener accessTokenListener;
protected OAuth20Service service;
protected String scopes;
protected String authorizationUrl;
protected String tokenUrl;
public OAuth(String authorizationUrl, String tokenUrl, String scopes) {
this.scopes = scopes;
this.authorizationUrl = authorizationUrl;
this.tokenUrl = tokenUrl;
}
@Override
public void apply(RequestTemplate template) {
// If the request already have an authorization (eg. Basic auth), do nothing
if (template.headers().containsKey("Authorization")) {
return;
}
private volatile String accessToken;
private Long expirationTimeMillis;
private OAuthClient oauthClient;
private TokenRequestBuilder tokenRequestBuilder;
private AuthenticationRequestBuilder authenticationRequestBuilder;
private AccessTokenListener accessTokenListener;
public OAuth(Client client, TokenRequestBuilder requestBuilder) {
this.oauthClient = new OAuthClient(new OAuthFeignClient(client));
this.tokenRequestBuilder = requestBuilder;
// If first time, get the token
if (expirationTimeMillis == null || System.currentTimeMillis() >= expirationTimeMillis) {
updateAccessToken(template);
}
public OAuth(Client client, OAuthFlow flow, String authorizationUrl, String tokenUrl, String scopes) {
this(client, OAuthClientRequest.tokenLocation(tokenUrl).setScope(scopes));
switch(flow) {
case accessCode:
case implicit:
tokenRequestBuilder.setGrantType(GrantType.AUTHORIZATION_CODE);
break;
case password:
tokenRequestBuilder.setGrantType(GrantType.PASSWORD);
break;
case application:
tokenRequestBuilder.setGrantType(GrantType.CLIENT_CREDENTIALS);
break;
default:
break;
}
authenticationRequestBuilder = OAuthClientRequest.authorizationLocation(authorizationUrl);
if (getAccessToken() != null) {
template.header("Authorization", "Bearer " + getAccessToken());
}
}
public OAuth(OAuthFlow flow, String authorizationUrl, String tokenUrl, String scopes) {
this(new Client.Default(null, null), flow, authorizationUrl, tokenUrl, scopes);
private synchronized void updateAccessToken(RequestTemplate template) {
OAuth2AccessToken accessTokenResponse;
try {
accessTokenResponse = getOAuth2AccessToken();
} catch (Exception e) {
throw new RetryableException(0, e.getMessage(), HttpMethod.POST, e, null, template.request());
}
@Override
public void apply(RequestTemplate template) {
// If the request already have an authorization (eg. Basic auth), do nothing
if (template.headers().containsKey("Authorization")) {
return;
}
// If first time, get the token
if (expirationTimeMillis == null || System.currentTimeMillis() >= expirationTimeMillis) {
updateAccessToken(template);
}
if (getAccessToken() != null) {
template.header("Authorization", "Bearer " + getAccessToken());
}
if (accessTokenResponse != null && accessTokenResponse.getAccessToken() != null) {
setAccessToken(accessTokenResponse.getAccessToken(), accessTokenResponse.getExpiresIn());
if (accessTokenListener != null) {
accessTokenListener.notify(accessTokenResponse);
}
}
}
public synchronized void updateAccessToken(RequestTemplate template) {
OAuthJSONAccessTokenResponse accessTokenResponse;
try {
accessTokenResponse = oauthClient.accessToken(tokenRequestBuilder.buildBodyMessage());
} catch (Exception e) {
throw new RetryableException(0, e.getMessage(), HttpMethod.POST, e, null, template.request());
}
if (accessTokenResponse != null && accessTokenResponse.getAccessToken() != null) {
setAccessToken(accessTokenResponse.getAccessToken(), accessTokenResponse.getExpiresIn());
if (accessTokenListener != null) {
accessTokenListener.notify((BasicOAuthToken) accessTokenResponse.getOAuthToken());
}
}
}
abstract OAuth2AccessToken getOAuth2AccessToken();
public synchronized void registerAccessTokenListener(AccessTokenListener accessTokenListener) {
this.accessTokenListener = accessTokenListener;
}
abstract OAuthFlow getFlow();
public synchronized String getAccessToken() {
return accessToken;
}
public synchronized void registerAccessTokenListener(AccessTokenListener accessTokenListener) {
this.accessTokenListener = accessTokenListener;
}
public synchronized void setAccessToken(String accessToken, Long expiresIn) {
this.accessToken = accessToken;
this.expirationTimeMillis = expiresIn == null ? null : System.currentTimeMillis() + expiresIn * MILLIS_PER_SECOND;
}
public synchronized String getAccessToken() {
return accessToken;
}
public TokenRequestBuilder getTokenRequestBuilder() {
return tokenRequestBuilder;
}
public synchronized void setAccessToken(String accessToken, Integer expiresIn) {
this.accessToken = accessToken;
this.expirationTimeMillis = expiresIn == null ? null : System.currentTimeMillis() + expiresIn * MILLIS_PER_SECOND;
}
public void setTokenRequestBuilder(TokenRequestBuilder tokenRequestBuilder) {
this.tokenRequestBuilder = tokenRequestBuilder;
}
public AuthenticationRequestBuilder getAuthenticationRequestBuilder() {
return authenticationRequestBuilder;
}
public void setAuthenticationRequestBuilder(AuthenticationRequestBuilder authenticationRequestBuilder) {
this.authenticationRequestBuilder = authenticationRequestBuilder;
}
public OAuthClient getOauthClient() {
return oauthClient;
}
public void setOauthClient(OAuthClient oauthClient) {
this.oauthClient = oauthClient;
}
public void setOauthClient(Client client) {
this.oauthClient = new OAuthClient( new OAuthFeignClient(client));
}
public static class OAuthFeignClient implements HttpClient {
private Client client;
public OAuthFeignClient() {
this.client = new Client.Default(null, null);
}
public OAuthFeignClient(Client client) {
this.client = client;
}
public <T extends OAuthClientResponse> T execute(OAuthClientRequest request, Map<String, String> headers,
String requestMethod, Class<T> responseClass)
throws OAuthSystemException, OAuthProblemException {
RequestTemplate req = new RequestTemplate()
.append(request.getLocationUri())
.method(requestMethod)
.body(request.getBody());
for (Entry<String, String> entry : headers.entrySet()) {
req.header(entry.getKey(), entry.getValue());
}
Response feignResponse;
String body = "";
try {
feignResponse = client.execute(req.request(), new Options());
body = Util.toString(feignResponse.body().asReader());
} catch (IOException e) {
throw new OAuthSystemException(e);
}
String contentType = null;
Collection<String> contentTypeHeader = feignResponse.headers().get("Content-Type");
if(contentTypeHeader != null) {
contentType = StringUtil.join(contentTypeHeader.toArray(new String[0]), ";");
}
return OAuthClientResponseFactory.createCustomResponse(
body,
contentType,
feignResponse.status(),
responseClass
);
}
public void shutdown() {
// Nothing to do here
}
}
}
}

View File

@ -0,0 +1,39 @@
package {{invokerPackage}}.auth;
import com.github.scribejava.core.builder.ServiceBuilder;
import com.github.scribejava.core.model.OAuth2AccessToken;
{{>generatedAnnotation}}
public class OauthClientCredentialsGrant extends OAuth {
public OauthClientCredentialsGrant(String authorizationUrl, String tokenUrl, String scopes) {
super(authorizationUrl, tokenUrl, scopes);
}
@Override
protected OAuth2AccessToken getOAuth2AccessToken() {
try {
return service.getAccessTokenClientCredentialsGrant(scopes);
} catch (Exception e) {
throw new RuntimeException("Failed to get oauth token", e);
}
}
@Override
protected OAuthFlow getFlow() {
return OAuthFlow.application;
}
/**
* Configures the client credentials flow
*
* @param clientId
* @param clientSecret
*/
public void configure(String clientId, String clientSecret) {
service = new ServiceBuilder(clientId)
.apiSecret(clientSecret)
.defaultScope(scopes)
.build(new DefaultApi20Impl(authorizationUrl, tokenUrl));
}
}

View File

@ -0,0 +1,48 @@
package {{invokerPackage}}.auth;
import com.github.scribejava.core.builder.ServiceBuilder;
import com.github.scribejava.core.model.OAuth2AccessToken;
{{>generatedAnnotation}}
public class OauthPasswordGrant extends OAuth {
private String username;
private String password;
public OauthPasswordGrant(String tokenUrl, String scopes) {
super(null, tokenUrl, scopes);
}
@Override
protected OAuth2AccessToken getOAuth2AccessToken() {
try {
return service.getAccessTokenPasswordGrant(username, password);
} catch (Exception e) {
throw new RuntimeException("Failed to get oauth token", e);
}
}
@Override
protected OAuthFlow getFlow() {
return OAuthFlow.password;
}
/**
* Configures Oauth password grant flow
* Note: this flow is deprecated.
*
* @param username
* @param password
* @param clientId
* @param clientSecret
*/
public void configure(String username, String password, String clientId, String clientSecret) {
this.username = username;
this.password = password;
//TODO the clientId and secret are optional according with the RFC
service = new ServiceBuilder(clientId)
.apiSecret(clientSecret)
.defaultScope(scopes)
.build(new DefaultApi20Impl(authorizationUrl, tokenUrl));
}
}

View File

@ -33,20 +33,8 @@ if(hasProperty('target') && target == 'android') {
targetSdkVersion 25
}
compileOptions {
{{#supportJava6}}
sourceCompatibility JavaVersion.VERSION_1_6
targetCompatibility JavaVersion.VERSION_1_6
{{/supportJava6}}
{{^supportJava6}}
{{#java8}}
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
{{/java8}}
{{^java8}}
sourceCompatibility JavaVersion.VERSION_1_7
targetCompatibility JavaVersion.VERSION_1_7
{{/java8}}
{{/supportJava6}}
}
// Rename the aar correctly
@ -91,20 +79,8 @@ if(hasProperty('target') && target == 'android') {
apply plugin: 'java'
apply plugin: 'maven'
{{#supportJava6}}
sourceCompatibility = JavaVersion.VERSION_1_6
targetCompatibility = JavaVersion.VERSION_1_6
{{/supportJava6}}
{{^supportJava6}}
{{#java8}}
sourceCompatibility = JavaVersion.VERSION_1_8
targetCompatibility = JavaVersion.VERSION_1_8
{{/java8}}
{{^java8}}
sourceCompatibility = JavaVersion.VERSION_1_7
targetCompatibility = JavaVersion.VERSION_1_7
{{/java8}}
{{/supportJava6}}
install {
repositories.mavenInstaller {
@ -118,6 +94,10 @@ if(hasProperty('target') && target == 'android') {
}
}
test {
useJUnitPlatform()
}
ext {
swagger_annotations_version = "1.5.24"
jackson_version = "2.10.3"
@ -130,8 +110,8 @@ ext {
{{/threetenbp}}
feign_version = "10.11"
feign_form_version = "3.8.0"
junit_version = "4.13.1"
oltu_version = "1.0.1"
junit_version = "5.7.0"
scribejava_version = "8.0.0"
}
dependencies {
@ -140,6 +120,7 @@ dependencies {
implementation "io.github.openfeign:feign-core:$feign_version"
implementation "io.github.openfeign:feign-jackson:$feign_version"
implementation "io.github.openfeign:feign-slf4j:$feign_version"
implementation "io.github.openfeign:feign-okhttp:$feign_version"
implementation "io.github.openfeign.form:feign-form:$feign_form_version"
implementation "com.fasterxml.jackson.core:jackson-core:$jackson_version"
implementation "com.fasterxml.jackson.core:jackson-annotations:$jackson_version"
@ -156,8 +137,15 @@ dependencies {
{{#threetenbp}}
implementation "com.github.joschi.jackson:jackson-datatype-threetenbp:$jackson_threetenbp_version"
{{/threetenbp}}
implementation "org.apache.oltu.oauth2:org.apache.oltu.oauth2.client:$oltu_version"
implementation "com.brsanthu:migbase64:2.2"
implementation "com.github.scribejava:scribejava-core:$scribejava_version"
implementation "com.brsanthu:migbase64:2.2"
implementation 'javax.annotation:javax.annotation-api:1.3.2'
testImplementation "junit:junit:$junit_version"
testImplementation "org.junit.jupiter:junit-jupiter:$junit_version"
testRuntimeOnly "org.junit.jupiter:junit-jupiter-engine:$junit_version"
testImplementation "org.junit.jupiter:junit-jupiter-params:$junit_version"
testImplementation "com.github.tomakehurst:wiremock-jre8:2.27.2"
testImplementation "org.hamcrest:hamcrest:2.2"
testImplementation "commons-io:commons-io:2.8.0"
testImplementation "ch.qos.logback:logback-classic:1.2.3"
}

View File

@ -10,19 +10,25 @@ lazy val root = (project in file(".")).
resolvers += Resolver.mavenLocal,
libraryDependencies ++= Seq(
"io.swagger" % "swagger-annotations" % "1.5.24" % "compile",
"com.google.code.findbugs" % "jsr305" % "3.0.2" % "compile",
"io.github.openfeign" % "feign-core" % "10.11" % "compile",
"io.github.openfeign" % "feign-jackson" % "10.11" % "compile",
"io.github.openfeign" % "feign-slf4j" % "10.11" % "compile",
"io.github.openfeign.form" % "feign-form" % "3.8.0" % "compile",
"io.github.openfeign" % "feign-okhttp" % "10.11" % "compile",
"com.fasterxml.jackson.core" % "jackson-core" % "2.10.3" % "compile",
"com.fasterxml.jackson.core" % "jackson-annotations" % "2.10.3" % "compile",
"com.fasterxml.jackson.core" % "jackson-databind" % "2.10.3" % "compile",
"com.fasterxml.jackson.datatype" % "jackson-datatype-{{^java8}}joda{{/java8}}{{#java8}}jsr310{{/java8}}" % "2.9.10" % "compile",
"com.github.joschi.jackson" % "jackson-datatype-threetenbp" % "2.9.10" % "compile",
"org.apache.oltu.oauth2" % "org.apache.oltu.oauth2.client" % "1.0.1" % "compile",
"com.github.scribejava" % "scribejava-core" % "8.0.0" % "compile",
"com.brsanthu" % "migbase64" % "2.2" % "compile",
"javax.annotation" % "javax.annotation-api" % "1.3.2" % "compile",
"junit" % "junit" % "4.13.1" % "test",
"org.junit.jupiter" % "junit-jupiter" % "5.7.0" % "test",
"org.junit.jupiter" % "junit-jupiter-params" % "5.7.0" % "test",
"com.github.tomakehurst" % "wiremock-jre8" % "2.27.2" % "test",
"org.hamcrest" % "hamcrest" % "2.2" % "test",
"commons-io" % "commons-io" % "2.8.0" % "test",
"com.novocode" % "junit-interface" % "0.10" % "test"
)
)

View File

@ -0,0 +1,48 @@
{{>licenseInfo}}
package {{package}};
{{#imports}}import {{import}};
{{/imports}}
import org.junit.jupiter.api.Test;
{{#fullJavaUtil}}
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
{{/fullJavaUtil}}
/**
* Model tests for {{classname}}
*/
class {{classname}}Test {
{{#models}}
{{#model}}
{{^vendorExtensions.x-is-one-of-interface}}
{{^isEnum}}
private final {{classname}} model = new {{classname}}();
{{/isEnum}}
/**
* Model tests for {{classname}}
*/
@Test
void test{{classname}}() {
// TODO: test {{classname}}
}
{{#allVars}}
/**
* Test the property '{{name}}'
*/
@Test
void {{name}}Test() {
// TODO: test {{name}}
}
{{/allVars}}
{{/vendorExtensions.x-is-one-of-interface}}
{{/model}}
{{/models}}
}

View File

@ -161,17 +161,7 @@
<version>3.1.1</version>
<configuration>
<doclint>none</doclint>
{{#supportJava6}}
<source>1.6</source>
{{/supportJava6}}
{{^supportJava6}}
{{#java8}}
<source>1.8</source>
{{/java8}}
{{^java8}}
<source>1.7</source>
{{/java8}}
{{/supportJava6}}
<source>1.8</source>
</configuration>
<executions>
<execution>
@ -257,6 +247,11 @@
<artifactId>feign-form</artifactId>
<version>${feign-form-version}</version>
</dependency>
<dependency>
<groupId>io.github.openfeign</groupId>
<artifactId>feign-okhttp</artifactId>
<version>${feign-version}</version>
</dependency>
<!-- JSON processing: jackson -->
<dependency>
@ -282,40 +277,38 @@
</dependency>
{{/openApiNullable}}
{{#withXml}}
<!-- XML Support -->
<dependency>
<groupId>com.fasterxml.jackson.dataformat</groupId>
<artifactId>jackson-dataformat-xml</artifactId>
<version>${jackson-version}</version>
</dependency>
<!-- XML Support -->
<dependency>
<groupId>com.fasterxml.jackson.dataformat</groupId>
<artifactId>jackson-dataformat-xml</artifactId>
<version>${jackson-version}</version>
</dependency>
{{/withXml}}
{{#joda}}
<dependency>
<groupId>com.fasterxml.jackson.datatype</groupId>
<artifactId>jackson-datatype-joda</artifactId>
<version>${jackson-version}</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.datatype</groupId>
<artifactId>jackson-datatype-joda</artifactId>
<version>${jackson-version}</version>
</dependency>
{{/joda}}
{{#java8}}
<dependency>
<groupId>com.fasterxml.jackson.datatype</groupId>
<artifactId>jackson-datatype-jsr310</artifactId>
<version>${jackson-version}</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.datatype</groupId>
<artifactId>jackson-datatype-jsr310</artifactId>
<version>${jackson-version}</version>
</dependency>
{{/java8}}
{{#threetenbp}}
<dependency>
<groupId>com.github.joschi.jackson</groupId>
<artifactId>jackson-datatype-threetenbp</artifactId>
<version>${jackson-threetenbp-version}</version>
</dependency>
<dependency>
<groupId>com.github.joschi.jackson</groupId>
<artifactId>jackson-datatype-threetenbp</artifactId>
<version>${jackson-threetenbp-version}</version>
</dependency>
{{/threetenbp}}
<dependency>
<groupId>org.apache.oltu.oauth2</groupId>
<artifactId>org.apache.oltu.oauth2.client</artifactId>
<version>${oltu-version}</version>
<groupId>com.github.scribejava</groupId>
<artifactId>scribejava-core</artifactId>
<version>${scribejava-version}</version>
</dependency>
<dependency>
<groupId>javax.annotation</groupId>
@ -326,27 +319,45 @@
<!-- test dependencies -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>1.2.3</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter</artifactId>
<version>${junit-version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.squareup.okhttp3</groupId>
<artifactId>mockwebserver</artifactId>
<version>3.6.0</version>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-params</artifactId>
<version>${junit-version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.assertj</groupId>
<artifactId>assertj-core</artifactId>
<version>1.7.1</version>
<groupId>org.hamcrest</groupId>
<artifactId>hamcrest</artifactId>
<version>2.2</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.github.tomakehurst</groupId>
<artifactId>wiremock-jre8</artifactId>
<version>2.27.2</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.8.0</version>
<scope>test</scope>
</dependency>
</dependencies>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<java.version>{{#supportJava6}}1.6{{/supportJava6}}{{^supportJava6}}{{#java8}}1.8{{/java8}}{{^java8}}1.7{{/java8}}{{/supportJava6}}</java.version>
<java.version>1.8</java.version>
<maven.compiler.source>${java.version}</maven.compiler.source>
<maven.compiler.target>${java.version}</maven.compiler.target>
<swagger-annotations-version>1.5.24</swagger-annotations-version>
@ -361,8 +372,8 @@
<jackson-threetenbp-version>2.9.10</jackson-threetenbp-version>
{{/threetenbp}}
<javax-annotation-version>1.3.2</javax-annotation-version>
<junit-version>4.13.1</junit-version>
<junit-version>5.7.0</junit-version>
<maven-plugin-version>1.0.0</maven-plugin-version>
<oltu-version>1.0.1</oltu-version>
<scribejava-version>8.0.0</scribejava-version>
</properties>
</project>

View File

@ -33,11 +33,6 @@ if(hasProperty('target') && target == 'android') {
targetSdkVersion 22
}
compileOptions {
{{#supportJava6}}
sourceCompatibility JavaVersion.VERSION_1_6
targetCompatibility JavaVersion.VERSION_1_6
{{/supportJava6}}
{{^supportJava6}}
{{#java8}}
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
@ -46,7 +41,6 @@ if(hasProperty('target') && target == 'android') {
sourceCompatibility JavaVersion.VERSION_1_7
targetCompatibility JavaVersion.VERSION_1_7
{{/java8}}
{{/supportJava6}}
}
// Rename the aar correctly
@ -91,11 +85,6 @@ if(hasProperty('target') && target == 'android') {
apply plugin: 'java'
apply plugin: 'maven'
{{#supportJava6}}
sourceCompatibility = JavaVersion.VERSION_1_6
targetCompatibility = JavaVersion.VERSION_1_6
{{/supportJava6}}
{{^supportJava6}}
{{#java8}}
sourceCompatibility = JavaVersion.VERSION_1_8
targetCompatibility = JavaVersion.VERSION_1_8
@ -104,7 +93,6 @@ if(hasProperty('target') && target == 'android') {
sourceCompatibility = JavaVersion.VERSION_1_7
targetCompatibility = JavaVersion.VERSION_1_7
{{/java8}}
{{/supportJava6}}
install {
repositories.mavenInstaller {

View File

@ -144,11 +144,6 @@
<artifactId>maven-compiler-plugin</artifactId>
<version>3.6.1</version>
<configuration>
{{#supportJava6}}
<source>1.6</source>
<target>1.6</target>
{{/supportJava6}}
{{^supportJava6}}
{{#java8}}
<source>1.8</source>
<target>1.8</target>
@ -157,7 +152,6 @@
<source>1.7</source>
<target>1.7</target>
{{/java8}}
{{/supportJava6}}
</configuration>
</plugin>
<plugin>
@ -166,17 +160,12 @@
<version>3.1.1</version>
<configuration>
<doclint>none</doclint>
{{#supportJava6}}
<source>1.6</source>
{{/supportJava6}}
{{^supportJava6}}
{{#java8}}
<source>1.8</source>
{{/java8}}
{{^java8}}
<source>1.7</source>
{{/java8}}
{{/supportJava6}}
</configuration>
<executions>
<execution>

View File

@ -34,15 +34,9 @@ import java.security.cert.X509Certificate;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
{{^supportJava6}}
import java.nio.file.Files;
import java.nio.file.StandardCopyOption;
import org.glassfish.jersey.logging.LoggingFeature;
{{/supportJava6}}
{{#supportJava6}}
import org.apache.commons.io.FileUtils;
import org.glassfish.jersey.filter.LoggingFilter;
{{/supportJava6}}
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.Collection;
@ -997,13 +991,7 @@ public class ApiClient{{#java8}} extends JavaTimeFormatter{{/java8}} {
public File downloadFileFromResponse(Response response) throws ApiException {
try {
File file = prepareDownloadFile(response);
{{^supportJava6}}
Files.copy(response.readEntity(InputStream.class), file.toPath(), StandardCopyOption.REPLACE_EXISTING);
{{/supportJava6}}
{{#supportJava6}}
// Java6 falls back to commons.io for file copying
FileUtils.copyToFile(response.readEntity(InputStream.class), file);
{{/supportJava6}}
return file;
} catch (IOException e) {
throw new ApiException(e);
@ -1259,15 +1247,10 @@ public class ApiClient{{#java8}} extends JavaTimeFormatter{{/java8}} {
// turn off compliance validation to be able to send payloads with DELETE calls
clientConfig.property(ClientProperties.SUPPRESS_HTTP_COMPLIANCE_VALIDATION, true);
if (debugging) {
{{^supportJava6}}
clientConfig.register(new LoggingFeature(java.util.logging.Logger.getLogger(LoggingFeature.DEFAULT_LOGGER_NAME), java.util.logging.Level.INFO, LoggingFeature.Verbosity.PAYLOAD_ANY, 1024*50 /* Log payloads up to 50K */));
clientConfig.property(LoggingFeature.LOGGING_FEATURE_VERBOSITY, LoggingFeature.Verbosity.PAYLOAD_ANY);
// Set logger to ALL
java.util.logging.Logger.getLogger(LoggingFeature.DEFAULT_LOGGER_NAME).setLevel(java.util.logging.Level.ALL);
{{/supportJava6}}
{{#supportJava6}}
clientConfig.register(new LoggingFilter(java.util.logging.Logger.getLogger(LoggingFilter.class.getName()), true));
{{/supportJava6}}
} else {
// suppress warnings for payloads with DELETE calls:
java.util.logging.Logger.getLogger("org.glassfish.jersey.client").setLevel(java.util.logging.Level.SEVERE);

View File

@ -33,11 +33,6 @@ if(hasProperty('target') && target == 'android') {
targetSdkVersion 25
}
compileOptions {
{{#supportJava6}}
sourceCompatibility JavaVersion.VERSION_1_6
targetCompatibility JavaVersion.VERSION_1_6
{{/supportJava6}}
{{^supportJava6}}
{{#java8}}
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
@ -46,7 +41,6 @@ if(hasProperty('target') && target == 'android') {
sourceCompatibility JavaVersion.VERSION_1_7
targetCompatibility JavaVersion.VERSION_1_7
{{/java8}}
{{/supportJava6}}
}
// Rename the aar correctly
@ -90,11 +84,6 @@ if(hasProperty('target') && target == 'android') {
apply plugin: 'java'
apply plugin: 'maven'
{{#supportJava6}}
sourceCompatibility = JavaVersion.VERSION_1_6
targetCompatibility = JavaVersion.VERSION_1_6
{{/supportJava6}}
{{^supportJava6}}
{{#java8}}
sourceCompatibility = JavaVersion.VERSION_1_8
targetCompatibility = JavaVersion.VERSION_1_8
@ -103,7 +92,6 @@ if(hasProperty('target') && target == 'android') {
sourceCompatibility = JavaVersion.VERSION_1_7
targetCompatibility = JavaVersion.VERSION_1_7
{{/java8}}
{{/supportJava6}}
install {
repositories.mavenInstaller {
@ -124,14 +112,7 @@ ext {
{{#openApiNullable}}
jackson_databind_nullable_version = "0.2.1"
{{/openApiNullable}}
{{#supportJava6}}
jersey_version = "2.6"
commons_io_version=2.5
commons_lang3_version=3.6
{{/supportJava6}}
{{^supportJava6}}
jersey_version = "2.27"
{{/supportJava6}}
junit_version = "4.13.1"
{{#threetenbp}}
threetenbp_version = "2.9.10"
@ -170,10 +151,6 @@ dependencies {
{{#hasHttpSignatureMethods}}
implementation "org.tomitribe:tomitribe-http-signatures:$tomitribe_http_signatures_version"
{{/hasHttpSignatureMethods}}
{{#supportJava6}}
implementation "commons-io:commons-io:$commons_io_version"
implementation "org.apache.commons:commons-lang3:$commons_lang3_version"
{{/supportJava6}}
{{#threetenbp}}
implementation "com.github.joschi.jackson:jackson-datatype-threetenbp:$threetenbp_version"
{{/threetenbp}}

View File

@ -10,11 +10,11 @@ lazy val root = (project in file(".")).
resolvers += Resolver.mavenLocal,
libraryDependencies ++= Seq(
"io.swagger" % "swagger-annotations" % "1.5.22",
"org.glassfish.jersey.core" % "jersey-client" % {{#supportJava6}}"2.6"{{/supportJava6}}{{^supportJava6}}"2.27"{{/supportJava6}},{{^supportJava6}}
"org.glassfish.jersey.inject" % "jersey-hk2" % "2.27",{{/supportJava6}}
"org.glassfish.jersey.media" % "jersey-media-multipart" % {{#supportJava6}}"2.6"{{/supportJava6}}{{^supportJava6}}"2.27"{{/supportJava6}},
"org.glassfish.jersey.media" % "jersey-media-json-jackson" % {{#supportJava6}}"2.6"{{/supportJava6}}{{^supportJava6}}"2.27"{{/supportJava6}},
"org.glassfish.jersey.connectors" % "jersey-apache-connector" % {{#supportJava6}}"2.6"{{/supportJava6}}{{^supportJava6}}"2.27"{{/supportJava6}},
"org.glassfish.jersey.core" % "jersey-client" % "2.27",
"org.glassfish.jersey.inject" % "jersey-hk2" % "2.27",
"org.glassfish.jersey.media" % "jersey-media-multipart" % "2.27",
"org.glassfish.jersey.media" % "jersey-media-json-jackson" % "2.27",
"org.glassfish.jersey.connectors" % "jersey-apache-connector" % "2.27",
"com.fasterxml.jackson.core" % "jackson-core" % "2.10.4" % "compile",
"com.fasterxml.jackson.core" % "jackson-annotations" % "2.10.4" % "compile",
"com.fasterxml.jackson.core" % "jackson-databind" % "2.10.4" % "compile",
@ -36,10 +36,6 @@ lazy val root = (project in file(".")).
{{^java8}}
"com.brsanthu" % "migbase64" % "2.2",
{{/java8}}
{{#supportJava6}}
"org.apache.commons" % "commons-lang3" % "3.6",
"commons-io" % "commons-io" % "2.5",
{{/supportJava6}}
"javax.annotation" % "javax.annotation-api" % "1.3.2" % "compile",
"junit" % "junit" % "4.13.1" % "test",
"com.novocode" % "junit-interface" % "0.10" % "test"

View File

@ -16,15 +16,10 @@ import com.fasterxml.jackson.annotation.JsonAnySetter;
{{/additionalPropertiesType}}
{{/model}}
{{/models}}
{{^supportJava6}}
import java.util.Objects;
import java.util.Arrays;
import java.util.Map;
import java.util.HashMap;
{{/supportJava6}}
{{#supportJava6}}
import org.apache.commons.lang3.ObjectUtils;
{{/supportJava6}}
{{#imports}}
import {{import}};
{{/imports}}

View File

@ -251,7 +251,6 @@ public class {{classname}} {{#parent}}extends {{{parent}}} {{/parent}}{{#vendorE
{{/vars}}
{{>libraries/jersey2/additional_properties}}
{{^supportJava6}}
/**
* Return true if this {{name}} object is equal to o.
*/
@ -286,30 +285,6 @@ public class {{classname}} {{#parent}}extends {{{parent}}} {{/parent}}{{#vendorE
{{/useReflectionEqualsHashCode}}
}
{{/supportJava6}}
{{#supportJava6}}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}{{#hasVars}}
{{classname}} {{classVarName}} = ({{classname}}) o;
return {{#vars}}ObjectUtils.equals(this.{{name}}, {{classVarName}}.{{name}}){{^-last}} &&
{{/-last}}{{/vars}}{{#parent}} &&
super.equals(o){{/parent}};{{/hasVars}}{{^hasVars}}
return true;{{/hasVars}}
}
@Override
public int hashCode() {
return ObjectUtils.hashCodeMulti({{#vars}}{{name}}{{^-last}}, {{/-last}}{{/vars}}{{#parent}}{{#hasVars}}, {{/hasVars}}super.hashCode(){{/parent}});
}
{{/supportJava6}}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();

View File

@ -145,11 +145,6 @@
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.1</version>
<configuration>
{{#supportJava6}}
<source>1.6</source>
<target>1.6</target>
{{/supportJava6}}
{{^supportJava6}}
{{#java8}}
<source>1.8</source>
<target>1.8</target>
@ -158,7 +153,6 @@
<source>1.7</source>
<target>1.7</target>
{{/java8}}
{{/supportJava6}}
<fork>true</fork>
<meminitial>128m</meminitial>
<maxmem>512m</maxmem>
@ -182,17 +176,12 @@
</executions>
<configuration>
<doclint>none</doclint>
{{#supportJava6}}
<source>1.6</source>
{{/supportJava6}}
{{^supportJava6}}
{{#java8}}
<source>1.8</source>
{{/java8}}
{{^java8}}
<source>1.7</source>
{{/java8}}
{{/supportJava6}}
<tags>
<tag>
<name>http.response.details</name>
@ -262,13 +251,11 @@
<artifactId>jersey-client</artifactId>
<version>${jersey-version}</version>
</dependency>
{{^supportJava6}}
<dependency>
<groupId>org.glassfish.jersey.inject</groupId>
<artifactId>jersey-hk2</artifactId>
<version>${jersey-version}</version>
</dependency>
{{/supportJava6}}
<dependency>
<groupId>org.glassfish.jersey.media</groupId>
<artifactId>jersey-media-multipart</artifactId>
@ -340,18 +327,6 @@
<version>2.2</version>
</dependency>
{{/java8}}
{{#supportJava6}}
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>${commons-lang3-version}</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>${commons-io-version}</version>
</dependency>
{{/supportJava6}}
{{#hasHttpSignatureMethods}}
<dependency>
<groupId>org.tomitribe</groupId>
@ -397,14 +372,7 @@
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<swagger-annotations-version>1.6.1</swagger-annotations-version>
{{^supportJava6}}
<jersey-version>2.30.1</jersey-version>
{{/supportJava6}}
{{#supportJava6}}
<jersey-version>2.6</jersey-version>
<commons-io-version>2.5</commons-io-version>
<commons-lang3-version>3.6</commons-lang3-version>
{{/supportJava6}}
<jackson-version>2.10.4</jackson-version>
<jackson-databind-version>2.10.4</jackson-databind-version>
<jackson-databind-nullable-version>0.2.1</jackson-databind-nullable-version>

View File

@ -18,7 +18,7 @@
## Requirements
Building the API client library requires:
1. Java {{#supportJava6}}1.6{{/supportJava6}}{{^supportJava6}}{{#java8}}1.8{{/java8}}{{^java8}}1.7{{/java8}}{{/supportJava6}}+
1. Java {{#java8}}1.8{{/java8}}{{^java8}}1.7{{/java8}}+
2. Maven/Gradle
## Installation

View File

@ -40,11 +40,6 @@ if(hasProperty('target') && target == 'android') {
targetSdkVersion 25
}
compileOptions {
{{#supportJava6}}
sourceCompatibility JavaVersion.VERSION_1_6
targetCompatibility JavaVersion.VERSION_1_6
{{/supportJava6}}
{{^supportJava6}}
{{#java8}}
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
@ -53,7 +48,6 @@ if(hasProperty('target') && target == 'android') {
sourceCompatibility JavaVersion.VERSION_1_7
targetCompatibility JavaVersion.VERSION_1_7
{{/java8}}
{{/supportJava6}}
}
// Rename the aar correctly
@ -98,11 +92,6 @@ if(hasProperty('target') && target == 'android') {
apply plugin: 'java'
apply plugin: 'maven'
{{#supportJava6}}
sourceCompatibility = JavaVersion.VERSION_1_6
targetCompatibility = JavaVersion.VERSION_1_6
{{/supportJava6}}
{{^supportJava6}}
{{#java8}}
sourceCompatibility = JavaVersion.VERSION_1_8
targetCompatibility = JavaVersion.VERSION_1_8
@ -111,7 +100,6 @@ if(hasProperty('target') && target == 'android') {
sourceCompatibility = JavaVersion.VERSION_1_7
targetCompatibility = JavaVersion.VERSION_1_7
{{/java8}}
{{/supportJava6}}
install {
repositories.mavenInstaller {

View File

@ -327,7 +327,7 @@
</dependency>
</dependencies>
<properties>
<java.version>{{#supportJava6}}1.6{{/supportJava6}}{{^supportJava6}}{{#java8}}1.8{{/java8}}{{^java8}}1.7{{/java8}}{{/supportJava6}}</java.version>
<java.version>{{#java8}}1.8{{/java8}}{{^java8}}1.7{{/java8}}</java.version>
<maven.compiler.source>${java.version}</maven.compiler.source>
<maven.compiler.target>${java.version}</maven.compiler.target>
<gson-fire-version>1.8.4</gson-fire-version>

View File

@ -560,13 +560,7 @@ public class ApiClient{{#java8}} extends JavaTimeFormatter{{/java8}} {
public File downloadFileFromResponse(Response response) throws ApiException {
try {
File file = prepareDownloadFile(response);
{{^supportJava6}}
Files.copy(response.readEntity(InputStream.class), file.toPath());
{{/supportJava6}}
{{#supportJava6}}
// Java6 falls back to commons.io for file copying
FileUtils.copyToFile(response.readEntity(InputStream.class), file);
{{/supportJava6}}
return file;
} catch (IOException e) {
throw new ApiException(e);

View File

@ -33,11 +33,6 @@ if(hasProperty('target') && target == 'android') {
targetSdkVersion 23
}
compileOptions {
{{#supportJava6}}
sourceCompatibility JavaVersion.VERSION_1_6
targetCompatibility JavaVersion.VERSION_1_6
{{/supportJava6}}
{{^supportJava6}}
{{#java8}}
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
@ -46,7 +41,6 @@ if(hasProperty('target') && target == 'android') {
sourceCompatibility JavaVersion.VERSION_1_7
targetCompatibility JavaVersion.VERSION_1_7
{{/java8}}
{{/supportJava6}}
}
// Rename the aar correctly
@ -90,11 +84,6 @@ if(hasProperty('target') && target == 'android') {
apply plugin: 'java'
apply plugin: 'maven'
{{#supportJava6}}
sourceCompatibility = JavaVersion.VERSION_1_6
targetCompatibility = JavaVersion.VERSION_1_6
{{/supportJava6}}
{{^supportJava6}}
{{#java8}}
sourceCompatibility = JavaVersion.VERSION_1_8
targetCompatibility = JavaVersion.VERSION_1_8
@ -103,7 +92,6 @@ if(hasProperty('target') && target == 'android') {
sourceCompatibility = JavaVersion.VERSION_1_7
targetCompatibility = JavaVersion.VERSION_1_7
{{/java8}}
{{/supportJava6}}
install {
repositories.mavenInstaller {
@ -129,10 +117,6 @@ ext {
{{^java8}}
jodatime_version = "2.9.9"
{{/java8}}
{{#supportJava6}}
commons_io_version=2.5
commons_lang3_version=3.5
{{/supportJava6}}
junit_version = "4.13"
}
@ -157,10 +141,6 @@ dependencies {
implementation "joda-time:joda-time:$jodatime_version"
implementation "com.brsanthu:migbase64:2.2"
{{/java8}}
{{#supportJava6}}
implementation "commons-io:commons-io:$commons_io_version"
implementation "org.apache.commons:commons-lang3:$commons_lang3_version"
{{/supportJava6}}
implementation 'javax.annotation:javax.annotation-api:1.3.2'
testImplementation "junit:junit:$junit_version"
}

View File

@ -25,10 +25,6 @@ lazy val root = (project in file(".")).
"joda-time" % "joda-time" % "2.9.9" % "compile",
"com.brsanthu" % "migbase64" % "2.2" % "compile",
{{/java8}}
{{#supportJava6}}
"org.apache.commons" % "commons-lang3" % "3.5" % "compile",
"commons-io" % "commons-io" % "2.5" % "compile",
{{/supportJava6}}
"javax.annotation" % "javax.annotation-api" % "1.3.2" % "compile",
"junit" % "junit" % "4.13" % "test",
"com.novocode" % "junit-interface" % "0.10" % "test"

View File

@ -142,11 +142,6 @@
<artifactId>maven-compiler-plugin</artifactId>
<version>2.5.1</version>
<configuration>
{{#supportJava6}}
<source>1.6</source>
<target>1.6</target>
{{/supportJava6}}
{{^supportJava6}}
{{#java8}}
<source>1.8</source>
<target>1.8</target>
@ -155,7 +150,6 @@
<source>1.7</source>
<target>1.7</target>
{{/java8}}
{{/supportJava6}}
</configuration>
</plugin>
<plugin>
@ -164,17 +158,12 @@
<version>3.1.1</version>
<configuration>
<doclint>none</doclint>
{{#supportJava6}}
<source>1.6</source>
{{/supportJava6}}
{{^supportJava6}}
{{#java8}}
<source>1.8</source>
{{/java8}}
{{^java8}}
<source>1.7</source>
{{/java8}}
{{/supportJava6}}
</configuration>
<executions>
<execution>
@ -263,19 +252,6 @@
</dependency>
{{/java8}}
{{#supportJava6}}
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>${commons_lang3_version}</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>${commons_io_version}</version>
</dependency>
{{/supportJava6}}
<dependency>
<groupId>org.jboss.resteasy</groupId>
<artifactId>resteasy-jackson2-provider</artifactId>
@ -317,10 +293,6 @@
{{^java8}}
<jodatime-version>2.9.9</jodatime-version>
{{/java8}}
{{#supportJava6}}
<commons_io_version>2.5</commons_io_version>
<commons_lang3_version>3.6</commons_lang3_version>
{{/supportJava6}}
<maven-plugin-version>1.0.0</maven-plugin-version>
<junit-version>4.13</junit-version>
</properties>

View File

@ -33,11 +33,6 @@ if(hasProperty('target') && target == 'android') {
targetSdkVersion 22
}
compileOptions {
{{#supportJava6}}
sourceCompatibility JavaVersion.VERSION_1_6
targetCompatibility JavaVersion.VERSION_1_6
{{/supportJava6}}
{{^supportJava6}}
{{#java8}}
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
@ -46,7 +41,6 @@ if(hasProperty('target') && target == 'android') {
sourceCompatibility JavaVersion.VERSION_1_7
targetCompatibility JavaVersion.VERSION_1_7
{{/java8}}
{{/supportJava6}}
}
// Rename the aar correctly
@ -91,11 +85,6 @@ if(hasProperty('target') && target == 'android') {
apply plugin: 'java'
apply plugin: 'maven'
{{#supportJava6}}
sourceCompatibility = JavaVersion.VERSION_1_6
targetCompatibility = JavaVersion.VERSION_1_6
{{/supportJava6}}
{{^supportJava6}}
{{#java8}}
sourceCompatibility = JavaVersion.VERSION_1_8
targetCompatibility = JavaVersion.VERSION_1_8
@ -104,7 +93,6 @@ if(hasProperty('target') && target == 'android') {
sourceCompatibility = JavaVersion.VERSION_1_7
targetCompatibility = JavaVersion.VERSION_1_7
{{/java8}}
{{/supportJava6}}
install {
repositories.mavenInstaller {

View File

@ -144,11 +144,6 @@
<artifactId>maven-compiler-plugin</artifactId>
<version>3.6.1</version>
<configuration>
{{#supportJava6}}
<source>1.6</source>
<target>1.6</target>
{{/supportJava6}}
{{^supportJava6}}
{{#java8}}
<source>1.8</source>
<target>1.8</target>
@ -157,7 +152,6 @@
<source>1.7</source>
<target>1.7</target>
{{/java8}}
{{/supportJava6}}
</configuration>
</plugin>
<plugin>

View File

@ -33,11 +33,6 @@ if(hasProperty('target') && target == 'android') {
targetSdkVersion 25
}
compileOptions {
{{#supportJava6}}
sourceCompatibility JavaVersion.VERSION_1_6
targetCompatibility JavaVersion.VERSION_1_6
{{/supportJava6}}
{{^supportJava6}}
{{#java8}}
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
@ -46,7 +41,6 @@ if(hasProperty('target') && target == 'android') {
sourceCompatibility JavaVersion.VERSION_1_7
targetCompatibility JavaVersion.VERSION_1_7
{{/java8}}
{{/supportJava6}}
}
// Rename the aar correctly

View File

@ -144,11 +144,6 @@
<artifactId>maven-compiler-plugin</artifactId>
<version>3.6.1</version>
<configuration>
{{#supportJava6}}
<source>1.6</source>
<target>1.6</target>
{{/supportJava6}}
{{^supportJava6}}
{{#java8}}
<source>1.8</source>
<target>1.8</target>
@ -157,7 +152,6 @@
<source>1.7</source>
<target>1.7</target>
{{/java8}}
{{/supportJava6}}
</configuration>
</plugin>
<plugin>
@ -166,17 +160,12 @@
<version>3.1.1</version>
<configuration>
<doclint>none</doclint>
{{#supportJava6}}
<source>1.6</source>
{{/supportJava6}}
{{^supportJava6}}
{{#java8}}
<source>1.8</source>
{{/java8}}
{{^java8}}
<source>1.7</source>
{{/java8}}
{{/supportJava6}}
</configuration>
<executions>
<execution>

View File

@ -33,11 +33,6 @@ if(hasProperty('target') && target == 'android') {
targetSdkVersion 25
}
compileOptions {
{{#supportJava6}}
sourceCompatibility JavaVersion.VERSION_1_6
targetCompatibility JavaVersion.VERSION_1_6
{{/supportJava6}}
{{^supportJava6}}
{{#java8}}
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
@ -46,7 +41,6 @@ if(hasProperty('target') && target == 'android') {
sourceCompatibility JavaVersion.VERSION_1_7
targetCompatibility JavaVersion.VERSION_1_7
{{/java8}}
{{/supportJava6}}
}
// Rename the aar correctly
@ -91,11 +85,6 @@ if(hasProperty('target') && target == 'android') {
apply plugin: 'java'
apply plugin: 'maven'
{{#supportJava6}}
sourceCompatibility = JavaVersion.VERSION_1_6
targetCompatibility = JavaVersion.VERSION_1_6
{{/supportJava6}}
{{^supportJava6}}
{{#java8}}
sourceCompatibility = JavaVersion.VERSION_1_8
targetCompatibility = JavaVersion.VERSION_1_8
@ -104,7 +93,6 @@ if(hasProperty('target') && target == 'android') {
sourceCompatibility = JavaVersion.VERSION_1_7
targetCompatibility = JavaVersion.VERSION_1_7
{{/java8}}
{{/supportJava6}}
install {
repositories.mavenInstaller {

View File

@ -44,7 +44,7 @@ public class ApiClient {
public ApiClient() {
// Setup authentications (key: authentication name, value: authentication).
authentications = new HashMap<{{#supportJava6}}String, Authentication{{/supportJava6}}>();{{#authMethods}}{{#isBasic}}{{#isBasicBasic}}
authentications = new HashMap<>();{{#authMethods}}{{#isBasic}}{{#isBasicBasic}}
// authentications.put("{{name}}", new HttpBasicAuth());{{/isBasicBasic}}{{^isBasicBasic}}
// authentications.put("{{name}}", new HttpBearerAuth("{{scheme}}"));{{/isBasicBasic}}{{/isBasic}}{{#isApiKey}}
authentications.put("{{name}}", new ApiKeyAuth({{#isKeyInHeader}}"header"{{/isKeyInHeader}}{{#isKeyInQuery}}"query"{{/isKeyInQuery}}{{#isKeyInCookie}}"cookie"{{/isKeyInCookie}}, "{{keyParamName}}"));{{/isApiKey}}{{#isOAuth}}
@ -62,9 +62,9 @@ public class ApiClient {
basePath = basePath + "/";
}
Map<String, String> extraHeaders = new HashMap<{{#supportJava6}}String, String{{/supportJava6}}>();
Map<String, String> extraCookies = new HashMap<{{#supportJava6}}String, String{{/supportJava6}}>();
List<Pair> extraQueryParams = new ArrayList<{{#supportJava6}}Pair{{/supportJava6}}>();
Map<String, String> extraHeaders = new HashMap<>();
Map<String, String> extraCookies = new HashMap<>();
List<Pair> extraQueryParams = new ArrayList<>();
for (String authName : authentications.keySet()) {
Authentication auth = authentications.get(authName);

View File

@ -44,7 +44,7 @@ public class ApiClient {
public ApiClient() {
// Setup authentications (key: authentication name, value: authentication).
authentications = new HashMap<{{#supportJava6}}String, Authentication{{/supportJava6}}>();{{#authMethods}}{{#isBasic}}
authentications = new HashMap<>();{{#authMethods}}{{#isBasic}}
// authentications.put("{{name}}", new HttpBasicAuth());{{/isBasic}}{{#isApiKey}}
authentications.put("{{name}}", new ApiKeyAuth({{#isKeyInHeader}}"header"{{/isKeyInHeader}}{{#isKeyInQuery}}"query"{{/isKeyInQuery}}{{#isKeyInCookie}}"query"{{/isKeyInCookie}}, "{{keyParamName}}"));{{/isApiKey}}{{#isOAuth}}
// authentications.put("{{name}}", new OAuth());{{/isOAuth}}{{/authMethods}}
@ -61,9 +61,9 @@ public class ApiClient {
basePath = basePath + "/";
}
Map<String, String> extraHeaders = new HashMap<{{#supportJava6}}String, String{{/supportJava6}}>();
Map<String, String> extraCookies = new HashMap<{{#supportJava6}}String, String{{/supportJava6}}>();
List<Pair> extraQueryParams = new ArrayList<{{#supportJava6}}Pair{{/supportJava6}}>();
Map<String, String> extraHeaders = new HashMap<>();
Map<String, String> extraCookies = new HashMap<>();
List<Pair> extraQueryParams = new ArrayList<>();
for (String authName : authentications.keySet()) {
Authentication auth = authentications.get(authName);

View File

@ -144,11 +144,6 @@
<artifactId>maven-compiler-plugin</artifactId>
<version>3.6.1</version>
<configuration>
{{#supportJava6}}
<source>1.6</source>
<target>1.6</target>
{{/supportJava6}}
{{^supportJava6}}
{{#java8}}
<source>1.8</source>
<target>1.8</target>
@ -157,7 +152,6 @@
<source>1.7</source>
<target>1.7</target>
{{/java8}}
{{/supportJava6}}
</configuration>
</plugin>
<plugin>
@ -166,17 +160,12 @@
<version>3.1.1</version>
<configuration>
<doclint>none</doclint>
{{#supportJava6}}
<source>1.6</source>
{{/supportJava6}}
{{^supportJava6}}
{{#java8}}
<source>1.8</source>
{{/java8}}
{{^java8}}
<source>1.7</source>
{{/java8}}
{{/supportJava6}}
</configuration>
<executions>
<execution>
@ -414,7 +403,7 @@
</dependencies>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<java.version>{{#supportJava6}}1.6{{/supportJava6}}{{^supportJava6}}{{#java8}}1.8{{/java8}}{{^java8}}1.7{{/java8}}{{/supportJava6}}</java.version>
<java.version>{{#java8}}1.8{{/java8}}{{^java8}}1.7{{/java8}}</java.version>
<maven.compiler.source>${java.version}</maven.compiler.source>
<maven.compiler.target>${java.version}</maven.compiler.target>
<gson-fire-version>1.8.3</gson-fire-version>

View File

@ -123,10 +123,10 @@ public class ApiClient{{#java8}} extends JavaTimeFormatter{{/java8}} {
public synchronized WebClient getWebClient() {
String webClientIdentifier = "web-client-" + identifier;
WebClient webClient = Vertx.currentContext().get(webClientIdentifier);
WebClient webClient = this.vertx.getOrCreateContext().get(webClientIdentifier);
if (webClient == null) {
webClient = buildWebClient(vertx, config);
Vertx.currentContext().put(webClientIdentifier, webClient);
this.vertx.getOrCreateContext().put(webClientIdentifier, webClient);
}
return webClient;
}

View File

@ -154,17 +154,12 @@
<version>3.1.1</version>
<configuration>
<doclint>none</doclint>
{{#supportJava6}}
<source>1.6</source>
{{/supportJava6}}
{{^supportJava6}}
{{#java8}}
<source>1.8</source>
{{/java8}}
{{^java8}}
<source>1.7</source>
{{/java8}}
{{/supportJava6}}
</configuration>
<executions>
<execution>

View File

@ -62,7 +62,7 @@ public class {{classname}} {
* @see <a href="{{url}}">{{summary}} Documentation</a>
{{/externalDocs}}
*/
public {{#returnType}}{{#isArray}}Flux<{{{returnBaseType}}}>{{/isArray}}{{^isArray}}Mono<{{{returnType}}}>{{/isArray}} {{/returnType}}{{^returnType}}Mono<Void> {{/returnType}}{{operationId}}({{#allParams}}{{{dataType}}} {{paramName}}{{^-last}}, {{/-last}}{{/allParams}}) throws WebClientResponseException {
public {{#returnType}}{{#isArray}}Flux<{{{returnBaseType}}}>{{/isArray}}{{^isArray}}Mono<{{{returnType}}}>{{/isArray}} {{/returnType}}{{^returnType}}Mono<Void> {{/returnType}}{{operationId}}({{#allParams}}{{#isFile}}{{#useAbstractionForFiles}}{{#collectionFormat}}java.util.Collection<org.springframework.core.io.AbstractResource>{{/collectionFormat}}{{^collectionFormat}}org.springframework.core.io.AbstractResource{{/collectionFormat}}{{/useAbstractionForFiles}}{{^useAbstractionForFiles}}{{{dataType}}}{{/useAbstractionForFiles}}{{/isFile}}{{^isFile}}{{{dataType}}}{{/isFile}} {{paramName}}{{^-last}}, {{/-last}}{{/allParams}}) throws WebClientResponseException {
Object postBody = {{#bodyParam}}{{paramName}}{{/bodyParam}}{{^bodyParam}}null{{/bodyParam}};
{{#allParams}}
{{#required}}
@ -109,7 +109,7 @@ public class {{classname}} {
{{#formParams}}
if ({{paramName}} != null)
formParams.add{{#collectionFormat}}All{{/collectionFormat}}("{{baseName}}", {{#isFile}}{{^collectionFormat}}new FileSystemResource({{paramName}}){{/collectionFormat}}{{/isFile}}{{#isFile}}{{#collectionFormat}}{{paramName}}.stream().map(FileSystemResource::new).collect(Collectors.toList()){{/collectionFormat}}{{/isFile}}{{^isFile}}{{paramName}}{{/isFile}});
formParams.add{{#collectionFormat}}All{{/collectionFormat}}("{{baseName}}", {{#isFile}}{{^collectionFormat}}{{#useAbstractionForFiles}}{{paramName}}{{/useAbstractionForFiles}}{{^useAbstractionForFiles}}new FileSystemResource({{paramName}}){{/useAbstractionForFiles}}{{/collectionFormat}}{{/isFile}}{{#isFile}}{{#collectionFormat}}{{paramName}}.stream(){{^useAbstractionForFiles}}.map(FileSystemResource::new){{/useAbstractionForFiles}}.collect(Collectors.toList()){{/collectionFormat}}{{/isFile}}{{^isFile}}{{paramName}}{{/isFile}});
{{/formParams}}
{{/hasFormParams}}

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