Merge branch 'sync_master_4.1.x' into 4.1.x

This commit is contained in:
wing328 2019-06-27 18:16:36 +08:00
commit 1020223007
987 changed files with 34212 additions and 13907 deletions

View File

@ -1 +1 @@
oracle64-1.8.0.152 1.8

View File

@ -131,6 +131,12 @@ script:
# WARN: Travis will timeout after 10 minutes of no stdout/stderr activity, which is problematic with mvn --quiet. # WARN: Travis will timeout after 10 minutes of no stdout/stderr activity, which is problematic with mvn --quiet.
- mvn --quiet --batch-mode --show-version clean install - mvn --quiet --batch-mode --show-version clean install
- mvn --quiet --batch-mode --show-version verify -Psamples - mvn --quiet --batch-mode --show-version verify -Psamples
# test maven plugin
- mvn clean compile -f modules/openapi-generator-maven-plugin/examples/java-client.xml
- mvn clean compile -f modules/openapi-generator-maven-plugin/examples/multi-module/pom.xml
# test gradle plugin
- (cd modules/openapi-generator-gradle-plugin/samples/local-spec && ./gradlew buildGoSdk)
- (cd modules/openapi-generator-gradle-plugin/samples/local-spec && ./gradlew openApiGenerate)
after_success: after_success:
# push to maven repo # push to maven repo
- if [ $SONATYPE_USERNAME ] && [ "$TRAVIS_PULL_REQUEST" == "false" ]; then - if [ $SONATYPE_USERNAME ] && [ "$TRAVIS_PULL_REQUEST" == "false" ]; then

View File

@ -12,6 +12,15 @@ if [ "$NODE_INDEX" = "1" ]; then
#cp CI/pom.xml.circleci pom.xml #cp CI/pom.xml.circleci pom.xml
java -version java -version
mvn --quiet verify -Psamples.circleci mvn --quiet verify -Psamples.circleci
# generate all petstore samples (client, servers, doc)
./bin/run-all-petstore
# generate all petstore samples (openapi3)
./bin/openapi3/run-all-petstore
# generate test scripts
./bin/tests/run-all-test
# test all generators with fake petstore spec (2.0, 3.0)
./bin/utils/test-fake-petstore-for-all.sh
elif [ "$NODE_INDEX" = "2" ]; then elif [ "$NODE_INDEX" = "2" ]; then
# run ensure-up-to-date sample script on SNAPSHOT version only # run ensure-up-to-date sample script on SNAPSHOT version only
project_version=`mvn org.apache.maven.plugins:maven-help-plugin:3.1.0:evaluate -Dexpression=project.version -q -DforceStdout` project_version=`mvn org.apache.maven.plugins:maven-help-plugin:3.1.0:evaluate -Dexpression=project.version -q -DforceStdout`

View File

@ -47,16 +47,16 @@ OpenAPI spec version: 1.0.0
<Reference Include="System.Runtime.Serialization" /> <Reference Include="System.Runtime.Serialization" />
<Reference Include="System.Xml" /> <Reference Include="System.Xml" />
<Reference Include="Newtonsoft.Json"> <Reference Include="Newtonsoft.Json">
<HintPath Condition="Exists('$(SolutionDir)\packages')">$(SolutionDir)\packages\Newtonsoft.Json.10.0.3\lib\net45\Newtonsoft.Json.dll</HintPath> <HintPath Condition="Exists('$(SolutionDir)\packages')">$(SolutionDir)\packages\Newtonsoft.Json.12.0.1\lib\net45\Newtonsoft.Json.dll</HintPath>
<HintPath Condition="Exists('..\packages')">..\packages\Newtonsoft.Json.10.0.3\lib\net45\Newtonsoft.Json.dll</HintPath> <HintPath Condition="Exists('..\packages')">..\packages\Newtonsoft.Json.12.0.1\lib\net45\Newtonsoft.Json.dll</HintPath>
<HintPath Condition="Exists('..\..\packages')">..\..\packages\Newtonsoft.Json.10.0.3\lib\net45\Newtonsoft.Json.dll</HintPath> <HintPath Condition="Exists('..\..\packages')">..\..\packages\Newtonsoft.Json.12.0.1\lib\net45\Newtonsoft.Json.dll</HintPath>
<HintPath Condition="Exists('..\..\vendor')">..\..\vendor\Newtonsoft.Json.10.0.3\lib\net45\Newtonsoft.Json.dll</HintPath> <HintPath Condition="Exists('..\..\vendor')">..\..\vendor\Newtonsoft.Json.12.0.1\lib\net45\Newtonsoft.Json.dll</HintPath>
</Reference> </Reference>
<Reference Include="JsonSubTypes"> <Reference Include="JsonSubTypes">
<HintPath Condition="Exists('$(SolutionDir)\packages')">$(SolutionDir)\packages\JsonSubTypes.1.2.0\lib\net45\JsonSubTypes.dll</HintPath> <HintPath Condition="Exists('$(SolutionDir)\packages')">$(SolutionDir)\packages\JsonSubTypes.1.5.2\lib\net45\JsonSubTypes.dll</HintPath>
<HintPath Condition="Exists('..\packages')">..\packages\JsonSubTypes.1.2.0\lib\net45\JsonSubTypes.dll</HintPath> <HintPath Condition="Exists('..\packages')">..\packages\JsonSubTypes.1.5.2\lib\net45\JsonSubTypes.dll</HintPath>
<HintPath Condition="Exists('..\..\packages')">..\..\packages\JsonSubTypes.1.2.0\lib\net45\JsonSubTypes.dll</HintPath> <HintPath Condition="Exists('..\..\packages')">..\..\packages\JsonSubTypes.1.5.2\lib\net45\JsonSubTypes.dll</HintPath>
<HintPath Condition="Exists('..\..\vendor')">..\..\vendor\JsonSubTypes.1.2.0\lib\net45\JsonSubTypes.dll</HintPath> <HintPath Condition="Exists('..\..\vendor')">..\..\vendor\JsonSubTypes.1.5.2\lib\net45\JsonSubTypes.dll</HintPath>
</Reference> </Reference>
<Reference Include="RestSharp"> <Reference Include="RestSharp">
<HintPath Condition="Exists('$(SolutionDir)\packages')">$(SolutionDir)\packages\RestSharp.105.1.0\lib\net45\RestSharp.dll</HintPath> <HintPath Condition="Exists('$(SolutionDir)\packages')">$(SolutionDir)\packages\RestSharp.105.1.0\lib\net45\RestSharp.dll</HintPath>
@ -65,10 +65,10 @@ OpenAPI spec version: 1.0.0
<HintPath Condition="Exists('..\..\vendor')">..\..\vendor\RestSharp.105.1.0\lib\net45\RestSharp.dll</HintPath> <HintPath Condition="Exists('..\..\vendor')">..\..\vendor\RestSharp.105.1.0\lib\net45\RestSharp.dll</HintPath>
</Reference> </Reference>
<Reference Include="nunit.framework"> <Reference Include="nunit.framework">
<HintPath Condition="Exists('$(SolutionDir)\packages')">$(SolutionDir)\packages\NUnit.2.6.4\lib\nunit.framework.dll</HintPath> <HintPath Condition="Exists('$(SolutionDir)\packages')">$(SolutionDir)\packages\NUnit.3.11.0\lib\net45\nunit.framework.dll</HintPath>
<HintPath Condition="Exists('..\packages')">..\packages\NUnit.2.6.4\lib\nunit.framework.dll</HintPath> <HintPath Condition="Exists('..\packages')">..\packages\NUnit.3.11.0\lib\net45\nunit.framework.dll</HintPath>
<HintPath Condition="Exists('..\..\packages')">..\..\packages\NUnit.2.6.4\lib\nunit.framework.dll</HintPath> <HintPath Condition="Exists('..\..\packages')">..\..\packages\NUnit.3.11.0\lib\net45\nunit.framework.dll</HintPath>
<HintPath Condition="Exists('..\..\vendor')">..\..\vendor\NUnit.2.6.4\lib\nunit.framework.dll</HintPath> <HintPath Condition="Exists('..\..\vendor')">..\..\vendor\NUnit.3.11.0\lib\net45\nunit.framework.dll</HintPath>
</Reference> </Reference>
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>

View File

@ -2,15 +2,15 @@
<div align="center"> <div align="center">
[Master](https://github.com/OpenAPITools/openapi-generator/tree/master) (`4.0.1`): [![Build Status](https://img.shields.io/travis/OpenAPITools/openapi-generator/master.svg?label=Integration%20Test)](https://travis-ci.org/OpenAPITools/openapi-generator) [Master](https://github.com/OpenAPITools/openapi-generator/tree/master) (`4.0.3`): [![Build Status](https://img.shields.io/travis/OpenAPITools/openapi-generator/master.svg?label=Integration%20Test)](https://travis-ci.org/OpenAPITools/openapi-generator)
[![Integration Test2](https://circleci.com/gh/OpenAPITools/openapi-generator.svg?style=shield)](https://circleci.com/gh/OpenAPITools/openapi-generator) [![Integration Test2](https://circleci.com/gh/OpenAPITools/openapi-generator.svg?style=shield)](https://circleci.com/gh/OpenAPITools/openapi-generator)
[![Run Status](https://api.shippable.com/projects/5af6bf74e790f4070084a115/badge?branch=master)](https://app.shippable.com/github/OpenAPITools/openapi-generator) [![Run Status](https://api.shippable.com/projects/5af6bf74e790f4070084a115/badge?branch=master)](https://app.shippable.com/github/OpenAPITools/openapi-generator)
[![Windows Test](https://ci.appveyor.com/api/projects/status/github/openapitools/openapi-generator?branch=master&svg=true&passingText=Windows%20Test%20-%20OK&failingText=Windows%20Test%20-%20Fails)](https://ci.appveyor.com/project/WilliamCheng/openapi-generator-wh2wu) [![Windows Test](https://ci.appveyor.com/api/projects/status/github/openapitools/openapi-generator?branch=master&svg=true&passingText=Windows%20Test%20-%20OK&failingText=Windows%20Test%20-%20Fails)](https://ci.appveyor.com/project/WilliamCheng/openapi-generator-wh2wu)
[`4.1.x`](https://github.com/OpenAPITools/openapi-generator/tree/4.0.x) branch: [![Build Status](https://img.shields.io/travis/OpenAPITools/openapi-generator/4.0.x.svg?label=Integration%20Test)](https://travis-ci.org/OpenAPITools/openapi-generator) [`4.1.x`](https://github.com/OpenAPITools/openapi-generator/tree/4.1.x) branch: [![Build Status](https://img.shields.io/travis/OpenAPITools/openapi-generator/4.1.x.svg?label=Integration%20Test)](https://travis-ci.org/OpenAPITools/openapi-generator)
[![Integration Test2](https://circleci.com/gh/OpenAPITools/openapi-generator/tree/4.0.x.svg?style=shield)](https://circleci.com/gh/OpenAPITools/openapi-generator) [![Integration Test2](https://circleci.com/gh/OpenAPITools/openapi-generator/tree/4.1.x.svg?style=shield)](https://circleci.com/gh/OpenAPITools/openapi-generator)
[![Run Status](https://api.shippable.com/projects/5af6bf74e790f4070084a115/badge?branch=4.0.x)](https://app.shippable.com/github/OpenAPITools/openapi-generator) [![Run Status](https://api.shippable.com/projects/5af6bf74e790f4070084a115/badge?branch=4.1.x)](https://app.shippable.com/github/OpenAPITools/openapi-generator)
[![Windows Test](https://ci.appveyor.com/api/projects/status/github/openapitools/openapi-generator?branch=4.0.x&svg=true&passingText=Windows%20Test%20-%20OK&failingText=Windows%20Test%20-%20Fails)](https://ci.appveyor.com/project/WilliamCheng/openapi-generator-wh2wu) [![Windows Test](https://ci.appveyor.com/api/projects/status/github/openapitools/openapi-generator?branch=4.1.x&svg=true&passingText=Windows%20Test%20-%20OK&failingText=Windows%20Test%20-%20Fails)](https://ci.appveyor.com/project/WilliamCheng/openapi-generator-wh2wu)
[`5.0.x`](https://github.com/OpenAPITools/openapi-generator/tree/5.0.x) branch: [![Build Status](https://img.shields.io/travis/OpenAPITools/openapi-generator/5.0.x.svg?label=Integration%20Test)](https://travis-ci.org/OpenAPITools/openapi-generator) [`5.0.x`](https://github.com/OpenAPITools/openapi-generator/tree/5.0.x) branch: [![Build Status](https://img.shields.io/travis/OpenAPITools/openapi-generator/5.0.x.svg?label=Integration%20Test)](https://travis-ci.org/OpenAPITools/openapi-generator)
[![Integration Test2](https://circleci.com/gh/OpenAPITools/openapi-generator/tree/5.0.x.svg?style=shield)](https://circleci.com/gh/OpenAPITools/openapi-generator) [![Integration Test2](https://circleci.com/gh/OpenAPITools/openapi-generator/tree/5.0.x.svg?style=shield)](https://circleci.com/gh/OpenAPITools/openapi-generator)
@ -99,8 +99,8 @@ OpenAPI Generator Version | Release Date | Notes
---------------------------- | ------------ | ----- ---------------------------- | ------------ | -----
5.0.0 (upcoming major release) [SNAPSHOT](https://oss.sonatype.org/content/repositories/snapshots/org/openapitools/openapi-generator-cli/5.0.0-SNAPSHOT/)| 13.05.2020 | Major release with breaking changes (no fallback) 5.0.0 (upcoming major release) [SNAPSHOT](https://oss.sonatype.org/content/repositories/snapshots/org/openapitools/openapi-generator-cli/5.0.0-SNAPSHOT/)| 13.05.2020 | Major release with breaking changes (no fallback)
4.1.0 (upcoming minor release) [SNAPSHOT](https://oss.sonatype.org/content/repositories/snapshots/org/openapitools/openapi-generator-cli/4.1.0-SNAPSHOT/)| 15.07.2019 | Minor release (breaking changes with fallbacks) 4.1.0 (upcoming minor release) [SNAPSHOT](https://oss.sonatype.org/content/repositories/snapshots/org/openapitools/openapi-generator-cli/4.1.0-SNAPSHOT/)| 15.07.2019 | Minor release (breaking changes with fallbacks)
4.0.2 (upcoming patch release) [SNAPSHOT](https://oss.sonatype.org/content/repositories/snapshots/org/openapitools/openapi-generator-cli/4.0.1-SNAPSHOT/)| 15.06.2019 | Patch release (minor bug fixes, etc) 4.0.3 (upcoming patch release) [SNAPSHOT](https://oss.sonatype.org/content/repositories/snapshots/org/openapitools/openapi-generator-cli/4.0.3-SNAPSHOT/)| 04.07.2019 | Patch release (minor bug fixes, etc)
[4.0.1](https://github.com/OpenAPITools/openapi-generator/releases/tag/v4.0.1) (latest stable release) | 31.05.2019 | Patch release (bug fixes, minor enhancements, etc) <!-- RELEASE_VERSION -->[4.0.2](https://github.com/OpenAPITools/openapi-generator/releases/tag/v4.0.2) (latest stable release) | 20.06.2019 | Patch release (bug fixes, minor enhancements, etc)<!-- /RELEASE_VERSION -->
OpenAPI Spec compatibility: 1.0, 1.1, 1.2, 2.0, 3.0 OpenAPI Spec compatibility: 1.0, 1.1, 1.2, 2.0, 3.0
@ -153,19 +153,19 @@ See the different versions of the [openapi-generator-cli](https://mvnrepository.
* [Readme](https://github.com/OpenAPITools/openapi-generator/blob/master/modules/openapi-generator-gradle-plugin/README.adoc) * [Readme](https://github.com/OpenAPITools/openapi-generator/blob/master/modules/openapi-generator-gradle-plugin/README.adoc)
### [1.3 - Download JAR](#table-of-contents) ### [1.3 - Download JAR](#table-of-contents)
<!-- RELEASE_VERSION -->
If you're looking for the latest stable version, you can grab it directly from Maven.org (Java 8 runtime at a minimum): If you're looking for the latest stable version, you can grab it directly from Maven.org (Java 8 runtime at a minimum):
JAR location: `http://central.maven.org/maven2/org/openapitools/openapi-generator-cli/4.0.1/openapi-generator-cli-4.0.1.jar` JAR location: `http://central.maven.org/maven2/org/openapitools/openapi-generator-cli/4.0.2/openapi-generator-cli-4.0.2.jar`
For **Mac/Linux** users: For **Mac/Linux** users:
```sh ```sh
wget http://central.maven.org/maven2/org/openapitools/openapi-generator-cli/4.0.1/openapi-generator-cli-4.0.1.jar -O openapi-generator-cli.jar wget http://central.maven.org/maven2/org/openapitools/openapi-generator-cli/4.0.2/openapi-generator-cli-4.0.2.jar -O openapi-generator-cli.jar
``` ```
For **Windows** users, you will need to install [wget](http://gnuwin32.sourceforge.net/packages/wget.htm) or you can use Invoke-WebRequest in PowerShell (3.0+), e.g. For **Windows** users, you will need to install [wget](http://gnuwin32.sourceforge.net/packages/wget.htm) or you can use Invoke-WebRequest in PowerShell (3.0+), e.g.
``` ```
Invoke-WebRequest -OutFile openapi-generator-cli.jar http://central.maven.org/maven2/org/openapitools/openapi-generator-cli/4.0.1/openapi-generator-cli-4.0.1.jar Invoke-WebRequest -OutFile openapi-generator-cli.jar http://central.maven.org/maven2/org/openapitools/openapi-generator-cli/4.0.2/openapi-generator-cli-4.0.2.jar
``` ```
After downloading the JAR, run `java -jar openapi-generator-cli.jar help` to show the usage. After downloading the JAR, run `java -jar openapi-generator-cli.jar help` to show the usage.
@ -175,7 +175,7 @@ For Mac users, please make sure Java 8 is installed (Tips: run `java -version` t
export JAVA_HOME=`/usr/libexec/java_home -v 1.8` export JAVA_HOME=`/usr/libexec/java_home -v 1.8`
export PATH=${JAVA_HOME}/bin:$PATH export PATH=${JAVA_HOME}/bin:$PATH
``` ```
<!-- /RELEASE_VERSION -->
### Launcher Script ### Launcher Script
One downside to manual jar downloads is that you don't keep up-to-date with the latest released version. We have a Bash launcher script at [bin/utils/openapi-generator.cli.sh](./bin/utils/openapi-generator-cli.sh) which resolves this issue. One downside to manual jar downloads is that you don't keep up-to-date with the latest released version. We have a Bash launcher script at [bin/utils/openapi-generator.cli.sh](./bin/utils/openapi-generator-cli.sh) which resolves this issue.
@ -368,10 +368,11 @@ npm install @openapitools/openapi-generator-cli -g
openapi-generator version openapi-generator version
``` ```
Or install a particualar OpenAPI Generator version (e.g. v4.0.1): <!-- RELEASE_VERSION -->
Or install a particular OpenAPI Generator version (e.g. v4.0.2):
```sh ```sh
npm install @openapitools/openapi-generator-cli@cli-4.0.1 -g npm install @openapitools/openapi-generator-cli@cli-4.0.2 -g
``` ```
Or install it as dev-dependency: Or install it as dev-dependency:
@ -379,7 +380,7 @@ Or install it as dev-dependency:
```sh ```sh
npm install @openapitools/openapi-generator-cli -D npm install @openapitools/openapi-generator-cli -D
``` ```
<!-- /RELEASE_VERSION -->
## [2 - Getting Started](#table-of-contents) ## [2 - Getting Started](#table-of-contents)
To generate a PHP client for [petstore.yaml](https://raw.githubusercontent.com/openapitools/openapi-generator/master/modules/openapi-generator/src/test/resources/2_0/petstore.yaml), please run the following To generate a PHP client for [petstore.yaml](https://raw.githubusercontent.com/openapitools/openapi-generator/master/modules/openapi-generator/src/test/resources/2_0/petstore.yaml), please run the following
@ -394,7 +395,9 @@ java -jar modules/openapi-generator-cli/target/openapi-generator-cli.jar generat
``` ```
(if you're on Windows, replace the last command with `java -jar modules\openapi-generator-cli\target\openapi-generator-cli.jar generate -i https://raw.githubusercontent.com/openapitools/openapi-generator/master/modules/openapi-generator/src/test/resources/2_0/petstore.yaml -g php -o c:\temp\php_api_client`) (if you're on Windows, replace the last command with `java -jar modules\openapi-generator-cli\target\openapi-generator-cli.jar generate -i https://raw.githubusercontent.com/openapitools/openapi-generator/master/modules/openapi-generator/src/test/resources/2_0/petstore.yaml -g php -o c:\temp\php_api_client`)
You can also download the JAR (latest release) directly from [maven.org](http://central.maven.org/maven2/org/openapitools/openapi-generator-cli/4.0.1/openapi-generator-cli-4.0.1.jar) <!-- RELEASE_VERSION -->
You can also download the JAR (latest release) directly from [maven.org](http://central.maven.org/maven2/org/openapitools/openapi-generator-cli/4.0.2/openapi-generator-cli-4.0.2.jar)
<!-- /RELEASE_VERSION -->
To get a list of **general** options available, please run `java -jar modules/openapi-generator-cli/target/openapi-generator-cli.jar help generate` To get a list of **general** options available, please run `java -jar modules/openapi-generator-cli/target/openapi-generator-cli.jar help generate`
@ -536,6 +539,7 @@ Here are some companies/projects (alphabetical order) using OpenAPI Generator in
- [codecentric AG](https://www.codecentric.de/) - [codecentric AG](https://www.codecentric.de/)
- [Cupix](https://www.cupix.com/) - [Cupix](https://www.cupix.com/)
- [FormAPI](https://formapi.io/) - [FormAPI](https://formapi.io/)
- [Fuse](https://www.fuse.no/)
- [GenFlow](https://github.com/RepreZen/GenFlow) - [GenFlow](https://github.com/RepreZen/GenFlow)
- [GMO Pepabo](https://pepabo.com/en/) - [GMO Pepabo](https://pepabo.com/en/)
- [GoDaddy](https://godaddy.com) - [GoDaddy](https://godaddy.com)
@ -590,7 +594,8 @@ Here are some companies/projects (alphabetical order) using OpenAPI Generator in
- 2019-05-01 - [Design and generate a REST API from Swagger / OpenAPI in Java, Python, C# and more](https://simply-how.com/design-and-generate-api-code-from-openapi) by [Simply How](https://simply-how.com/) - 2019-05-01 - [Design and generate a REST API from Swagger / OpenAPI in Java, Python, C# and more](https://simply-how.com/design-and-generate-api-code-from-openapi) by [Simply How](https://simply-how.com/)
- 2019-05-17 - [Generate Spring Boot REST API using Swagger/OpenAPI](https://www.47northlabs.com/knowledge-base/generate-spring-boot-rest-api-using-swagger-openapi/) by [Antonie Zafirov](https://www.47northlabs.com/author/antonie-zafirov/) - 2019-05-17 - [Generate Spring Boot REST API using Swagger/OpenAPI](https://www.47northlabs.com/knowledge-base/generate-spring-boot-rest-api-using-swagger-openapi/) by [Antonie Zafirov](https://www.47northlabs.com/author/antonie-zafirov/)
- 2019-05-22 - [REST APIs代码生成指南(OpenAPI Generator)](https://gum.co/openapi_generator_ebook_gb) by [William Cheng](https://twitter.com/wing328), [Xin Meng](https://github.com/xmeng1) - 2019-05-22 - [REST APIs代码生成指南(OpenAPI Generator)](https://gum.co/openapi_generator_ebook_gb) by [William Cheng](https://twitter.com/wing328), [Xin Meng](https://github.com/xmeng1)
- 2019-05/24 - [REST API 代碼生成指南 (OpenAPI Generator)](https://gum.co/openapi_generator_ebook_big5) by [William Cheng](https://twitter.com/wing328) - 2019-05-24 - [REST API 代碼生成指南 (OpenAPI Generator)](https://gum.co/openapi_generator_ebook_big5) by [William Cheng](https://twitter.com/wing328)
- 2019-06-24 - [Kubernetes Clients and OpenAPI Generator](https://speakerdeck.com/wing328/kubernetes-clients-and-openapi-generator) by [William Cheng](https://twitter.com/wing328) at [Kubernetes Contributor Summits Shanghai 2019](https://www.lfasiallc.com/events/contributors-summit-china-2019/)
## [6 - About Us](#table-of-contents) ## [6 - About Us](#table-of-contents)
@ -603,7 +608,8 @@ OpenAPI Generator core team members are contributors who have been making signif
* [@jimschubert](https://github.com/jimschubert) (2016/05) [:heart:](https://www.patreon.com/jimschubert) * [@jimschubert](https://github.com/jimschubert) (2016/05) [:heart:](https://www.patreon.com/jimschubert)
* [@cbornet](https://github.com/cbornet) (2016/05) * [@cbornet](https://github.com/cbornet) (2016/05)
* [@ackintosh](https://github.com/ackintosh) (2018/02) [:heart:](https://www.patreon.com/ackintosh/overview) * [@ackintosh](https://github.com/ackintosh) (2018/02) [:heart:](https://www.patreon.com/ackintosh/overview)
* [@jmini](https://github.com/jmini) (2018/04) * [@jmini](https://github.com/jmini) (2018/04) [:heart:](https://www.patreon.com/jmini)
* [@etherealjoy](https://github.com/etherealjoy) (2019/06)
:heart: = Link to support the contributor directly :heart: = Link to support the contributor directly
@ -774,7 +780,7 @@ If you want to join the committee, please kindly apply by sending an email to te
| Lua | @daurnimator (2017/08) | | Lua | @daurnimator (2017/08) |
| NodeJS/Javascript | @CodeNinjai (2017/07) @frol (2017/07) @cliffano (2017/07) | | NodeJS/Javascript | @CodeNinjai (2017/07) @frol (2017/07) @cliffano (2017/07) |
| ObjC | | | ObjC | |
| Perl | @wing328 (2017/07) [:heart:](https://www.patreon.com/wing328) | | Perl | @wing328 (2017/07) [:heart:](https://www.patreon.com/wing328) @yue9944882 (2019/06) |
| PHP | @jebentier (2017/07), @dkarlovi (2017/07), @mandrean (2017/08), @jfastnacht (2017/09), @ackintosh (2017/09) [:heart:](https://www.patreon.com/ackintosh/overview), @ybelenko (2018/07), @renepardon (2018/12) | | PHP | @jebentier (2017/07), @dkarlovi (2017/07), @mandrean (2017/08), @jfastnacht (2017/09), @ackintosh (2017/09) [:heart:](https://www.patreon.com/ackintosh/overview), @ybelenko (2018/07), @renepardon (2018/12) |
| PowerShell | | | PowerShell | |
| Python | @taxpon (2017/07) @frol (2017/07) @mbohlool (2017/07) @cbornet (2017/09) @kenjones-cisco (2017/11) @tomplus (2018/10) @Jyhess (2019/01) | | Python | @taxpon (2017/07) @frol (2017/07) @mbohlool (2017/07) @cbornet (2017/09) @kenjones-cisco (2017/11) @tomplus (2018/10) @Jyhess (2019/01) |
@ -811,7 +817,7 @@ OpenAPI Generator is a fork of [Swagger Codegen](https://github.com/swagger-api/
- [Jean-François Côté](https://github.com/JFCote) - [Jean-François Côté](https://github.com/JFCote)
- [Jim Schubert](https://github.com/jimschubert) - [Jim Schubert](https://github.com/jimschubert)
- [Jon Schoning](https://github.com/jonschoning) - [Jon Schoning](https://github.com/jonschoning)
- [Jérémie Bresson](https://github.com/jmini) - [Jérémie Bresson](https://github.com/jmini) [:heart:](https://www.patreon.com/jmini)
- [Jörn Ahrens](https://github.com/jayearn) - [Jörn Ahrens](https://github.com/jayearn)
- [Keni Steward](https://github.com/kenisteward) - [Keni Steward](https://github.com/kenisteward)
- [Marcin Stefaniuk](https://github.com/mstefaniuk) - [Marcin Stefaniuk](https://github.com/mstefaniuk)

View File

@ -50,7 +50,7 @@ build_script:
# install openapi-generator locally # install openapi-generator locally
- mvn clean install --quiet - mvn clean install --quiet
# run the locally installed openapi-generator-gradle-plugin # run the locally installed openapi-generator-gradle-plugin
- gradle -PopenApiGeneratorVersion=4.0.2-SNAPSHOT -b modules\openapi-generator-gradle-plugin\samples\local-spec\build.gradle buildGoSdk --info - gradle -b modules\openapi-generator-gradle-plugin\samples\local-spec\build.gradle buildGoSdk --info
test_script: test_script:
# restore test-related files # restore test-related files
- copy /b/v/y CI\samples.ci\client\petstore\csharp\OpenAPIClient\src\Org.OpenAPITools.Test\Org.OpenAPITools.Test.csproj samples\client\petstore\csharp\OpenAPIClient\src\Org.OpenAPITools.Test\Org.OpenAPITools.Test.csproj - copy /b/v/y CI\samples.ci\client\petstore\csharp\OpenAPIClient\src\Org.OpenAPITools.Test\Org.OpenAPITools.Test.csproj samples\client\petstore\csharp\OpenAPIClient\src\Org.OpenAPITools.Test\Org.OpenAPITools.Test.csproj
@ -58,9 +58,9 @@ test_script:
- dotnet test samples\client\petstore\csharp-netcore\OpenAPIClient\src\Org.OpenAPITools.Test\Org.OpenAPITools.Test.csproj - dotnet test samples\client\petstore\csharp-netcore\OpenAPIClient\src\Org.OpenAPITools.Test\Org.OpenAPITools.Test.csproj
- dotnet test samples\client\petstore\csharp-netcore\OpenAPIClientCore\src\Org.OpenAPITools.Test\Org.OpenAPITools.Test.csproj - dotnet test samples\client\petstore\csharp-netcore\OpenAPIClientCore\src\Org.OpenAPITools.Test\Org.OpenAPITools.Test.csproj
# test c# API client # test c# API client
- nunit-console samples\client\petstore\csharp\OpenAPIClient\src\Org.OpenAPITools.Test\bin\Debug\Org.OpenAPITools.Test.dll --result=myresults.xml;format=AppVeyor - 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) # test c# API client (with PropertyChanged)
- nunit-console samples\client\petstore\csharp\OpenAPIClientWithPropertyChanged\src\Org.OpenAPITools.Test\bin\Debug\Org.OpenAPITools.Test.dll --result=myresults.xml;format=AppVeyor - nunit3-console samples\client\petstore\csharp\OpenAPIClientWithPropertyChanged\src\Org.OpenAPITools.Test\bin\Debug\Org.OpenAPITools.Test.dll --result=myresults.xml;format=AppVeyor
# generate all petstore clients # generate all petstore clients
- .\bin\windows\run-all-petstore.cmd - .\bin\windows\run-all-petstore.cmd

View File

@ -27,6 +27,6 @@ fi
# if you've executed sbt assembly previously it will use that instead. # if you've executed sbt assembly previously it will use that instead.
export JAVA_OPTS="${JAVA_OPTS} -Xmx1024M -DloggerPath=conf/log4j.properties" export JAVA_OPTS="${JAVA_OPTS} -Xmx1024M -DloggerPath=conf/log4j.properties"
ags="generate -t modules/openapi-generator/src/main/resources/cpp-rest-sdk-client -i modules/openapi-generator/src/test/resources/2_0/petstore.yaml -g cpp-restsdk -o samples/client/petstore/cpp-restsdk $@" ags="generate -t modules/openapi-generator/src/main/resources/cpp-rest-sdk-client -i modules/openapi-generator/src/test/resources/2_0/petstore.yaml -g cpp-restsdk -o samples/client/petstore/cpp-restsdk/client $@"
java $JAVA_OPTS -jar $executable $ags java $JAVA_OPTS -jar $executable $ags

View File

@ -32,6 +32,6 @@ ags="generate -i modules/openapi-generator/src/test/resources/2_0/petstore-with-
java $JAVA_OPTS -jar $executable $ags java $JAVA_OPTS -jar $executable $ags
# restore csproj file # restore csproj file
echo "restore csproject file: CI/samples/client/petstore/csharp/OpenAPIClient/src/Org.OpenAPITools.Test/Org.OpenAPITools.Test.csproj" echo "restore csproject file: CI/samples.ci/client/petstore/csharp/OpenAPIClient/src/Org.OpenAPITools.Test/Org.OpenAPITools.Test.csproj"
cp ./CI/samples.ci/client/petstore/csharp/OpenAPIClient/src/Org.OpenAPITools.Test/Org.OpenAPITools.Test.csproj ./samples/client/petstore/csharp/OpenAPIClient/src/Org.OpenAPITools.Test/ cp ./CI/samples.ci/client/petstore/csharp/OpenAPIClient/src/Org.OpenAPITools.Test/Org.OpenAPITools.Test.csproj ./samples/client/petstore/csharp/OpenAPIClient/src/Org.OpenAPITools.Test/

View File

@ -0,0 +1,4 @@
#!/bin/sh
./bin/kotlin-springboot-petstore-server.sh
./bin/kotlin-springboot-petstore-server-reactive.sh

View File

@ -0,0 +1,35 @@
#!/bin/sh
SCRIPT="$0"
echo "# START SCRIPT: $SCRIPT"
while [ -h "$SCRIPT" ] ; do
ls=$(ls -ld "$SCRIPT")
link=$(expr "$ls" : '.*-> \(.*\)$')
if expr "$link" : '/.*' > /dev/null; then
SCRIPT="$link"
else
SCRIPT=$(dirname "$SCRIPT")/"$link"
fi
done
if [ ! -d "${APP_DIR}" ]; then
APP_DIR=$(dirname "$SCRIPT")/..
APP_DIR=$(cd "${APP_DIR}"; pwd)
fi
executable="./modules/openapi-generator-cli/target/openapi-generator-cli.jar"
if [ ! -f "$executable" ]
then
mvn clean package
fi
export JAVA_OPTS="${JAVA_OPTS} -Xmx1024M -DloggerPath=conf/log4j.properties"
ags="$@ generate -i modules/openapi-generator/src/test/resources/2_0/petstore.yaml -t modules/openapi-generator/src/main/resources/kotlin-spring -g kotlin-spring -o samples/server/petstore/kotlin-springboot-reactive --additional-properties=library=spring-boot,beanValidations=true,swaggerAnnotations=true,serviceImplementation=true,reactive=true"
echo "Cleaning previously generated files if any from samples/server/petstore/kotlin-springboot-reactive"
rm -rf samples/server/petstore/kotlin-springboot-reactive
echo "Generating Kotling Spring Boot reactive server..."
java $JAVA_OPTS -jar $executable $ags

View File

@ -26,7 +26,7 @@ then
fi fi
# if you've executed sbt assembly previously it will use that instead. # if you've executed sbt assembly previously it will use that instead.
export JAVA_OPTS="${JAVA_OPTS} -Xmx1024M -DloggerPath=conf/log4j.properties -Dservice" export JAVA_OPTS="${JAVA_OPTS} -Xmx1024M -DloggerPath=conf/log4j.properties"
ags="generate -i modules/openapi-generator/src/test/resources/2_0/petstore.yaml -g nodejs-server --additional-properties=googleCloudFunctions=true -o samples/server/petstore/nodejs-google-cloud-functions $@" ags="generate -i modules/openapi-generator/src/test/resources/2_0/petstore.yaml -g nodejs-server-deprecated --additional-properties=googleCloudFunctions=true -o samples/server/petstore/nodejs-google-cloud-functions -Dservice $@"
java $JAVA_OPTS -jar $executable $ags java $JAVA_OPTS -jar $executable $ags

View File

@ -26,7 +26,7 @@ then
fi fi
# if you've executed sbt assembly previously it will use that instead. # if you've executed sbt assembly previously it will use that instead.
export JAVA_OPTS="${JAVA_OPTS} -Xmx1024M -DloggerPath=conf/log4j.properties -Dservice" export JAVA_OPTS="${JAVA_OPTS} -Xmx1024M -DloggerPath=conf/log4j.properties"
ags="generate -t modules/openapi-generator/src/main/resources/nodejs -i modules/openapi-generator/src/test/resources/2_0/petstore.yaml -g nodejs-server -o samples/server/petstore/nodejs $@" ags="generate -t modules/openapi-generator/src/main/resources/nodejs -i modules/openapi-generator/src/test/resources/2_0/petstore.yaml -g nodejs-server-deprecated -o samples/server/petstore/nodejs -Dservice $@"
java $JAVA_OPTS -jar $executable $ags java $JAVA_OPTS -jar $executable $ags

View File

@ -0,0 +1,4 @@
#!/bin/sh
./bin/openapi3/kotlin-springboot-petstore-server.sh
./bin/openapi3/kotlin-springboot-petstore-server-reactive.sh

View File

@ -0,0 +1,35 @@
#!/bin/sh
SCRIPT="$0"
echo "# START SCRIPT: $SCRIPT"
while [ -h "$SCRIPT" ] ; do
ls=$(ls -ld "$SCRIPT")
link=$(expr "$ls" : '.*-> \(.*\)$')
if expr "$link" : '/.*' > /dev/null; then
SCRIPT="$link"
else
SCRIPT=$(dirname "$SCRIPT")/"$link"
fi
done
if [ ! -d "${APP_DIR}" ]; then
APP_DIR=$(dirname "$SCRIPT")/..
APP_DIR=$(cd "${APP_DIR}"; pwd)
fi
executable="./modules/openapi-generator-cli/target/openapi-generator-cli.jar"
if [ ! -f "$executable" ]
then
mvn clean package
fi
export JAVA_OPTS="${JAVA_OPTS} -Xmx1024M -DloggerPath=conf/log4j.properties"
ags="$@ generate -i modules/openapi-generator/src/test/resources/3_0/petstore.yaml -t modules/openapi-generator/src/main/resources/kotlin-spring -g kotlin-spring -o samples/server/openapi3/petstore/kotlin-springboot-reactive --additional-properties=library=spring-boot,beanValidations=true,swaggerAnnotations=true,serviceImplementation=true,reactive=true"
echo "Cleaning previously generated files if any from samples/server/openapi3/petstore/kotlin-springboot-reactive"
rm -rf samples/server/openapi3/petstore/kotlin-springboot-reactive
echo "Generating Kotling Spring Boot server..."
java $JAVA_OPTS -jar $executable $ags

View File

@ -26,7 +26,7 @@ then
fi fi
# if you've executed sbt assembly previously it will use that instead. # if you've executed sbt assembly previously it will use that instead.
export JAVA_OPTS="${JAVA_OPTS} -Xmx1024M -DloggerPath=conf/log4j.properties -Dservice" export JAVA_OPTS="${JAVA_OPTS} -Xmx1024M -DloggerPath=conf/log4j.properties"
ags="generate -i modules/openapi-generator/src/test/resources/3_0/petstore.yaml -g nodejs-server --additional-properties=googleCloudFunctions=true -o samples/server/petstore/nodejs-google-cloud-functions $@" ags="generate -i modules/openapi-generator/src/test/resources/3_0/petstore.yaml -g nodejs-server-deprecated --additional-properties=googleCloudFunctions=true -o samples/server/petstore/nodejs-google-cloud-functions -Dservice $@"
java $JAVA_OPTS -jar $executable $ags java $JAVA_OPTS -jar $executable $ags

View File

@ -26,7 +26,7 @@ then
fi fi
# if you've executed sbt assembly previously it will use that instead. # if you've executed sbt assembly previously it will use that instead.
export JAVA_OPTS="${JAVA_OPTS} -Xmx1024M -DloggerPath=conf/log4j.properties -Dservice" export JAVA_OPTS="${JAVA_OPTS} -Xmx1024M -DloggerPath=conf/log4j.properties"
ags="generate -t modules/openapi-generator/src/main/resources/nodejs -i modules/openapi-generator/src/test/resources/3_0/petstore.yaml -g nodejs-server -o samples/server/petstore/nodejs $@" ags="generate -t modules/openapi-generator/src/main/resources/nodejs -i modules/openapi-generator/src/test/resources/3_0/petstore.yaml -g nodejs-server-deprecated -o samples/server/petstore/nodejs -Dservice $@"
java $JAVA_OPTS -jar $executable $ags java $JAVA_OPTS -jar $executable $ags

View File

@ -25,6 +25,7 @@ declare -a scripts=(
"./bin/kotlin-client-threetenbp.sh" "./bin/kotlin-client-threetenbp.sh"
"./bin/kotlin-server-petstore.sh" "./bin/kotlin-server-petstore.sh"
"./bin/kotlin-springboot-petstore-server.sh" "./bin/kotlin-springboot-petstore-server.sh"
"./bin/kotlin-springboot-petstore-server-reactive.sh"
"./bin/mysql-schema-petstore.sh" "./bin/mysql-schema-petstore.sh"
"./bin/python-petstore-all.sh" "./bin/python-petstore-all.sh"
"./bin/openapi3/python-petstore.sh" "./bin/openapi3/python-petstore.sh"
@ -51,9 +52,11 @@ declare -a scripts=(
"./bin/csharp-netcore-petstore-all.sh" "./bin/csharp-netcore-petstore-all.sh"
"./bin/elixir-petstore.sh" "./bin/elixir-petstore.sh"
"./bin/go-petstore.sh" "./bin/go-petstore.sh"
"./bin/go-petstore-withxml.sh"
"./bin/go-gin-petstore-server.sh" "./bin/go-gin-petstore-server.sh"
"./bin/groovy-petstore.sh" "./bin/groovy-petstore.sh"
"./bin/apex-petstore.sh" "./bin/apex-petstore.sh"
"./bin/perl-petstore-all.sh"
#"./bin/elm-petstore-all.sh" #"./bin/elm-petstore-all.sh"
"./bin/meta-codegen.sh" "./bin/meta-codegen.sh"
# OTHERS # OTHERS

221
bin/utils/release/bump.sh Executable file
View File

@ -0,0 +1,221 @@
#!/usr/bin/env bash
#
# This script bumps from one version to another
#
# 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.
#
declare -r version_regex="([0-9]+).([0-9]+).([0-9]+)-?(SNAPSHOT){0,1}"
declare start="<!-- RELEASE_VERSION -->"
declare end="<!-- \/RELEASE_VERSION -->"
declare from="${version_regex}"
declare to=""
declare debug=${debug:-false}
declare -a from_parts=()
declare -a to_parts=()
declare -ar inc=(major minor build snapshot)
USAGE="
USAGE: $0 OPTIONS input_file
This script will bump a version number (or other value) between marker tags.
OPTIONS:
-f The 'from' version
-t The 'to' version
-s The start tag regex
default: $start
-e The end tag regex
default: $end
-i Increase by one of: ${inc[@]}
-h Print this message
EXAMPLES:
Update to next snapshot version:
$0 -f 3.0.0 -t 3.0.1-SNAPSHOT pom.xml
Update build version only (useful for docs)
$0 -f 3.0.0 -t 3.0.1 pom.xml
Update from any version to any other version
$0 -f 1.2.3 -t 9.9.9-SNAPSHOT pom.xml
Customize the start/end tags
$0 -f 1.0.0 1.0.1-SNAPSHOT -s \"<!-- START -->\" -e \"<!-- END -->\" pom.xml
"
## print an error message and exit
err() {
>&2 echo -e "$1"
exit 1
}
## debug log messages. Run with debug=true ./bump.sh
d() {
if [[ true = "${debug}" ]]; then
echo "$1"
fi
}
## outputs usage and exits
usage()
{
err "${USAGE}"
exit 1
}
## usage: version input extracted_array
## - Checks that 'input' is a valid version
## - Extracts the version parts into 'extracted_array'
version()
{
if [[ "$#" -ne 2 ]]; then
err "Call function version with two parameters: version string arr"
fi
local v=$1
if [[ "${v}" =~ $version_regex ]]; then
local major=${BASH_REMATCH[1]}
local minor=${BASH_REMATCH[2]}
local build=${BASH_REMATCH[3]}
local snapshot=false
if [[ "SNAPSHOT" = "${BASH_REMATCH[4]}" ]]; then
snapshot=true
fi
d "major=$major minor=$minor build=$build snapshot=$snapshot"
eval "$2=(${major} ${minor} ${build} ${snapshot})"
else
err "Invalid version: $v"
fi
}
while getopts "hf:t:s:e:i:" OPTION
do
case ${OPTION} in
f)
from=${OPTARG}
;;
t)
to=${OPTARG}
;;
s)
start=${OPTARG}
;;
e)
end=${OPTARG}
;;
i)
increase=${OPTARG}
if [[ ! "${inc[@]}" =~ ${increase} ]];then
err "Only support increasing by one of: ${inc[@]}"
fi
;;
h)
usage
;;
esac
done
shift $((OPTIND-1))
file=( "$@" )
if [[ ${#file[@]} -eq 0 ]];then
echo "No file specified" >&2
usage
fi
if [[ -z "${from}" ]]; then
echo "No 'from' version specified." >&2
usage
fi
# TODO: compare steps in from_parts and to_parts.
version "${from}" from_parts
if [[ -z "${to}" ]]; then
if [[ -z "${increase}" ]]; then
err "No 'to' version specified."
else
case ${increase} in
major)
to="$(( ${from_parts[0]} + 1 )).0.0"
version "$to" to_parts
;;
minor)
to="${from_parts[0]}.$(( ${from_parts[1]} + 1 )).0"
version "$to" to_parts
;;
build)
to="${from_parts[0]}.${from_parts[1]}.$(( ${from_parts[2]} + 1 ))"
version "$to" to_parts
;;
snapshot)
if [[ true = ${from_parts[3]} ]]; then
err "Can't move from SNAPSHOT to SNAPSHOT (from=${from})."
else
to="${from_parts[0]}.${from_parts[1]}.$(( ${from_parts[2]} + 1 ))-SNAPSHOT"
version "$to" to_parts
fi
;;
esac
fi
else
version "${to}" to_parts
fi
if [[ ${from_parts[3]} = true && ${to_parts[3]} = true ]]; then
err "Moving from SNAPSHOT to SNAPSHOT is not supported."
fi
cat <<EOF > sedscript.sed
/${start}/,/${end}/{
s/${from}/${to}/g
}
EOF
d "Moving from=${from} to=${to}"
trap 'rm -f sedscript.sed' EXIT
sed_cross() {
# Cross-platform sed invocation. OSX has no option to show a version number in sed.
local target=$1
sed --version >/dev/null 2>&1 && sed -e -i '' -f sedscript.sed "$target" || sed -i '' -E -f sedscript.sed "$target"
}
update_file() {
local filename=$1
local error_message="ERROR: Failed to update $filename to target version ${to}"
local original_hash=$(ruby -r digest -e "p Digest::SHA2.file(\"$filename\").hexdigest")
local final_hash=""
if ! sed_cross ${filename}; then
# occurs if, for example, the file doesn't exist.
echo "ERROR: Failed to update $filename to target version ${to}" >&2
fi
local final_hash=$(ruby -r digest -e "p Digest::SHA2.file(\"$filename\").hexdigest")
if [[ "${original_hash}" = "${final_hash}" ]]; then
# occurs if, for example, the file doesn't have expected marker tags for replacement
echo "ERROR: $filename was not modified." >&2
else
echo "Updated $filename successfully!"
fi
}
for filename in "${file[@]}"; do
update_file ${filename}
done

View File

@ -0,0 +1,96 @@
#!/usr/bin/env bash
#
# This script is used to update files to the "latest" version.
#
# usage: ./bin/utils/release_version_update.sh <from> <to>
# example: ./bin/utils/release_version_update.sh 3.0.1-SNAPSHOT 3.0.1
#
# 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.
#
declare cwd=$(cd $(dirname "${BASH_SOURCE}") && pwd)
declare root=$(cd "$cwd" && cd ../../../ && pwd)
USAGE="
USAGE: $0 target
This script will convert the current version in target files to the specified 'target'
where target is one of:
major
minor
build
snapshot
EXAMPLES:
Update to new snapshot (1.0.0 -> 1.0.1-SNAPSHOT):
$0 snapshot
Update build version (1.0.0 -> 1.0.1)
$0 build
Update minor version (1.2.3 -> 1.3.0)
$0 minor
Update major version (1.2.3 -> 2.0.0)
$0 major
"
version=$(ruby -r rexml/document -e 'include REXML;
p XPath.first(Document.new($stdin), "/project/version/text()")' < ${cwd}/../../../pom.xml | tr -d '"')
if [[ -n "$1" ]]; then
case $1 in
--help|-h)
echo -e "$USAGE" >&2
exit 1
;;
major|minor|build|snapshot)
inc="$1"
;;
*)
echo "Invalid target.Must be one of: major minor build or snapshot" >&2
exit 1
;;
esac
else
inc="snapshot"
fi
echo "Release preparation: Moving from $version to next $inc version."
# These files should wrap target version replacement blocks with <!-- RELEASE_VERSION --> and <!-- /RELEASE_VERSION -->
# We can include xml and md files here.
declare -a xml_files=(
"${root}/modules/openapi-generator-cli/pom.xml"
"${root}/modules/openapi-generator-gradle-plugin/pom.xml"
"${root}/modules/openapi-generator-core/pom.xml"
"${root}/modules/openapi-generator-maven-plugin/pom.xml"
"${root}/modules/openapi-generator-online/pom.xml"
"${root}/modules/openapi-generator/pom.xml"
"${root}/modules/openapi-generator-maven-plugin/examples/multi-module/java-client/pom.xml"
"${root}/modules/openapi-generator-maven-plugin/examples/java-client.xml"
"${root}/modules/openapi-generator-maven-plugin/examples/non-java-invalid-spec.xml"
"${root}/modules/openapi-generator-maven-plugin/examples/non-java.xml"
"${root}/samples/meta-codegen/lib/pom.xml"
"${root}/pom.xml"
)
# These files should wrap target version replacement blocks with # RELEASE_VERSION and # /RELEASE_VERSION
declare -a properties_files=(
"${root}/modules/openapi-generator-gradle-plugin/gradle.properties"
"${root}/modules/openapi-generator-gradle-plugin/samples/local-spec/gradle.properties"
)
${cwd}/bump.sh -f ${version} -i ${inc} ${xml_files[@]}
${cwd}/bump.sh -f ${version} -t ${inc} -s '# RELEASE_VERSION' -e '# \/RELEASE_VERSION' ${properties_files[@]}

View File

@ -0,0 +1,115 @@
#!/usr/bin/env bash
#
# This script is used to update reference files to the "next" version.
#
# usage: ./bin/utils/release_version_update.sh <from> <to>
# example: ./bin/utils/release_version_update.sh 3.0.1 3.0.2
#
# 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.
#
declare cwd=$(cd $(dirname "${BASH_SOURCE}") && pwd)
declare root=$(cd "$cwd" && cd ../../../ && pwd)
USAGE="
USAGE: $0 version target
This script will convert the specified version in DOC target files to the 'target'
where target is one of:
major
minor
build
or an explicitly defined version number.
NOTE:
Files prepped by this script should never target SNAPSHOT, as the docs should refer to release artifacts.
If intending to update to/from snapshots, please add target files to release_version_update.sh instead.
EXAMPLES:
Update build version (1.0.0 -> 1.0.1)
$0 1.0.0 build
Update minor version (1.2.3 -> 1.3.0)
$0 1.2.3 minor
Update major version (1.2.3 -> 2.0.0)
$0 1.2.3 major
"
declare version=$(ruby -r rexml/document -e 'include REXML;
p XPath.first(Document.new($stdin), "/project/version/text()")' < ${cwd}/../../../pom.xml | tr -d '"')
declare target="${2:-build}"
declare inc=""
declare next_version=""
declare ags=""
if [[ -z "$1" ]]; then
echo "Missing argument." >&2
echo -e "$USAGE" >&2
exit 1
fi
# Get version number we're changing
case $1 in
--help|-h)
echo -e "$USAGE" >&2
exit 1
;;
*)
version="$1"
;;
esac
# Get the target…
case ${target} in
major|minor|build)
inc="$target"
;;
snapshot)
echo -e "Files prepped by this script should never target SNAPSHOT, as the docs should refer to release artifacts.
If intending to update to/from snapshots, please add target files to release_version_update.sh instead.
" >&2
exit 1
;;
*)
next_version="$target"
;;
esac
ags="-f ${version}"
if [[ -n "${next_version}" ]];then
echo "Release preparation: Moving from $version to ${next_version}."
ags="$ags -t ${next_version}"
else
echo "Release preparation: Moving from $version to next $inc version."
ags="$ags -i ${inc}"
fi
declare -a xml_files=(
"${root}/modules/openapi-generator-maven-plugin/README.md"
"${root}/modules/openapi-generator-gradle-plugin/samples/local-spec/README.md"
"${root}/README.md"
)
declare -a commented_files=(
"${root}/modules/openapi-generator-gradle-plugin/README.adoc"
)
${cwd}/bump.sh ${ags} ${xml_files[@]}
${cwd}/bump.sh ${ags} -s '# RELEASE_VERSION' -e '# \/RELEASE_VERSION' ${commented_files[@]}

View File

@ -0,0 +1,17 @@
This is a test simple:
<!-- RELEASE_VERSION -->3.0.1<!-- /RELEASE_VERSION -->
Testing with other data:
<!-- RELEASE_VERSION -->
Version 1.2.3
<!-- /RELEASE_VERSION -->
Testing with -SNAPSHOT data:
<!-- RELEASE_VERSION -->
Version 2.3.4-SNAPSHOT
<!-- /RELEASE_VERSION -->
Testing with a value not to be replaced:
<!-- RELEASE_VERSION -->
Version 3.2.2
<!-- /RELEASE_VERSION -->

View File

@ -0,0 +1,17 @@
This is a test simple:
<!-- RELEASE_VERSION -->3.0.1<!-- /RELEASE_VERSION -->
Testing with other data:
<!-- RELEASE_VERSION -->
Version 1.2.3
<!-- /RELEASE_VERSION -->
Testing with -SNAPSHOT data:
<!-- RELEASE_VERSION -->
Version 2.3.4-SNAPSHOT
<!-- /RELEASE_VERSION -->
Testing with a value not to be replaced:
<!-- RELEASE_VERSION -->
Version 3.2.2
<!-- /RELEASE_VERSION -->

View File

@ -40,7 +40,8 @@ end
def check_openapi_generator_online_docker def check_openapi_generator_online_docker
print "Checking openapi-generator-online docker ... " print "Checking openapi-generator-online docker ... "
url = "https://hub.docker.com/r/openapitools/openapi-generator-online/tags/" url = "https://hub.docker.com/v2/repositories/openapitools/openapi-generator-online/tags/?page_size=25&page=1"
docker_tag = "v#{$version}" docker_tag = "v#{$version}"
open(url) do |f| open(url) do |f|
content = f.read content = f.read
@ -56,7 +57,7 @@ end
def check_openapi_generator_cli_docker def check_openapi_generator_cli_docker
print "Checking openapi-generator-cli docker ... " print "Checking openapi-generator-cli docker ... "
url = "https://hub.docker.com/r/openapitools/openapi-generator-cli/tags/" url = "https://hub.docker.com/v2/repositories/openapitools/openapi-generator-cli/tags/?page_size=25&page=1"
docker_tag = "v#{$version}" docker_tag = "v#{$version}"
open(url) do |f| open(url) do |f|
content = f.read content = f.read
@ -202,6 +203,8 @@ $version = ARGV[0]
puts "Running checkout on OpenAPI Generator release #{$version}" puts "Running checkout on OpenAPI Generator release #{$version}"
check_openapi_generator_online_docker
check_openapi_generator_cli_docker
check_npmjs check_npmjs
check_homebrew check_homebrew
check_openapi_generator_jar check_openapi_generator_jar
@ -211,5 +214,3 @@ check_openapi_generator_gradle_plugin_jar
check_openapi_generator_online_jar check_openapi_generator_online_jar
check_openapi_generator_project_pom check_openapi_generator_project_pom
check_readme check_readme
check_openapi_generator_online_docker
check_openapi_generator_cli_docker

View File

@ -1,62 +0,0 @@
#!/bin/bash
#
# usage: ./bin/utils/release_version_update.sh 3.0.1-SNAPSHOT 3.0.1
#
# 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.
#
if [[ "$1" != "" ]]; then
FROM="$1"
else
echo "Missing argument. Usage e.g.: ./bin/utils/release_version_update.sh 3.0.1-SNAPSHOT 3.0.1"
exit 1;
fi
if [[ "$2" != "" ]]; then
TO="$2"
else
echo "Missing argument. Usage e.g.: ./bin/utils/release_version_update.sh 3.0.1-SNAPSHOT 3.0.1"
exit 1;
fi
echo "Release preparation: replacing $FROM with $TO in different files"
# This script assumes the files defined here have a version surrounded by angle brackets within an xml node.
# For example, >4.0.0< becomes >4.0.1-SNAPSHOT<.
# Verify the sed command below against a file before adding here.
declare -a files=("modules/openapi-generator-cli/pom.xml"
"modules/openapi-generator-gradle-plugin/pom.xml"
"modules/openapi-generator-core/pom.xml"
"modules/openapi-generator-maven-plugin/pom.xml"
"modules/openapi-generator-online/pom.xml"
"modules/openapi-generator/pom.xml"
"samples/meta-codegen/lib/pom.xml"
"pom.xml")
sedi () {
# Cross-platform version of sed -i that works both on Mac and Linux
sed --version >/dev/null 2>&1 && sed -i -e "$@" || sed -i "" "$@"
}
for filename in "${files[@]}"; do
# e.g. sed -i '' "s/3.0.1-SNAPSHOT/3.0.1/g" CI/pom.xml.bash
#echo "Running command: sed -i '' "s/$FROM/$TO/g" $filename"
if sedi "s/>$FROM</>$TO</g" $filename; then
echo "Updated $filename successfully!"
else
echo "ERROR: Failed to update $filename with the following command"
echo "sed -i '' \"s/$FROM/$TO/g\" $filename"
fi
done

View File

@ -41,7 +41,6 @@ declare -a files=("modules/openapi-generator-maven-plugin/README.md"
"modules/openapi-generator-gradle-plugin/README.adoc" "modules/openapi-generator-gradle-plugin/README.adoc"
"modules/openapi-generator-gradle-plugin/gradle.properties" "modules/openapi-generator-gradle-plugin/gradle.properties"
"modules/openapi-generator-gradle-plugin/samples/local-spec/gradle.properties" "modules/openapi-generator-gradle-plugin/samples/local-spec/gradle.properties"
"modules/openapi-generator-gradle-plugin/samples/local-spec/build.gradle"
"modules/openapi-generator-gradle-plugin/samples/local-spec/README.md" "modules/openapi-generator-gradle-plugin/samples/local-spec/README.md"
"README.md") "README.md")

View File

@ -5,6 +5,6 @@ If Not Exist %executable% (
) )
REM set JAVA_OPTS=%JAVA_OPTS% -Xmx1024M -DloggerPath=conf/log4j.properties REM set JAVA_OPTS=%JAVA_OPTS% -Xmx1024M -DloggerPath=conf/log4j.properties
set ags=generate -i modules\openapi-generator\src\test\resources\2_0\petstore.yaml -g cpp-restsdk -o samples\client\petstore\cpp-restsdk set ags=generate -i modules\openapi-generator\src\test\resources\2_0\petstore.yaml -g cpp-restsdk -o samples\client\petstore\cpp-restsdk\client
java %JAVA_OPTS% -jar %executable% %ags% java %JAVA_OPTS% -jar %executable% %ags%

View File

@ -5,6 +5,6 @@ If Not Exist %executable% (
) )
REM set JAVA_OPTS=%JAVA_OPTS% -Xmx1024M -DloggerPath=conf/log4j.properties REM set JAVA_OPTS=%JAVA_OPTS% -Xmx1024M -DloggerPath=conf/log4j.properties
set ags=generate -i modules\openapi-generator\src\test\resources\2_0\petstore.yaml -g r -o samples\client\petstore\R set ags=generate -i modules\openapi-generator\src\test\resources\2_0\petstore.yaml -g r -o samples\client\petstore\R --additional-properties packageName=petstore
java %JAVA_OPTS% -jar %executable% %ags% java %JAVA_OPTS% -jar %executable% %ags%

View File

@ -91,7 +91,7 @@ The following generators are available:
- [jaxrs-spec](generators/jaxrs-spec.md) - [jaxrs-spec](generators/jaxrs-spec.md)
- [kotlin-server](generators/kotlin-server.md) - [kotlin-server](generators/kotlin-server.md)
- [kotlin-spring](generators/kotlin-spring.md) - [kotlin-spring](generators/kotlin-spring.md)
- [nodejs-server](generators/nodejs-server.md) - [nodejs-server-deprecated](generators/nodejs-server-deprecated.md) (deprecated)
- [php-laravel](generators/php-laravel.md) - [php-laravel](generators/php-laravel.md)
- [php-lumen](generators/php-lumen.md) - [php-lumen](generators/php-lumen.md)
- [php-silex](generators/php-silex.md) - [php-silex](generators/php-silex.md)

View File

@ -16,14 +16,19 @@ sidebar_label: aspnetcore
|packageVersion|C# package version.| |1.0.0| |packageVersion|C# package version.| |1.0.0|
|packageGuid|The GUID that will be associated with the C# project| |null| |packageGuid|The GUID that will be associated with the C# project| |null|
|sourceFolder|source folder for generated code| |src| |sourceFolder|source folder for generated code| |src|
|compatibilityVersion|ASP.Net Core CompatibilityVersion| |Version_2_1| |compatibilityVersion|ASP.Net Core CompatibilityVersion| |Version_2_2|
|aspnetCoreVersion|ASP.NET Core version: 2.2 (default), 2.1, 2.0 (deprecated)| |2.2| |aspnetCoreVersion|ASP.NET Core version: 3.0 (preview4 only), 2.2, 2.1, 2.0 (deprecated)| |2.2|
|swashbuckleVersion|Swashbucke version: 3.0.0, 4.0.0| |3.0.0|
|sortParamsByRequiredFlag|Sort method arguments to place required parameters before optional parameters.| |true| |sortParamsByRequiredFlag|Sort method arguments to place required parameters before optional parameters.| |true|
|useDateTimeOffset|Use DateTimeOffset to model date-time properties| |false| |useDateTimeOffset|Use DateTimeOffset to model date-time properties| |false|
|useCollection|Deserialize array types to Collection&lt;T&gt; instead of List&lt;T&gt;.| |false| |useCollection|Deserialize array types to Collection&lt;T&gt; instead of List&lt;T&gt;.| |false|
|returnICollection|Return ICollection&lt;T&gt; instead of the concrete type.| |false| |returnICollection|Return ICollection&lt;T&gt; instead of the concrete type.| |false|
|useSwashbuckle|Uses the Swashbuckle.AspNetCore NuGet package for documentation.| |true| |useSwashbuckle|Uses the Swashbuckle.AspNetCore NuGet package for documentation.| |true|
|isLibrary|Is the build a library| |false| |isLibrary|Is the build a library| |false|
|useFrameworkReference|Use frameworkReference for ASP.NET Core 3.0+ and PackageReference ASP.NET Core 2.2 or earlier.| |false|
|useNewtonsoft|Uses the Newtonsoft JSON library.| |true|
|newtonsoftVersion|Version for Microsoft.AspNetCore.Mvc.NewtonsoftJson for ASP.NET Core 3.0+| |3.0.0-preview5-19227-01|
|useDefaultRouting|Use default routing for the ASP.NET Core version. For 3.0 turn off default because it is not yet supported.| |true|
|classModifier|Class Modifier can be empty, abstract| || |classModifier|Class Modifier can be empty, abstract| ||
|operationModifier|Operation Modifier can be virtual, abstract or partial| |virtual| |operationModifier|Operation Modifier can be virtual, abstract or partial| |virtual|
|buildTarget|Target to build an application or library| |program| |buildTarget|Target to build an application or library| |program|

View File

@ -10,6 +10,7 @@ sidebar_label: go
|packageName|Go package name (convention: lowercase).| |openapi| |packageName|Go package name (convention: lowercase).| |openapi|
|packageVersion|Go package version.| |1.0.0| |packageVersion|Go package version.| |1.0.0|
|hideGenerationTimestamp|Hides the generation timestamp when files are generated.| |true| |hideGenerationTimestamp|Hides the generation timestamp when files are generated.| |true|
|isGoSubmodule|whether the generated Go module is a submodule| |false|
|withGoCodegenComment|whether to include Go codegen comment to disable Go Lint and collapse by default GitHub in PRs and diffs| |false| |withGoCodegenComment|whether to include Go codegen comment to disable Go Lint and collapse by default GitHub in PRs and diffs| |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| |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|
|prependFormOrBodyParameters|Add form or body parameters to the beginning of the parameter list.| |false| |prependFormOrBodyParameters|Add form or body parameters to the beginning of the parameter list.| |false|

View File

@ -54,4 +54,5 @@ sidebar_label: java
|useRuntimeException|Use RuntimeException instead of Exception| |false| |useRuntimeException|Use RuntimeException instead of Exception| |false|
|feignVersion|Version of OpenFeign: '10.x', '9.x' (default)| |false| |feignVersion|Version of OpenFeign: '10.x', '9.x' (default)| |false|
|useReflectionEqualsHashCode|Use org.apache.commons.lang3.builder for equals and hashCode in the models. WARNING: This will fail under a security manager, unless the appropriate permissions are set up correctly and also there's potential performance impact.| |false| |useReflectionEqualsHashCode|Use org.apache.commons.lang3.builder for equals and hashCode in the models. WARNING: This will fail under a security manager, unless the appropriate permissions are set up correctly and also there's potential performance impact.| |false|
|caseInsensitiveResponseHeaders|Make API response's headers case-insensitive. Available on okhttp-gson, jersey2 libraries| |false|
|library|library template (sub-template) to use|<dl><dt>**jersey1**</dt><dd>HTTP client: Jersey client 1.19.x. JSON processing: Jackson 2.8.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.8.x</dd><dt>**feign**</dt><dd>HTTP client: OpenFeign 9.x or 10.x. JSON processing: Jackson 2.8.x. To enable OpenFeign 10.x, set the 'feignVersion' option to '10.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>**retrofit**</dt><dd>HTTP client: OkHttp 2.x. JSON processing: Gson 2.x (Retrofit 1.9.0). IMPORTANT NOTE: retrofit1.x is no longer actively maintained so please upgrade to 'retrofit2' instead.</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]=true'. (RxJava 1.x or 2.x)</dd><dt>**resttemplate**</dt><dd>HTTP client: Spring RestTemplate 4.x. JSON processing: Jackson 2.8.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.8.x</dd><dt>**vertx**</dt><dd>HTTP client: VertX client 3.x. JSON processing: Jackson 2.8.x</dd><dt>**google-api-client**</dt><dd>HTTP client: Google API client 1.x. JSON processing: Jackson 2.8.x</dd><dt>**rest-assured**</dt><dd>HTTP client: rest-assured : 3.x. JSON processing: Gson 2.x. Only for Java8</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.8.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.8.x</dd><dt>**feign**</dt><dd>HTTP client: OpenFeign 9.x or 10.x. JSON processing: Jackson 2.8.x. To enable OpenFeign 10.x, set the 'feignVersion' option to '10.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>**retrofit**</dt><dd>HTTP client: OkHttp 2.x. JSON processing: Gson 2.x (Retrofit 1.9.0). IMPORTANT NOTE: retrofit1.x is no longer actively maintained so please upgrade to 'retrofit2' instead.</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]=true'. (RxJava 1.x or 2.x)</dd><dt>**resttemplate**</dt><dd>HTTP client: Spring RestTemplate 4.x. JSON processing: Jackson 2.8.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.8.x</dd><dt>**vertx**</dt><dd>HTTP client: VertX client 3.x. JSON processing: Jackson 2.8.x</dd><dt>**google-api-client**</dt><dd>HTTP client: Google API client 1.x. JSON processing: Jackson 2.8.x</dd><dt>**rest-assured**</dt><dd>HTTP client: rest-assured : 3.x. JSON processing: Gson 2.x. Only for Java8</dd><dl>|okhttp-gson|

View File

@ -20,10 +20,11 @@ sidebar_label: kotlin-spring
|serverPort|configuration the port in which the sever is to run on| |8080| |serverPort|configuration the port in which the sever is to run on| |8080|
|modelPackage|model package for generated code| |org.openapitools.model| |modelPackage|model package for generated code| |org.openapitools.model|
|apiPackage|api package for generated code| |org.openapitools.api| |apiPackage|api package for generated code| |org.openapitools.api|
|exceptionHandler|generate default global exception handlers| |true| |exceptionHandler|generate default global exception handlers (not compatible with reactive. enabling reactive will disable exceptionHandler )| |true|
|gradleBuildFile|generate a gradle build file using the Kotlin DSL| |true| |gradleBuildFile|generate a gradle build file using the Kotlin DSL| |true|
|swaggerAnnotations|generate swagger annotations to go alongside controllers and models| |false| |swaggerAnnotations|generate swagger annotations to go alongside controllers and models| |false|
|serviceInterface|generate service interfaces to go alongside controllers. In most cases this option would be used to update an existing project, so not to override implementations. Useful to help facilitate the generation gap pattern| |false| |serviceInterface|generate service interfaces to go alongside controllers. In most cases this option would be used to update an existing project, so not to override implementations. Useful to help facilitate the generation gap pattern| |false|
|serviceImplementation|generate stub service implementations that extends service interfaces. If this is set to true service interfaces will also be generated| |false| |serviceImplementation|generate stub service implementations that extends service interfaces. If this is set to true service interfaces will also be generated| |false|
|useBeanValidation|Use BeanValidation API annotations to validate data types| |true| |useBeanValidation|Use BeanValidation API annotations to validate data types| |true|
|reactive|use coroutines for reactive behavior| |false|
|library|library template (sub-template)|<dl><dt>**spring-boot**</dt><dd>Spring-boot Server application.</dd><dl>|spring-boot| |library|library template (sub-template)|<dl><dt>**spring-boot**</dt><dd>Spring-boot Server application.</dd><dl>|spring-boot|

View File

@ -0,0 +1,16 @@
---
id: generator-opts-server-nodejs-server-deprecated
title: Config Options for nodejs-server-deprecated
sidebar_label: nodejs-server-deprecated
---
| Option | Description | Values | Default |
| ------ | ----------- | ------ | ------- |
|sortParamsByRequiredFlag|Sort method arguments to place required parameters before optional parameters.| |true|
|ensureUniqueParams|Whether to ensure parameter names are unique in an operation (rename parameters that are not).| |true|
|allowUnicodeIdentifiers|boolean, toggles whether unicode identifiers are allowed in names or not, default is false| |false|
|prependFormOrBodyParameters|Add form or body parameters to the beginning of the parameter list.| |false|
|googleCloudFunctions|When specified, it will generate the code which runs within Google Cloud Functions instead of standalone Node.JS server. See https://cloud.google.com/functions/docs/quickstart for the details of how to deploy the generated code.| |false|
|exportedName|When the generated code will be deployed to Google Cloud Functions, this option can be used to update the name of the exported function. By default, it refers to the basePath. This does not affect normal standalone nodejs server code.| |null|
|serverPort|TCP port to listen on.| |null|

View File

@ -35,7 +35,7 @@ sidebar_label: spring
|hideGenerationTimestamp|Hides the generation timestamp when files are generated.| |false| |hideGenerationTimestamp|Hides the generation timestamp when files are generated.| |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| |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|
|dateLibrary|Option. Date library to use|<dl><dt>**joda**</dt><dd>Joda (for legacy app only)</dd><dt>**legacy**</dt><dd>Legacy java.util.Date (if you really have a good reason not to use threetenbp</dd><dt>**java8-localdatetime**</dt><dd>Java 8 using LocalDateTime (for legacy app only)</dd><dt>**java8**</dt><dd>Java 8 native JSR310 (preferred for jdk 1.8+) - note: this also sets &quot;java8&quot; to true</dd><dt>**threetenbp**</dt><dd>Backport of JSR310 (preferred for jdk &lt; 1.8)</dd><dl>|threetenbp| |dateLibrary|Option. Date library to use|<dl><dt>**joda**</dt><dd>Joda (for legacy app only)</dd><dt>**legacy**</dt><dd>Legacy java.util.Date (if you really have a good reason not to use threetenbp</dd><dt>**java8-localdatetime**</dt><dd>Java 8 using LocalDateTime (for legacy app only)</dd><dt>**java8**</dt><dd>Java 8 native JSR310 (preferred for jdk 1.8+) - note: this also sets &quot;java8&quot; to true</dd><dt>**threetenbp**</dt><dd>Backport of JSR310 (preferred for jdk &lt; 1.8)</dd><dl>|threetenbp|
|java8|Option. Use Java8 classes instead of third party equivalents|<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>|false| |java8|Option. Use Java8 classes instead of third party equivalents|<dl><dt>**true**</dt><dd>Use Java 8 classes such as Base64. Use java8 default interface when a responseWrapper is used</dd><dt>**false**</dt><dd>Various third party libraries as needed</dd><dl>|false|
|disableHtmlEscaping|Disable HTML escaping of JSON strings when using gson (needed to avoid problems with byte[] fields)| |false| |disableHtmlEscaping|Disable HTML escaping of JSON strings when using gson (needed to avoid problems with byte[] fields)| |false|
|booleanGetterPrefix|Set booleanGetterPrefix| |get| |booleanGetterPrefix|Set booleanGetterPrefix| |get|
|parentGroupId|parent groupId in generated pom N.B. parentGroupId, parentArtifactId and parentVersion must all be specified for any of them to take effect| |null| |parentGroupId|parent groupId in generated pom N.B. parentGroupId, parentArtifactId and parentVersion must all be specified for any of them to take effect| |null|
@ -48,7 +48,6 @@ sidebar_label: spring
|interfaceOnly|Whether to generate only API interface stubs without the server files.| |false| |interfaceOnly|Whether to generate only API interface stubs without the server files.| |false|
|delegatePattern|Whether to generate the server files using the delegate pattern| |false| |delegatePattern|Whether to generate the server files using the delegate pattern| |false|
|singleContentTypes|Whether to select only one produces/consumes content-type by operation.| |false| |singleContentTypes|Whether to select only one produces/consumes content-type by operation.| |false|
|java8|use java8 default interface| |true|
|async|use async Callable controllers| |false| |async|use async Callable controllers| |false|
|reactive|wrap responses in Mono/Flux Reactor types (spring-boot only)| |false| |reactive|wrap responses in Mono/Flux Reactor types (spring-boot only)| |false|
|responseWrapper|wrap the responses in given type (Future,Callable,CompletableFuture,ListenableFuture,DeferredResult,HystrixCommand,RxObservable,RxSingle or fully qualified type)| |null| |responseWrapper|wrap the responses in given type (Future,Callable,CompletableFuture,ListenableFuture,DeferredResult,HystrixCommand,RxObservable,RxSingle or fully qualified type)| |null|

View File

@ -3,7 +3,9 @@
<parent> <parent>
<groupId>org.openapitools</groupId> <groupId>org.openapitools</groupId>
<artifactId>openapi-generator-project</artifactId> <artifactId>openapi-generator-project</artifactId>
<!-- RELEASE_VERSION -->
<version>4.1.0-SNAPSHOT</version> <version>4.1.0-SNAPSHOT</version>
<!-- /RELEASE_VERSION -->
<relativePath>../..</relativePath> <relativePath>../..</relativePath>
</parent> </parent>
<modelVersion>4.0.0</modelVersion> <modelVersion>4.0.0</modelVersion>

View File

@ -5,7 +5,9 @@
<parent> <parent>
<artifactId>openapi-generator-project</artifactId> <artifactId>openapi-generator-project</artifactId>
<groupId>org.openapitools</groupId> <groupId>org.openapitools</groupId>
<!-- RELEASE_VERSION -->
<version>4.1.0-SNAPSHOT</version> <version>4.1.0-SNAPSHOT</version>
<!-- /RELEASE_VERSION -->
<relativePath>../..</relativePath> <relativePath>../..</relativePath>
</parent> </parent>
<modelVersion>4.0.0</modelVersion> <modelVersion>4.0.0</modelVersion>
@ -25,6 +27,11 @@
<artifactId>slf4j-api</artifactId> <artifactId>slf4j-api</artifactId>
<version>${slf4j-version}</version> <version>${slf4j-version}</version>
</dependency> </dependency>
<dependency>
<groupId>org.testng</groupId>
<artifactId>testng</artifactId>
<scope>test</scope>
</dependency>
</dependencies> </dependencies>
<properties> <properties>

View File

@ -0,0 +1,61 @@
/*
* Copyright 2019 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.validation;
import java.util.List;
/**
* A generic implementation of a validator instance which simply applies rules to an input instance.
*
* @param <TInput> The type of object being evaluated.
*/
@SuppressWarnings({"WeakerAccess"})
public class GenericValidator<TInput> implements Validator<TInput> {
private List<ValidationRule> rules;
/**
* Constructs a new instance of {@link GenericValidator}.
*
* @param rules The rules to be evaluated during validation.
*/
public GenericValidator(List<ValidationRule> rules) {
this.rules = rules;
}
/**
* Validates input, resulting in a instance of {@link ValidationResult} which provides details on all validations performed (success, error, warning).
*
* @param input The object instance to be validated.
*
* @return A {@link ValidationResult} which details the success, error, and warning validation results.
*/
@Override
public ValidationResult validate(TInput input) {
ValidationResult result = new ValidationResult();
if (rules != null) {
rules.forEach(it -> {
boolean passes = it.evaluate(input);
if (passes) {
result.addResult(Validated.valid(it));
} else {
result.addResult(Validated.invalid(it, it.getFailureMessage()));
}
});
}
return result;
}
}

View File

@ -0,0 +1,57 @@
/*
* Copyright 2019 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.validation;
/**
* Represents a {@link Validated} state which is "Invalid" to some degree of {@link Severity}.
*/
@SuppressWarnings({"WeakerAccess"})
public final class Invalid extends Validated {
private String message;
private ValidationRule rule;
/**
* Constructs a new {@link Invalid} instance.
*
* @param rule The rule which was evaluated and resulted in this state.
* @param message The message to be displayed for this invalid state.
*/
Invalid(ValidationRule rule, String message) {
this.rule = rule;
this.message = message;
}
@Override
String getMessage() {
return message;
}
@Override
ValidationRule getRule() {
return rule;
}
/**
* Get details about the severity of this invalid state.
* For instance, is this an {@link Severity#ERROR} or simply a {@link Severity#WARNING}.
*
* @return The {@link Severity} enum detailing this state's severity.
*/
public Severity getSeverity() {
return rule.getSeverity();
}
}

View File

@ -0,0 +1,33 @@
/*
* Copyright 2019 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.validation;
/**
* Defines different levels of severity to be used during validation.
*/
public enum Severity {
/**
* Lower severity indicating that the target state may be unpredictable, no longer supported, or known to have issues.
* Marking a type with this value should not result in application exceptions under normal operating circumstances.
*/
WARNING,
/**
* Higher severity indicating that the target state is not supported, or is known to cause problems with the application.
* Marking a type with this value should result in an application exception or error exit code under normal operating circumstances.
*/
ERROR
}

View File

@ -0,0 +1,53 @@
/*
* Copyright 2019 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.validation;
/**
* Represents a {@link Validated} state which is "valid" according to the defined rule.
*/
public final class Valid extends Validated {
private ValidationRule rule;
/**
* Defines whether or not the validation resulted in a "valid" condition.
*
* @return <code>true</code> if the instance passed validation of the rule returned by {@link Validated#getRule()}.
*/
@Override
boolean isValid() {
return true;
}
/**
* Constructs a new {@link Valid} instance.
*
* @param rule The rule which was evaluated and resulted in this state.
*/
Valid(ValidationRule rule) {
this.rule = rule;
}
@Override
public String getMessage() {
return null;
}
@Override
public ValidationRule getRule() {
return rule;
}
}

View File

@ -0,0 +1,68 @@
/*
* Copyright 2019 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.validation;
/**
* Provides details about the state of a completed validation.
*/
public abstract class Validated {
/**
* Defines whether or not the validation resulted in a "valid" condition.
*
* @return <code>true</code> if the instance passed validation of the rule returned by {@link Validated#getRule()}.
*/
boolean isValid() {
return false;
}
/**
* Gets the rule which was evaluated and resulted in this state.
*
* @return The instance of {@link ValidationRule} which was evaluated.
*/
abstract ValidationRule getRule();
/**
* Gets the message with details about this validated state.
*
* @return A string intended to be displayed to a user.
*/
abstract String getMessage();
/**
* Creates an instance of an {@link Invalid} validation state.
*
* @param rule The rule which was evaluated.
* @param message The message to display to a user.
*
* @return A {@link Validated} instance representing an invalid state according to the rule.
*/
public static Validated invalid(ValidationRule rule, String message) {
return new Invalid(rule, message);
}
/**
* Creates an instance of an {@link Valid} validation state.
*
* @param rule The rule which was evaluated.
*
* @return A {@link Validated} instance representing a valid state according to the rule.
*/
public static Validated valid(ValidationRule rule) {
return new Valid(rule);
}
}

View File

@ -0,0 +1,104 @@
/*
* Copyright 2019 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.validation;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;
/**
* Encapsulates details about the result of a validation test.
*/
@SuppressWarnings("WeakerAccess")
public final class ValidationResult {
private final List<Validated> validations;
/**
* Constructs a new {@link ValidationResult} instance, backed by the provided validations (useful for testing).
*
* @param validations A pre-defined set of validations to begin with.
*/
private ValidationResult(List<Validated> validations) {
this.validations = Collections.synchronizedList(validations);
}
/**
* Constructs a new {@link ValidationResult} instance.
*/
public ValidationResult() {
this(new ArrayList<>());
}
/**
* Gets all the validated states resulting from the evaluation. This includes all {@link Valid} and {@link Invalid} instances.
*
* @return All validated results.
*/
public List<Validated> getAll() {
return validations;
}
/**
* Gets a filtered list of {@link Valid} states.
*
* @return A list containing only {@link Valid} states.
*/
public List<Valid> getValid(){
return validations.stream().filter(Validated::isValid).map(it -> (Valid)it).collect(Collectors.toList());
}
/**
* Gets a filters list of {@link Invalid} states with the level of {@link Severity#ERROR}
*
* @return A list of all validation errors.
*/
public List<Invalid> getErrors(){
return validations.stream()
.filter(it -> !it.isValid())
.map(it -> (Invalid)it)
.filter(it -> it.getSeverity().equals(Severity.ERROR))
.collect(Collectors.toList());
}
/**
* Gets a filtered list of {@link Invalid} states with the level of {@link Severity#WARNING}
*
* @return A list of all validation warnings.
*/
public List<Invalid> getWarnings(){
return validations.stream()
.filter(it -> !it.isValid())
.map(it -> (Invalid)it)
.filter(it -> it.getSeverity().equals(Severity.WARNING))
.collect(Collectors.toList());
}
/**
* Adds a validation state to the final results.
*
* @param validated The {@link Valid} or {@link Invalid} instance to add to validations.
*/
public void addResult(Validated validated) {
synchronized (validations) {
ValidationRule rule = validated.getRule();
if (rule != null && !rule.equals(ValidationRule.empty())) {
validations.add(validated);
}
}
}
}

View File

@ -0,0 +1,152 @@
/*
* Copyright 2019 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.validation;
import java.util.function.Function;
/**
* Defines a rule to be evaluated against some target object.
*/
@SuppressWarnings("WeakerAccess")
public class ValidationRule {
private Severity severity;
private String description;
private String failureMessage;
private Function<Object, Boolean> test;
/**
* Constructs a new instance of {@link ValidationRule}
*
* @param severity The declared severity if this validation rule fails.
* @param description A description to help differentiate this rule from others (not intended to be user-facing).
* @param failureMessage The message to be displayed in the event of a test failure (intended to be user-facing).
* @param test The test condition to be applied as a part of this rule, when this function returns <code>true</code>,
* the evaluated instance will be considered "valid" according to this rule.
*/
ValidationRule(Severity severity, String description, String failureMessage, Function<Object, Boolean> test) {
this.severity = severity;
this.description = description;
this.failureMessage = failureMessage;
this.test = test;
}
/**
* Gets the message to be displayed in the event of a test failure (intended to be user-facing).
*
* @return A string message
*/
public String getFailureMessage() {
return failureMessage;
}
/**
* Evalute an instance of an object against this rule.
*
* @param input The instance to be evaluated.
*
* @return <code>true</code> if the object state is valid according to this rule, otherwise <code>false</code>.
*/
public boolean evaluate(Object input) {
return test.apply(input);
}
/**
* Get the level of severity which this rule considers a failure in evaluation. For example, if this is {@link Severity#WARNING} and
* a call to {@link ValidationRule#evaluate(Object)} returns <code>false</code>, a user should not expect an error to be thrown under
* normal operation.
*
* @return An enum defining how severe a failure to evaluate this rule should be considered by the caller.
*/
public Severity getSeverity() {
return severity;
}
/**
* Gets a description to help differentiate this rule from others (not intended to be user-facing).
*
* @return A string description.
*/
public String getDescription() {
return description;
}
/**
* Constructs an empty rule (useful for testing).
*
* @return An "empty" rule.
*/
static ValidationRule empty() {
return new ValidationRule(Severity.ERROR, "empty", "failure message", (i) -> false);
}
/**
* Create an instance of a {@link ValidationRule}
*
* @param severity The declared severity if this validation rule fails.
* @param description A description to help differentiate this rule from others (not intended to be user-facing).
* @param failureMessage The message to be displayed in the event of a test failure (intended to be user-facing).
* @param fn The test condition to be applied as a part of this rule, when this function returns <code>true</code>,
* the evaluated instance will be considered "valid" according to this rule.
* @param <T> The type of the object being evaluated.
*
* @return A new instance of a {@link ValidationRule}
*/
@SuppressWarnings("unchecked")
public static <T> ValidationRule create(Severity severity, String description, String failureMessage, Function<T, Boolean> fn) {
return new ValidationRule(severity, description, failureMessage, (Function<Object, Boolean>) fn);
}
/**
* Create an instance of a {@link ValidationRule} which should result in an error should the evaluate of this rule fail.
*
* @param failureMessage The message to be displayed in the event of a test failure (intended to be user-facing).
* @param fn The test condition to be applied as a part of this rule, when this function returns <code>true</code>,
* the evaluated instance will be considered "valid" according to this rule.
* @param <T> The type of the object being evaluated.
*
* @return A new instance of a {@link ValidationRule}
*/
@SuppressWarnings("unchecked")
public static <T> ValidationRule error(String failureMessage, Function<T, Boolean> fn) {
return new ValidationRule(Severity.ERROR, null, failureMessage, (Function<Object, Boolean>) fn);
}
/**
* Create an instance of a {@link ValidationRule} which should result in a warning should the evaluate of this rule fail.
*
* @param description A description to help differentiate this rule from others (not intended to be user-facing).
* @param failureMessage The message to be displayed in the event of a test failure (intended to be user-facing).
* @param fn The test condition to be applied as a part of this rule, when this function returns <code>true</code>,
* the evaluated instance will be considered "valid" according to this rule.
* @param <T> The type of the object being evaluated.
*
* @return A new instance of a {@link ValidationRule}
*/
@SuppressWarnings("unchecked")
public static <T> ValidationRule warn(String description, String failureMessage, Function<T, Boolean> fn) {
return new ValidationRule(Severity.WARNING, description, failureMessage, (Function<Object, Boolean>) fn);
}
@Override
public String toString() {
return "ValidationRule{" +
"severity=" + severity +
", description='" + description + '\'' +
", failureMessage='" + failureMessage + '\'' +
'}';
}
}

View File

@ -0,0 +1,34 @@
/*
* Copyright 2019 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.validation;
/**
* Defines a contract allowing some input to be validated.
*
* @param <TInput> The type of the input object.
*/
@FunctionalInterface
public interface Validator<TInput> {
/**
* Validates input, resulting in a instance of {@link ValidationResult} which provides details on all validations performed (success, error, warning).
*
* @param input The object instance to be validated.
*
* @return A {@link ValidationResult} which details the success, error, and warning validation results.
*/
ValidationResult validate(TInput input);
}

View File

@ -0,0 +1,149 @@
/*
* Copyright 2019 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.validation;
import org.testng.annotations.Test;
import static org.testng.Assert.*;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;
public class GenericValidatorTest {
class Person {
private int age;
private String name;
Person(String name, int age) {
this.age = age;
this.name = name;
}
}
private static boolean isValidAge(Person person) {
return person.age > 0;
}
private static boolean isAdult(Person person) {
return person.age > 18;
}
private static boolean isNameSet(Person person) {
return person.name != null && person.name.length() > 0;
}
private static boolean isNameValid(Person person) {
String pattern = "^[A-Z][a-z]*$";
return person.name.matches(pattern);
}
private static boolean isNameNormalLength(Person person) {
return person.name.length() < 10;
}
private List<ValidationRule> validationRules = Arrays.asList(
ValidationRule.error("Age must be positive and more than zero", GenericValidatorTest::isValidAge),
ValidationRule.error("Only adults (18 years old and older)", GenericValidatorTest::isAdult),
ValidationRule.error("Name isn't set!", GenericValidatorTest::isNameSet),
ValidationRule.error("Name isn't formatted correct", GenericValidatorTest::isNameValid),
ValidationRule.warn("Name too long?", "Name may be too long.", GenericValidatorTest::isNameNormalLength)
);
@Test
public void testGenericValidatorSuccesses(){
Person person = new Person("Jim", 23);
GenericValidator<Person> validator = new GenericValidator<>(validationRules);
ValidationResult result = validator.validate(person);
List<Validated> validated = result.getAll();
List<Valid> valid = result.getValid();
List<Invalid> invalid = result.getErrors();
assertEquals(validated.size(), 5, "Expected 5 validations to run.");
assertEquals(valid.size(), 5, "Expected all validations to succeed");
assertEquals(invalid.size(), 0, "Expected zero validations to fail.");
}
@Test
public void testGenericValidatorSingleConditionFails(){
Person person = new Person("Jim", 3);
GenericValidator<Person> validator = new GenericValidator<>(validationRules);
ValidationResult result = validator.validate(person);
List<Validated> validated = result.getAll();
List<Valid> valid = result.getValid();
List<Invalid> errors = result.getErrors();
List<Invalid> warnings = result.getWarnings();
assertEquals(validated.size(), 5, "Expected 5 validations to run.");
assertEquals(valid.size(), 4, "Expected 4 validations to succeed");
assertEquals(errors.size(), 1, "Expected 1 validation to fail.");
assertEquals(warnings.size(), 0, "Expected no warnings to be triggered.");
Invalid failed = errors.get(0);
assertEquals(failed.getMessage(), "Only adults (18 years old and older)");
}
@Test
public void testGenericValidatorMultipleConditionsFail(){
Person person = new Person("asdf", 3);
GenericValidator<Person> validator = new GenericValidator<>(validationRules);
ValidationResult result = validator.validate(person);
List<Validated> validated = result.getAll();
List<Valid> valid = result.getValid();
List<Invalid> errors = result.getErrors();
List<Invalid> warnings = result.getWarnings();
assertEquals(validated.size(), 5, "Expected 5 validations to run.");
assertEquals(valid.size(), 3, "Expected 3 validations to succeed");
assertEquals(errors.size(), 2, "Expected 2 validations to fail.");
assertEquals(warnings.size(), 0, "Expected no warnings to be triggered.");
Optional<Invalid> nameValidation = errors.stream().filter(it -> it.getMessage().contains("formatted")).findFirst();
Optional<Invalid> ageValidation = errors.stream().filter(it -> it.getMessage().contains("adults")).findFirst();
assertTrue(nameValidation.isPresent(), "Expected validation on name formatting to fail.");
assertTrue(ageValidation.isPresent(), "Expected validation on age requirements to fail.");
assertEquals(nameValidation.get().getMessage(), "Name isn't formatted correct");
assertEquals(ageValidation.get().getMessage(), "Only adults (18 years old and older)");
}
@Test
public void testGenericValidatorErrorsAndWarnings(){
Person person = new Person("0123456789asdfghjkl", 3);
GenericValidator<Person> validator = new GenericValidator<>(validationRules);
ValidationResult result = validator.validate(person);
List<Validated> validated = result.getAll();
List<Valid> valid = result.getValid();
List<Invalid> errors = result.getErrors();
List<Invalid> warnings = result.getWarnings();
assertEquals(validated.size(), 5, "Expected 5 validations to run.");
assertEquals(valid.size(), 2, "Expected 2 validations to succeed");
assertEquals(errors.size(), 2, "Expected 2 validations to fail.");
assertEquals(warnings.size(), 1, "Expected 1 warning to be triggered.");
Optional<Invalid> nameValidation = errors.stream().filter(it -> it.getMessage().contains("formatted")).findFirst();
Optional<Invalid> ageValidation = errors.stream().filter(it -> it.getMessage().contains("adults")).findFirst();
Invalid nameLengthWarning = warnings.get(0);
assertTrue(nameValidation.isPresent(), "Expected validation on name formatting to fail.");
assertTrue(ageValidation.isPresent(), "Expected validation on age requirements to fail.");
assertEquals(nameValidation.get().getMessage(), "Name isn't formatted correct");
assertEquals(ageValidation.get().getMessage(), "Only adults (18 years old and older)");
assertEquals(nameLengthWarning.getMessage(), "Name may be too long.");
}
}

View File

@ -0,0 +1,35 @@
/*
* Copyright 2019 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.validation;
import org.testng.annotations.Test;
import static org.testng.Assert.*;
public class ValidatedTest {
@Test
public void isValidTrueForValidType(){
boolean isValid = Validated.valid(ValidationRule.empty()).isValid();
assertTrue(isValid);
}
@Test
public void isValidFalseForInvalidType(){
boolean isValid = Validated.invalid(ValidationRule.empty(), "test").isValid();
assertFalse(isValid);
}
}

View File

@ -0,0 +1,68 @@
/*
* Copyright 2019 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.validation;
import org.testng.annotations.Test;
import static org.testng.Assert.*;
public class ValidationRuleTest {
class Sample {
private String name;
public Sample(String name) {
this.name = name;
}
public String getName() {
return name;
}
}
private static boolean checkName(Sample input) {
return input.getName() != null && input.getName().length() > 7;
}
private static boolean checkPattern(Sample input) {
String pattern = "^[A-Z][a-z]*$";
return input.getName() != null && input.getName().matches(pattern);
}
@Test
public void createMethodUsingMethodReference(){
Sample nil = new Sample(null);
Sample six = new Sample("123456");
Sample seven = new Sample("1234567");
Sample eight = new Sample("12345678");
ValidationRule result = ValidationRule.error("test", ValidationRuleTest::checkName);
assertFalse(result.evaluate(nil));
assertFalse(result.evaluate(six));
assertFalse(result.evaluate(seven));
assertTrue(result.evaluate(eight));
}
@Test
public void createMethodUsingLambda(){
Sample nil = new Sample(null);
Sample lowercase = new Sample("jim");
Sample titlecase = new Sample("Jim");
ValidationRule result = ValidationRule.error("test", i -> checkPattern((Sample)i));
assertFalse(result.evaluate(nil));
assertFalse(result.evaluate(lowercase));
assertTrue(result.evaluate(titlecase));
}
}

View File

@ -40,25 +40,34 @@ compileJava.dependsOn tasks.openApiGenerate
== Plugin Setup == Plugin Setup
//# RELEASE_VERSION
[source,group]
----
plugins {
id "org.openapi.generator" version "4.0.3-SNAPSHOT"
}
----
Using https://docs.gradle.org/current/userguide/plugins.html#sec:old_plugin_application[legacy plugin application]:
[source,groovy] [source,groovy]
---- ----
buildscript { buildscript {
repositories { repositories {
mavenLocal() mavenLocal()
mavenCentral() mavenCentral()
// or, via Gradle Plugin Portal:
// url "https://plugins.gradle.org/m2/"
} }
dependencies { dependencies {
classpath "org.openapitools:openapi-generator-gradle-plugin:4.0.1" classpath "org.openapitools:openapi-generator-gradle-plugin:4.0.3-SNAPSHOT"
} }
} }
apply plugin: 'org.openapi.generator' apply plugin: 'org.openapi.generator'
---- ----
//# /RELEASE_VERSION
[NOTE]
====
The gradle plugin is not currently published to https://plugins.gradle.org/m2/.
====
== Configuration == Configuration
@ -591,6 +600,7 @@ Android Studio may experience a Windows-specific Guava dependency conflict with
As a workaround, you may force exclude conflicting Guava dependencies. As a workaround, you may force exclude conflicting Guava dependencies.
//# RELEASE_VERSION
```gradle ```gradle
buildscript { buildscript {
repositories { repositories {
@ -599,7 +609,7 @@ buildscript {
} }
dependencies { dependencies {
classpath 'com.android.tools.build:gradle:3.2.1' classpath 'com.android.tools.build:gradle:3.2.1'
classpath('org.openapitools:openapi-generator-gradle-plugin:4.0.1') { classpath('org.openapitools:openapi-generator-gradle-plugin:4.0.3-SNAPSHOT') {
exclude group: 'com.google.guava' exclude group: 'com.google.guava'
} }
} }
@ -612,5 +622,6 @@ configurations {
// … // …
apply plugin: 'org.openapi.generator' apply plugin: 'org.openapi.generator'
``` ```
//# /RELEASE_VERSION
See https://github.com/OpenAPITools/openapi-generator/issues/1818[OpenAPITools/openapi-generator#1818] for more details. See https://github.com/OpenAPITools/openapi-generator/issues/1818[OpenAPITools/openapi-generator#1818] for more details.

View File

@ -1,4 +1,6 @@
# RELEASE_VERSION
openApiGeneratorVersion=4.1.0-SNAPSHOT openApiGeneratorVersion=4.1.0-SNAPSHOT
# /RELEASE_VERSION
# BEGIN placeholders # BEGIN placeholders
# these are just placeholders to allow contributors to build directly # these are just placeholders to allow contributors to build directly

View File

@ -3,7 +3,9 @@
<parent> <parent>
<groupId>org.openapitools</groupId> <groupId>org.openapitools</groupId>
<artifactId>openapi-generator-project</artifactId> <artifactId>openapi-generator-project</artifactId>
<!-- RELEASE_VERSION -->
<version>4.1.0-SNAPSHOT</version> <version>4.1.0-SNAPSHOT</version>
<!-- /RELEASE_VERSION -->
<relativePath>../..</relativePath> <relativePath>../..</relativePath>
</parent> </parent>
<modelVersion>4.0.0</modelVersion> <modelVersion>4.0.0</modelVersion>

View File

@ -0,0 +1 @@
.bak/

View File

@ -17,5 +17,5 @@ gradle generateGoWithInvalidSpec
The samples can be tested against other versions of the plugin using the `openApiGeneratorVersion` property. For example: The samples can be tested against other versions of the plugin using the `openApiGeneratorVersion` property. For example:
```bash ```bash
gradle -PopenApiGeneratorVersion=4.0.1 openApiValidate gradle -PopenApiGeneratorVersion=4.0.3-SNAPSHOT openApiValidate
``` ```

View File

@ -1 +1,3 @@
openApiGeneratorVersion=4.0.1 # RELEASE_VERSION
openApiGeneratorVersion=4.0.3-SNAPSHOT
# /RELEASE_VERSION

View File

@ -0,0 +1,5 @@
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-4.10.2-bin.zip
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists

View File

@ -0,0 +1,172 @@
#!/usr/bin/env sh
##############################################################################
##
## Gradle start up script for UN*X
##
##############################################################################
# Attempt to set APP_HOME
# Resolve links: $0 may be a link
PRG="$0"
# Need this for relative symlinks.
while [ -h "$PRG" ] ; do
ls=`ls -ld "$PRG"`
link=`expr "$ls" : '.*-> \(.*\)$'`
if expr "$link" : '/.*' > /dev/null; then
PRG="$link"
else
PRG=`dirname "$PRG"`"/$link"
fi
done
SAVED="`pwd`"
cd "`dirname \"$PRG\"`/" >/dev/null
APP_HOME="`pwd -P`"
cd "$SAVED" >/dev/null
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=""
# Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD="maximum"
warn () {
echo "$*"
}
die () {
echo
echo "$*"
echo
exit 1
}
# OS specific support (must be 'true' or 'false').
cygwin=false
msys=false
darwin=false
nonstop=false
case "`uname`" in
CYGWIN* )
cygwin=true
;;
Darwin* )
darwin=true
;;
MINGW* )
msys=true
;;
NONSTOP* )
nonstop=true
;;
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
# IBM's JDK on AIX uses strange locations for the executables
JAVACMD="$JAVA_HOME/jre/sh/java"
else
JAVACMD="$JAVA_HOME/bin/java"
fi
if [ ! -x "$JAVACMD" ] ; then
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
else
JAVACMD="java"
which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
# Increase the maximum file descriptors if we can.
if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then
MAX_FD_LIMIT=`ulimit -H -n`
if [ $? -eq 0 ] ; then
if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
MAX_FD="$MAX_FD_LIMIT"
fi
ulimit -n $MAX_FD
if [ $? -ne 0 ] ; then
warn "Could not set maximum file descriptor limit: $MAX_FD"
fi
else
warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
fi
fi
# For Darwin, add options to specify how the application appears in the dock
if $darwin; then
GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
fi
# For Cygwin, switch paths to Windows format before running java
if $cygwin ; 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
ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
SEP=""
for dir in $ROOTDIRSRAW ; do
ROOTDIRS="$ROOTDIRS$SEP$dir"
SEP="|"
done
OURCYGPATTERN="(^($ROOTDIRS))"
# Add a user-defined pattern to the cygpath arguments
if [ "$GRADLE_CYGPATTERN" != "" ] ; then
OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
fi
# Now convert the arguments - kludge to limit ourselves to /bin/sh
i=0
for arg in "$@" ; do
CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
else
eval `echo args$i`="\"$arg\""
fi
i=$((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" ;;
esac
fi
# Escape application args
save () {
for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done
echo " "
}
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

@ -0,0 +1,84 @@
@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=
@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

View File

@ -11,7 +11,9 @@ Add to your `build->plugins` section (default phase is `generate-sources` phase)
<plugin> <plugin>
<groupId>org.openapitools</groupId> <groupId>org.openapitools</groupId>
<artifactId>openapi-generator-maven-plugin</artifactId> <artifactId>openapi-generator-maven-plugin</artifactId>
<version>4.0.1</version> <!-- RELEASE_VERSION -->
<version>4.0.3-SNAPSHOT</version>
<!-- /RELEASE_VERSION -->
<executions> <executions>
<execution> <execution>
<goals> <goals>

View File

@ -12,7 +12,9 @@
<plugin> <plugin>
<groupId>org.openapitools</groupId> <groupId>org.openapitools</groupId>
<artifactId>openapi-generator-maven-plugin</artifactId> <artifactId>openapi-generator-maven-plugin</artifactId>
<version>4.0.2-SNAPSHOT</version> <!-- RELEASE_VERSION -->
<version>4.0.3-SNAPSHOT</version>
<!-- /RELEASE_VERSION -->
<executions> <executions>
<execution> <execution>
<goals> <goals>

View File

@ -18,7 +18,9 @@
<plugin> <plugin>
<groupId>org.openapitools</groupId> <groupId>org.openapitools</groupId>
<artifactId>openapi-generator-maven-plugin</artifactId> <artifactId>openapi-generator-maven-plugin</artifactId>
<version>4.0.2-SNAPSHOT</version> <!-- RELEASE_VERSION -->
<version>4.0.3-SNAPSHOT</version>
<!-- /RELEASE_VERSION -->
<dependencies> <dependencies>
<dependency> <dependency>
<groupId>${project.groupId}</groupId> <groupId>${project.groupId}</groupId>

View File

@ -12,7 +12,9 @@
<plugin> <plugin>
<groupId>org.openapitools</groupId> <groupId>org.openapitools</groupId>
<artifactId>openapi-generator-maven-plugin</artifactId> <artifactId>openapi-generator-maven-plugin</artifactId>
<version>4.0.2-SNAPSHOT</version> <!-- RELEASE_VERSION -->
<version>4.0.3-SNAPSHOT</version>
<!-- /RELEASE_VERSION -->
<executions> <executions>
<execution> <execution>
<goals> <goals>

View File

@ -12,7 +12,9 @@
<plugin> <plugin>
<groupId>org.openapitools</groupId> <groupId>org.openapitools</groupId>
<artifactId>openapi-generator-maven-plugin</artifactId> <artifactId>openapi-generator-maven-plugin</artifactId>
<version>4.0.2-SNAPSHOT</version> <!-- RELEASE_VERSION -->
<version>4.0.3-SNAPSHOT</version>
<!-- /RELEASE_VERSION -->
<executions> <executions>
<execution> <execution>
<goals> <goals>

View File

@ -4,7 +4,9 @@
<parent> <parent>
<groupId>org.openapitools</groupId> <groupId>org.openapitools</groupId>
<artifactId>openapi-generator-project</artifactId> <artifactId>openapi-generator-project</artifactId>
<!-- RELEASE_VERSION -->
<version>4.1.0-SNAPSHOT</version> <version>4.1.0-SNAPSHOT</version>
<!-- /RELEASE_VERSION -->
<relativePath>../..</relativePath> <relativePath>../..</relativePath>
</parent> </parent>
<artifactId>openapi-generator-maven-plugin</artifactId> <artifactId>openapi-generator-maven-plugin</artifactId>

View File

@ -245,7 +245,7 @@ public class CodeGenMojo extends AbstractMojo {
* To treat a document strictly against the spec. * To treat a document strictly against the spec.
*/ */
@Parameter(name = "strictSpec", property = "openapi.generator.maven.plugin.strictSpec", required = false) @Parameter(name = "strictSpec", property = "openapi.generator.maven.plugin.strictSpec", required = false)
private Boolean strictSpecBehavior; private Boolean strictSpec;
/** /**
* To generate alias (array, map) as model * To generate alias (array, map) as model
@ -471,8 +471,8 @@ public class CodeGenMojo extends AbstractMojo {
configurator.setValidateSpec(!skipValidateSpec); configurator.setValidateSpec(!skipValidateSpec);
} }
if (strictSpecBehavior != null) { if (strictSpec != null) {
configurator.setStrictSpecBehavior(strictSpecBehavior); configurator.setStrictSpecBehavior(strictSpec);
} }
if (logToStderr != null) { if (logToStderr != null) {

View File

@ -3,7 +3,9 @@
<parent> <parent>
<groupId>org.openapitools</groupId> <groupId>org.openapitools</groupId>
<artifactId>openapi-generator-project</artifactId> <artifactId>openapi-generator-project</artifactId>
<!-- RELEASE_VERSION -->
<version>4.1.0-SNAPSHOT</version> <version>4.1.0-SNAPSHOT</version>
<!-- /RELEASE_VERSION -->
<relativePath>../..</relativePath> <relativePath>../..</relativePath>
</parent> </parent>
<artifactId>openapi-generator-online</artifactId> <artifactId>openapi-generator-online</artifactId>

View File

@ -3,7 +3,9 @@
<parent> <parent>
<groupId>org.openapitools</groupId> <groupId>org.openapitools</groupId>
<artifactId>openapi-generator-project</artifactId> <artifactId>openapi-generator-project</artifactId>
<!-- RELEASE_VERSION -->
<version>4.1.0-SNAPSHOT</version> <version>4.1.0-SNAPSHOT</version>
<!-- /RELEASE_VERSION -->
<relativePath>../..</relativePath> <relativePath>../..</relativePath>
</parent> </parent>
<modelVersion>4.0.0</modelVersion> <modelVersion>4.0.0</modelVersion>
@ -318,7 +320,7 @@
<dependency> <dependency>
<groupId>org.openapitools</groupId> <groupId>org.openapitools</groupId>
<artifactId>openapi-generator-core</artifactId> <artifactId>openapi-generator-core</artifactId>
<version>4.1.0-SNAPSHOT</version> <version>${project.parent.version}</version>
</dependency> </dependency>
</dependencies> </dependencies>
<repositories> <repositories>

View File

@ -69,6 +69,9 @@ public class CodegenConstants {
public static final String WITH_GO_CODEGEN_COMMENT = "withGoCodegenComment"; public static final String WITH_GO_CODEGEN_COMMENT = "withGoCodegenComment";
public static final String WITH_GO_CODEGEN_COMMENT_DESC = "whether to include Go codegen comment to disable Go Lint and collapse by default GitHub in PRs and diffs"; public static final String WITH_GO_CODEGEN_COMMENT_DESC = "whether to include Go codegen comment to disable Go Lint and collapse by default GitHub in PRs and diffs";
public static final String IS_GO_SUBMODULE = "isGoSubmodule";
public static final String IS_GO_SUBMODULE_DESC = "whether the generated Go module is a submodule";
public static final String GROUP_ID = "groupId"; public static final String GROUP_ID = "groupId";
public static final String GROUP_ID_DESC = "groupId in generated pom.xml"; public static final String GROUP_ID_DESC = "groupId in generated pom.xml";

View File

@ -38,7 +38,7 @@ public class CodegenSecurity {
// Oauth specific // Oauth specific
public String flow, authorizationUrl, tokenUrl; public String flow, authorizationUrl, tokenUrl;
public List<Map<String, Object>> scopes; public List<Map<String, Object>> scopes;
public Boolean isCode, isPassword, isApplication, isImplicit; public Boolean isCode, isPassword, isApplication, isImplicit, hasScopes;
@Override @Override
public String toString() { public String toString() {

View File

@ -1756,10 +1756,10 @@ public class DefaultCodegen implements CodegenConfig {
m.interfaces.add(modelName); m.interfaces.add(modelName);
addImport(m, modelName); addImport(m, modelName);
if (allDefinitions != null && refSchema != null) { if (allDefinitions != null && refSchema != null) {
if (allParents.contains(modelName) && supportsMultipleInheritance) { if (allParents.contains(ref) && supportsMultipleInheritance) {
// multiple inheritance // multiple inheritance
addProperties(allProperties, allRequired, refSchema); addProperties(allProperties, allRequired, refSchema);
} else if (parentName != null && parentName.equals(modelName) && supportsInheritance) { } else if (parentName != null && parentName.equals(ref) && supportsInheritance) {
// single inheritance // single inheritance
addProperties(allProperties, allRequired, refSchema); addProperties(allProperties, allRequired, refSchema);
} else { } else {
@ -2210,6 +2210,7 @@ public class DefaultCodegen implements CodegenConfig {
// property.baseType = getSimpleRef(p.get$ref()); // property.baseType = getSimpleRef(p.get$ref());
//} //}
// --END of revision // --END of revision
property.isModel = ModelUtils.isModel(p);
setNonArrayMapProperty(property, type); setNonArrayMapProperty(property, type);
} }
@ -3035,6 +3036,9 @@ public class DefaultCodegen implements CodegenConfig {
} else { } else {
codegenParameter.dataType = codegenProperty.dataType; codegenParameter.dataType = codegenProperty.dataType;
} }
if (ModelUtils.isObjectSchema(parameterSchema)) {
codegenProperty.complexType = codegenParameter.dataType;
}
codegenParameter.dataFormat = codegenProperty.dataFormat; codegenParameter.dataFormat = codegenProperty.dataFormat;
codegenParameter.required = codegenProperty.required; codegenParameter.required = codegenProperty.required;
@ -3221,6 +3225,10 @@ public class DefaultCodegen implements CodegenConfig {
* @return data type * @return data type
*/ */
protected String getParameterDataType(Parameter parameter, Schema schema) { protected String getParameterDataType(Parameter parameter, Schema schema) {
if (parameter.get$ref() != null) {
String refName = ModelUtils.getSimpleRef(parameter.get$ref());
return toModelName(refName);
}
return null; return null;
} }
@ -4652,9 +4660,17 @@ public class DefaultCodegen implements CodegenConfig {
schema.setAdditionalProperties(inner); schema.setAdditionalProperties(inner);
} }
CodegenProperty codegenProperty = fromProperty("property", schema); CodegenProperty codegenProperty = fromProperty("property", schema);
// only support 1-dimension map only
imports.add(codegenProperty.baseType); imports.add(codegenProperty.baseType);
CodegenProperty innerCp = codegenProperty;
while (innerCp != null) {
if (innerCp.complexType != null) {
imports.add(innerCp.complexType);
}
innerCp = innerCp.items;
}
if (StringUtils.isEmpty(bodyParameterName)) { if (StringUtils.isEmpty(bodyParameterName)) {
codegenParameter.baseName = "request_body"; codegenParameter.baseName = "request_body";
} else { } else {
@ -4707,7 +4723,7 @@ public class DefaultCodegen implements CodegenConfig {
codegenParameter.items = codegenProperty.items; codegenParameter.items = codegenProperty.items;
codegenParameter.mostInnerItems = codegenProperty.mostInnerItems; codegenParameter.mostInnerItems = codegenProperty.mostInnerItems;
codegenParameter.dataType = getTypeDeclaration(arraySchema); codegenParameter.dataType = getTypeDeclaration(arraySchema);
codegenParameter.baseType = getSchemaType(arraySchema); codegenParameter.baseType = getSchemaType(inner);
codegenParameter.isContainer = Boolean.TRUE; codegenParameter.isContainer = Boolean.TRUE;
codegenParameter.isListContainer = Boolean.TRUE; codegenParameter.isListContainer = Boolean.TRUE;

View File

@ -560,6 +560,7 @@ public class DefaultGenerator extends AbstractGenerator implements Generator {
operation.put("classVarName", config.toApiVarName(tag)); operation.put("classVarName", config.toApiVarName(tag));
operation.put("importPath", config.toApiImport(tag)); operation.put("importPath", config.toApiImport(tag));
operation.put("classFilename", config.toApiFilename(tag)); operation.put("classFilename", config.toApiFilename(tag));
operation.put("strictSpecBehavior", config.isStrictSpecBehavior());
if (allModels == null || allModels.isEmpty()) { if (allModels == null || allModels.isEmpty()) {
operation.put("hasModel", false); operation.put("hasModel", false);
@ -1049,6 +1050,7 @@ public class DefaultGenerator extends AbstractGenerator implements Generator {
if (securities != null && securities.isEmpty()) { if (securities != null && securities.isEmpty()) {
continue; continue;
} }
Map<String, SecurityScheme> authMethods = getAuthMethods(securities, securitySchemes); Map<String, SecurityScheme> authMethods = getAuthMethods(securities, securitySchemes);
if (authMethods == null || authMethods.isEmpty()) { if (authMethods == null || authMethods.isEmpty()) {
authMethods = getAuthMethods(globalSecurities, securitySchemes); authMethods = getAuthMethods(globalSecurities, securitySchemes);
@ -1056,6 +1058,39 @@ public class DefaultGenerator extends AbstractGenerator implements Generator {
if (authMethods != null && !authMethods.isEmpty()) { if (authMethods != null && !authMethods.isEmpty()) {
codegenOperation.authMethods = config.fromSecurity(authMethods); codegenOperation.authMethods = config.fromSecurity(authMethods);
List<Map<String, Object>> scopes = new ArrayList<Map<String, Object>>();
if (codegenOperation.authMethods != null){
for (CodegenSecurity security : codegenOperation.authMethods){
if (security != null && security.isBasicBearer != null && security.isBasicBearer &&
securities != null){
for (SecurityRequirement req : securities){
if (req == null) continue;
for (String key : req.keySet()){
if (security.name != null && key.equals(security.name)){
int count = 0;
for (String sc : req.get(key)){
Map<String, Object> scope = new HashMap<String, Object>();
scope.put("scope", sc);
scope.put("description", "");
count++;
if (req.get(key) != null && count < req.get(key).size()){
scope.put("hasMore", "true");
} else {
scope.put("hasMore", null);
}
scopes.add(scope);
}
//end this inner for
break;
}
}
}
security.hasScopes = scopes.size() > 0;
security.scopes = scopes;
}
}
}
codegenOperation.hasAuthMethods = true; codegenOperation.hasAuthMethods = true;
} }

View File

@ -361,10 +361,11 @@ public abstract class AbstractGoCodegen extends DefaultCodegen implements Codege
iterator.remove(); iterator.remove();
} }
// this will only import "fmt" if there are items in pathParams // this will only import "fmt" and "strings" if there are items in pathParams
for (CodegenOperation operation : operations) { for (CodegenOperation operation : operations) {
if (operation.pathParams != null && operation.pathParams.size() > 0) { if (operation.pathParams != null && operation.pathParams.size() > 0) {
imports.add(createMapping("import", "fmt")); imports.add(createMapping("import", "fmt"));
imports.add(createMapping("import", "strings"));
break; //just need to import once break; //just need to import once
} }
} }

View File

@ -175,7 +175,7 @@ public abstract class AbstractJavaCodegen extends DefaultCodegen implements Code
dateLibrary.setEnum(dateOptions); dateLibrary.setEnum(dateOptions);
cliOptions.add(dateLibrary); cliOptions.add(dateLibrary);
CliOption java8Mode = new CliOption(JAVA8_MODE, "Option. Use Java8 classes instead of third party equivalents").defaultValue(String.valueOf(this.java8Mode)); CliOption java8Mode = CliOption.newBoolean(JAVA8_MODE, "Option. Use Java8 classes instead of third party equivalents", this.java8Mode);
Map<String, String> java8ModeOptions = new HashMap<>(); Map<String, String> java8ModeOptions = new HashMap<>();
java8ModeOptions.put("true", "Use Java 8 classes such as Base64"); java8ModeOptions.put("true", "Use Java 8 classes such as Base64");
java8ModeOptions.put("false", "Various third party libraries as needed"); java8ModeOptions.put("false", "Various third party libraries as needed");

View File

@ -38,6 +38,7 @@ public class AspNetCoreServerCodegen extends AbstractCSharpCodegen {
public static final String USE_SWASHBUCKLE = "useSwashbuckle"; public static final String USE_SWASHBUCKLE = "useSwashbuckle";
public static final String ASPNET_CORE_VERSION = "aspnetCoreVersion"; public static final String ASPNET_CORE_VERSION = "aspnetCoreVersion";
public static final String SWASHBUCKLE_VERSION = "swashbuckleVersion";
public static final String CLASS_MODIFIER = "classModifier"; public static final String CLASS_MODIFIER = "classModifier";
public static final String OPERATION_MODIFIER = "operationModifier"; public static final String OPERATION_MODIFIER = "operationModifier";
public static final String OPERATION_IS_ASYNC = "operationIsAsync"; public static final String OPERATION_IS_ASYNC = "operationIsAsync";
@ -51,6 +52,10 @@ public class AspNetCoreServerCodegen extends AbstractCSharpCodegen {
public static final String SDK_LIB = "Microsoft.NET.Sdk"; public static final String SDK_LIB = "Microsoft.NET.Sdk";
public static final String COMPATIBILITY_VERSION = "compatibilityVersion"; public static final String COMPATIBILITY_VERSION = "compatibilityVersion";
public static final String IS_LIBRARY = "isLibrary"; public static final String IS_LIBRARY = "isLibrary";
public static final String USE_FRAMEWORK_REFERENCE = "useFrameworkReference";
public static final String USE_NEWTONSOFT = "useNewtonsoft";
public static final String USE_DEFAULT_ROUTING = "useDefaultRouting";
public static final String NEWTONSOFT_VERSION = "newtonsoftVersion";
private String packageGuid = "{" + randomUUID().toString().toUpperCase(Locale.ROOT) + "}"; private String packageGuid = "{" + randomUUID().toString().toUpperCase(Locale.ROOT) + "}";
@ -60,18 +65,23 @@ public class AspNetCoreServerCodegen extends AbstractCSharpCodegen {
private boolean useSwashbuckle = true; private boolean useSwashbuckle = true;
protected int serverPort = 8080; protected int serverPort = 8080;
protected String serverHost = "0.0.0.0"; protected String serverHost = "0.0.0.0";
protected CliOption aspnetCoreVersion = new CliOption(ASPNET_CORE_VERSION, "ASP.NET Core version: 2.2 (default), 2.1, 2.0 (deprecated)"); protected CliOption swashbuckleVersion = new CliOption(SWASHBUCKLE_VERSION, "Swashbucke version: 3.0.0, 4.0.0");
; // default to 2.1 ; // default to 2.1
protected CliOption aspnetCoreVersion = new CliOption(ASPNET_CORE_VERSION, "ASP.NET Core version: 3.0 (preview4 only), 2.2, 2.1, 2.0 (deprecated)");
private CliOption classModifier = new CliOption(CLASS_MODIFIER, "Class Modifier can be empty, abstract"); private CliOption classModifier = new CliOption(CLASS_MODIFIER, "Class Modifier can be empty, abstract");
private CliOption operationModifier = new CliOption(OPERATION_MODIFIER, "Operation Modifier can be virtual, abstract or partial"); private CliOption operationModifier = new CliOption(OPERATION_MODIFIER, "Operation Modifier can be virtual, abstract or partial");
private CliOption modelClassModifier = new CliOption(MODEL_CLASS_MODIFIER, "Model Class Modifier can be nothing or partial"); private CliOption modelClassModifier = new CliOption(MODEL_CLASS_MODIFIER, "Model Class Modifier can be nothing or partial");
private boolean generateBody = true; private boolean generateBody = true;
private CliOption buildTarget = new CliOption("buildTarget", "Target to build an application or library"); private CliOption buildTarget = new CliOption("buildTarget", "Target to build an application or library");
private String projectSdk = SDK_WEB; private String projectSdk = SDK_WEB;
private String compatibilityVersion = "Version_2_1"; private String compatibilityVersion = "Version_2_2";
private boolean operationIsAsync = false; private boolean operationIsAsync = false;
private boolean operationResultTask = false; private boolean operationResultTask = false;
private boolean isLibrary = false; private boolean isLibrary = false;
private boolean useFrameworkReference = false;
private boolean useNewtonsoft = true;
private boolean useDefaultRouting = true;
private String newtonsoftVersion = "3.0.0-preview5-19227-01";
public AspNetCoreServerCodegen() { public AspNetCoreServerCodegen() {
super(); super();
@ -146,10 +156,18 @@ public class AspNetCoreServerCodegen extends AbstractCSharpCodegen {
aspnetCoreVersion.addEnum("2.0", "ASP.NET COre 2.0"); aspnetCoreVersion.addEnum("2.0", "ASP.NET COre 2.0");
aspnetCoreVersion.addEnum("2.1", "ASP.NET Core 2.1"); aspnetCoreVersion.addEnum("2.1", "ASP.NET Core 2.1");
aspnetCoreVersion.addEnum("2.2", "ASP.NET Core 2.2"); aspnetCoreVersion.addEnum("2.2", "ASP.NET Core 2.2");
aspnetCoreVersion.addEnum("3.0", "ASP.NET Core 3.0");
aspnetCoreVersion.setDefault("2.2"); aspnetCoreVersion.setDefault("2.2");
aspnetCoreVersion.setOptValue(aspnetCoreVersion.getDefault()); aspnetCoreVersion.setOptValue(aspnetCoreVersion.getDefault());
addOption(aspnetCoreVersion.getOpt(), aspnetCoreVersion.getDescription(), aspnetCoreVersion.getOptValue()); addOption(aspnetCoreVersion.getOpt(), aspnetCoreVersion.getDescription(), aspnetCoreVersion.getOptValue());
swashbuckleVersion.addEnum("3.0.0", "Swashbuckle 3.0.0");
swashbuckleVersion.addEnum("4.0.0", "Swashbuckle 4.0.0");
swashbuckleVersion.addEnum("5.0.0", "Swashbuckle 5.0.0");
swashbuckleVersion.setDefault("3.0.0");
swashbuckleVersion.setOptValue(swashbuckleVersion.getDefault());
addOption(swashbuckleVersion.getOpt(), swashbuckleVersion.getDescription(), swashbuckleVersion.getOptValue());
// CLI Switches // CLI Switches
addSwitch(CodegenConstants.SORT_PARAMS_BY_REQUIRED_FLAG, addSwitch(CodegenConstants.SORT_PARAMS_BY_REQUIRED_FLAG,
CodegenConstants.SORT_PARAMS_BY_REQUIRED_FLAG_DESC, CodegenConstants.SORT_PARAMS_BY_REQUIRED_FLAG_DESC,
@ -175,6 +193,23 @@ public class AspNetCoreServerCodegen extends AbstractCSharpCodegen {
"Is the build a library", "Is the build a library",
isLibrary); isLibrary);
addSwitch(USE_FRAMEWORK_REFERENCE,
"Use frameworkReference for ASP.NET Core 3.0+ and PackageReference ASP.NET Core 2.2 or earlier.",
useFrameworkReference);
addSwitch(USE_NEWTONSOFT,
"Uses the Newtonsoft JSON library.",
useNewtonsoft);
addOption(NEWTONSOFT_VERSION,
"Version for Microsoft.AspNetCore.Mvc.NewtonsoftJson for ASP.NET Core 3.0+",
newtonsoftVersion);
addSwitch(USE_DEFAULT_ROUTING,
"Use default routing for the ASP.NET Core version. For 3.0 turn off default because it is not yet supported.",
useDefaultRouting);
classModifier.addEnum("", "Keep class default with no modifier"); classModifier.addEnum("", "Keep class default with no modifier");
classModifier.addEnum("abstract", "Make class abstract"); classModifier.addEnum("abstract", "Make class abstract");
classModifier.setDefault(""); classModifier.setDefault("");
@ -246,6 +281,11 @@ public class AspNetCoreServerCodegen extends AbstractCSharpCodegen {
} }
additionalProperties.put("packageGuid", packageGuid); additionalProperties.put("packageGuid", packageGuid);
if (!additionalProperties.containsKey(NEWTONSOFT_VERSION)) {
additionalProperties.put(NEWTONSOFT_VERSION, newtonsoftVersion);
} else {
newtonsoftVersion = (String)additionalProperties.get(NEWTONSOFT_VERSION);
}
// CHeck for the modifiers etc. // CHeck for the modifiers etc.
// The order of the checks is important. // The order of the checks is important.
@ -275,6 +315,10 @@ public class AspNetCoreServerCodegen extends AbstractCSharpCodegen {
// determine the ASP.NET core version setting // determine the ASP.NET core version setting
setAspnetCoreVersion(packageFolder); setAspnetCoreVersion(packageFolder);
setSwashbuckleVersion();
setIsFramework();
setUseNewtonsoft();
setUseEndpointRouting();
supportingFiles.add(new SupportingFile("build.sh.mustache", "", "build.sh")); supportingFiles.add(new SupportingFile("build.sh.mustache", "", "build.sh"));
supportingFiles.add(new SupportingFile("build.bat.mustache", "", "build.bat")); supportingFiles.add(new SupportingFile("build.bat.mustache", "", "build.bat"));
@ -309,6 +353,8 @@ public class AspNetCoreServerCodegen extends AbstractCSharpCodegen {
supportingFiles.add(new SupportingFile("Filters" + File.separator + "GeneratePathParamsValidationFilter.mustache", supportingFiles.add(new SupportingFile("Filters" + File.separator + "GeneratePathParamsValidationFilter.mustache",
packageFolder + File.separator + "Filters", "GeneratePathParamsValidationFilter.cs")); packageFolder + File.separator + "Filters", "GeneratePathParamsValidationFilter.cs"));
} }
supportingFiles.add(new SupportingFile("Authentication" + File.separator + "ApiAuthentication.mustache",packageFolder + File.separator + "Authentication", "ApiAuthentication.cs"));
} }
public void setPackageGuid(String packageGuid) { public void setPackageGuid(String packageGuid) {
@ -483,4 +529,60 @@ public class AspNetCoreServerCodegen extends AbstractCSharpCodegen {
additionalProperties.put(OPERATION_IS_ASYNC, operationIsAsync); additionalProperties.put(OPERATION_IS_ASYNC, operationIsAsync);
} }
} }
private void setIsFramework() {
if (aspnetCoreVersion.getOptValue().startsWith("3.")) {// default, do nothing
LOGGER.warn("ASP.NET core version is " + aspnetCoreVersion.getOptValue() + " so changing to use frameworkReference instead of packageReference ");
useFrameworkReference = true;
additionalProperties.put(USE_FRAMEWORK_REFERENCE, useFrameworkReference);
} else {
if (additionalProperties.containsKey(USE_FRAMEWORK_REFERENCE)) {
useFrameworkReference = convertPropertyToBooleanAndWriteBack(USE_FRAMEWORK_REFERENCE);
} else {
additionalProperties.put(USE_FRAMEWORK_REFERENCE, useFrameworkReference);
}
}
}
private void setUseNewtonsoft() {
if (aspnetCoreVersion.getOptValue().startsWith("2.")) {
LOGGER.warn("ASP.NET core version is " + aspnetCoreVersion.getOptValue() + " so staying on default json library.");
useNewtonsoft = false;
additionalProperties.put(USE_NEWTONSOFT, useNewtonsoft);
} else {
if (additionalProperties.containsKey(USE_NEWTONSOFT)) {
useNewtonsoft = convertPropertyToBooleanAndWriteBack(USE_NEWTONSOFT);
} else {
additionalProperties.put(USE_NEWTONSOFT, useNewtonsoft);
}
}
}
private void setUseEndpointRouting() {
if (aspnetCoreVersion.getOptValue().startsWith("3.")) {
LOGGER.warn("ASP.NET core version is " + aspnetCoreVersion.getOptValue() + " so switching to old style endpoint routing.");
useDefaultRouting = false;
additionalProperties.put(USE_DEFAULT_ROUTING, useDefaultRouting);
} else {
if (additionalProperties.containsKey(USE_DEFAULT_ROUTING)) {
useDefaultRouting = convertPropertyToBooleanAndWriteBack(USE_DEFAULT_ROUTING);
} else {
additionalProperties.put(USE_DEFAULT_ROUTING, useDefaultRouting);
}
}
}
private void setSwashbuckleVersion() {
setCliOption(swashbuckleVersion);
if (aspnetCoreVersion.getOptValue().startsWith("3.")) {
LOGGER.warn("ASP.NET core version is " + aspnetCoreVersion.getOptValue() + " so changing default Swashbuckle version to 4.0.0.");
swashbuckleVersion.setOptValue("4.0.0");
additionalProperties.put(SWASHBUCKLE_VERSION, swashbuckleVersion.getOptValue());
} else {
// default, do nothing
LOGGER.info("Swashbuckle version: " + swashbuckleVersion.getOptValue());
}
}
} }

View File

@ -33,6 +33,7 @@ public class GoClientCodegen extends AbstractGoCodegen {
protected String packageVersion = "1.0.0"; protected String packageVersion = "1.0.0";
protected String apiDocPath = "docs/"; protected String apiDocPath = "docs/";
protected String modelDocPath = "docs/"; protected String modelDocPath = "docs/";
protected boolean isGoSubmodule = false;
public static final String WITH_GO_CODEGEN_COMMENT = "withGoCodegenComment"; public static final String WITH_GO_CODEGEN_COMMENT = "withGoCodegenComment";
public static final String WITH_XML = "withXml"; public static final String WITH_XML = "withXml";
@ -51,6 +52,7 @@ public class GoClientCodegen extends AbstractGoCodegen {
// default HIDE_GENERATION_TIMESTAMP to true // default HIDE_GENERATION_TIMESTAMP to true
hideGenerationTimestamp = Boolean.TRUE; hideGenerationTimestamp = Boolean.TRUE;
cliOptions.add(CliOption.newBoolean(CodegenConstants.IS_GO_SUBMODULE, CodegenConstants.IS_GO_SUBMODULE_DESC));
cliOptions.add(CliOption.newBoolean(WITH_GO_CODEGEN_COMMENT, "whether to include Go codegen comment to disable Go Lint and collapse by default GitHub in PRs and diffs")); cliOptions.add(CliOption.newBoolean(WITH_GO_CODEGEN_COMMENT, "whether to include Go codegen comment to disable Go Lint and collapse by default GitHub in PRs and diffs"));
cliOptions.add(CliOption.newBoolean(WITH_XML, "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)")); cliOptions.add(CliOption.newBoolean(WITH_XML, "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)"));
@ -111,6 +113,13 @@ public class GoClientCodegen extends AbstractGoCodegen {
additionalProperties.put(WITH_XML, "true"); additionalProperties.put(WITH_XML, "true");
} }
} }
if (additionalProperties.containsKey(CodegenConstants.IS_GO_SUBMODULE)) {
setIsGoSubmodule(Boolean.parseBoolean(additionalProperties.get(CodegenConstants.IS_GO_SUBMODULE).toString()));
if (isGoSubmodule) {
additionalProperties.put(CodegenConstants.IS_GO_SUBMODULE, "true");
}
}
} }
/** /**
@ -184,4 +193,8 @@ public class GoClientCodegen extends AbstractGoCodegen {
this.packageVersion = packageVersion; this.packageVersion = packageVersion;
} }
public void setIsGoSubmodule(boolean isGoSubmodule) {
this.isGoSubmodule = isGoSubmodule;
}
} }

View File

@ -54,6 +54,7 @@ public class JavaClientCodegen extends AbstractJavaCodegen
public static final String PARCELABLE_MODEL = "parcelableModel"; public static final String PARCELABLE_MODEL = "parcelableModel";
public static final String USE_RUNTIME_EXCEPTION = "useRuntimeException"; public static final String USE_RUNTIME_EXCEPTION = "useRuntimeException";
public static final String USE_REFLECTION_EQUALS_HASHCODE = "useReflectionEqualsHashCode"; public static final String USE_REFLECTION_EQUALS_HASHCODE = "useReflectionEqualsHashCode";
public static final String CASE_INSENSITIVE_RESPONSE_HEADERS = "caseInsensitiveResponseHeaders";
public static final String PLAY_24 = "play24"; public static final String PLAY_24 = "play24";
public static final String PLAY_25 = "play25"; public static final String PLAY_25 = "play25";
@ -90,6 +91,7 @@ public class JavaClientCodegen extends AbstractJavaCodegen
protected boolean useGzipFeature = false; protected boolean useGzipFeature = false;
protected boolean useRuntimeException = false; protected boolean useRuntimeException = false;
protected boolean useReflectionEqualsHashCode = false; protected boolean useReflectionEqualsHashCode = false;
protected boolean caseInsensitiveResponseHeaders = false;
protected String authFolder; protected String authFolder;
public JavaClientCodegen() { public JavaClientCodegen() {
@ -122,6 +124,8 @@ public class JavaClientCodegen extends AbstractJavaCodegen
cliOptions.add(CliOption.newBoolean(USE_RUNTIME_EXCEPTION, "Use RuntimeException instead of Exception")); cliOptions.add(CliOption.newBoolean(USE_RUNTIME_EXCEPTION, "Use RuntimeException instead of Exception"));
cliOptions.add(CliOption.newBoolean(FEIGN_VERSION, "Version of OpenFeign: '10.x', '9.x' (default)")); cliOptions.add(CliOption.newBoolean(FEIGN_VERSION, "Version of OpenFeign: '10.x', '9.x' (default)"));
cliOptions.add(CliOption.newBoolean(USE_REFLECTION_EQUALS_HASHCODE, "Use org.apache.commons.lang3.builder for equals and hashCode in the models. WARNING: This will fail under a security manager, unless the appropriate permissions are set up correctly and also there's potential performance impact.")); cliOptions.add(CliOption.newBoolean(USE_REFLECTION_EQUALS_HASHCODE, "Use org.apache.commons.lang3.builder for equals and hashCode in the models. WARNING: This will fail under a security manager, unless the appropriate permissions are set up correctly and also there's potential performance impact."));
cliOptions.add(CliOption.newBoolean(CASE_INSENSITIVE_RESPONSE_HEADERS, "Make API response's headers case-insensitive. Available on " + OKHTTP_GSON + ", " + JERSEY2 + " libraries"));
supportedLibraries.put(JERSEY1, "HTTP client: Jersey client 1.19.x. JSON processing: Jackson 2.8.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.8.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(JERSEY2, "HTTP client: Jersey client 2.25.1. JSON processing: Jackson 2.8.x"); supportedLibraries.put(JERSEY2, "HTTP client: Jersey client 2.25.1. JSON processing: Jackson 2.8.x");
@ -232,6 +236,10 @@ public class JavaClientCodegen extends AbstractJavaCodegen
this.setUseReflectionEqualsHashCode(convertPropertyToBooleanAndWriteBack(USE_REFLECTION_EQUALS_HASHCODE)); this.setUseReflectionEqualsHashCode(convertPropertyToBooleanAndWriteBack(USE_REFLECTION_EQUALS_HASHCODE));
} }
if (additionalProperties.containsKey(CASE_INSENSITIVE_RESPONSE_HEADERS)) {
this.setUseReflectionEqualsHashCode(convertPropertyToBooleanAndWriteBack(CASE_INSENSITIVE_RESPONSE_HEADERS));
}
final String invokerFolder = (sourceFolder + '/' + invokerPackage).replace(".", "/"); final String invokerFolder = (sourceFolder + '/' + invokerPackage).replace(".", "/");
final String apiFolder = (sourceFolder + '/' + apiPackage).replace(".", "/"); final String apiFolder = (sourceFolder + '/' + apiPackage).replace(".", "/");
authFolder = (sourceFolder + '/' + invokerPackage + ".auth").replace(".", "/"); authFolder = (sourceFolder + '/' + invokerPackage + ".auth").replace(".", "/");
@ -659,6 +667,10 @@ public class JavaClientCodegen extends AbstractJavaCodegen
this.useReflectionEqualsHashCode = useReflectionEqualsHashCode; this.useReflectionEqualsHashCode = useReflectionEqualsHashCode;
} }
public void setCaseInsensitiveResponseHeaders(final Boolean caseInsensitiveResponseHeaders) {
this.caseInsensitiveResponseHeaders = caseInsensitiveResponseHeaders;
}
final private static Pattern JSON_MIME_PATTERN = Pattern.compile("(?i)application\\/json(;.*)?"); final private static Pattern JSON_MIME_PATTERN = Pattern.compile("(?i)application\\/json(;.*)?");
final private static Pattern JSON_VENDOR_MIME_PATTERN = Pattern.compile("(?i)application\\/vnd.(.*)+json(;.*)?"); final private static Pattern JSON_VENDOR_MIME_PATTERN = Pattern.compile("(?i)application\\/vnd.(.*)+json(;.*)?");

View File

@ -60,6 +60,8 @@ public class KotlinSpringServerCodegen extends AbstractKotlinCodegen
public static final String SWAGGER_ANNOTATIONS = "swaggerAnnotations"; public static final String SWAGGER_ANNOTATIONS = "swaggerAnnotations";
public static final String SERVICE_INTERFACE = "serviceInterface"; public static final String SERVICE_INTERFACE = "serviceInterface";
public static final String SERVICE_IMPLEMENTATION = "serviceImplementation"; public static final String SERVICE_IMPLEMENTATION = "serviceImplementation";
public static final String REACTIVE = "reactive";
private String basePackage; private String basePackage;
private String invokerPackage; private String invokerPackage;
@ -72,6 +74,7 @@ public class KotlinSpringServerCodegen extends AbstractKotlinCodegen
private boolean swaggerAnnotations = false; private boolean swaggerAnnotations = false;
private boolean serviceInterface = false; private boolean serviceInterface = false;
private boolean serviceImplementation = false; private boolean serviceImplementation = false;
private boolean reactive = false;
public KotlinSpringServerCodegen() { public KotlinSpringServerCodegen() {
super(); super();
@ -92,55 +95,26 @@ public class KotlinSpringServerCodegen extends AbstractKotlinCodegen
updateOption(CodegenConstants.ARTIFACT_ID, this.artifactId); updateOption(CodegenConstants.ARTIFACT_ID, this.artifactId);
// Use lists instead of arrays // Use lists instead of arrays
typeMapping.put("array", "List"); typeMapping.put("array", "kotlin.collections.List");
typeMapping.put("string", "String"); typeMapping.put("list", "kotlin.collections.List");
typeMapping.put("boolean", "Boolean");
typeMapping.put("integer", "Int");
typeMapping.put("float", "Float");
typeMapping.put("long", "Long");
typeMapping.put("double", "Double");
typeMapping.put("ByteArray", "ByteArray");
typeMapping.put("list", "List");
typeMapping.put("map", "Map");
typeMapping.put("object", "Any");
typeMapping.put("binary", "Array<kotlin.Byte>");
typeMapping.put("date", "java.time.LocalDate"); typeMapping.put("date", "java.time.LocalDate");
typeMapping.put("date-time", "java.time.OffsetDateTime"); typeMapping.put("date-time", "java.time.OffsetDateTime");
typeMapping.put("Date", "java.time.LocalDate"); typeMapping.put("Date", "java.time.LocalDate");
typeMapping.put("DateTime", "java.time.OffsetDateTime"); typeMapping.put("DateTime", "java.time.OffsetDateTime");
importMapping.put("Date", "java.time.LocalDate");
importMapping.put("DateTime", "java.time.OffsetDateTime");
// use resource for file handling // use resource for file handling
typeMapping.put("file", "org.springframework.core.io.Resource"); typeMapping.put("file", "org.springframework.core.io.Resource");
importMapping.put("Date", "java.time.LocalDate");
languageSpecificPrimitives.addAll(Arrays.asList( importMapping.put("DateTime", "java.time.OffsetDateTime");
"Any",
"Byte",
"ByteArray",
"Short",
"Int",
"Long",
"Float",
"Double",
"Boolean",
"Char",
"String",
"Array",
"List",
"Map",
"Set"
));
addOption(TITLE, "server title name or client service name", title); addOption(TITLE, "server title name or client service name", title);
addOption(BASE_PACKAGE, "base package (invokerPackage) for generated code", basePackage); addOption(BASE_PACKAGE, "base package (invokerPackage) for generated code", basePackage);
addOption(SERVER_PORT, "configuration the port in which the sever is to run on", serverPort); addOption(SERVER_PORT, "configuration the port in which the sever is to run on", serverPort);
addOption(CodegenConstants.MODEL_PACKAGE, "model package for generated code", modelPackage); addOption(CodegenConstants.MODEL_PACKAGE, "model package for generated code", modelPackage);
addOption(CodegenConstants.API_PACKAGE, "api package for generated code", apiPackage); addOption(CodegenConstants.API_PACKAGE, "api package for generated code", apiPackage);
addSwitch(EXCEPTION_HANDLER, "generate default global exception handlers", exceptionHandler); addSwitch(EXCEPTION_HANDLER, "generate default global exception handlers (not compatible with reactive. enabling reactive will disable exceptionHandler )", exceptionHandler);
addSwitch(GRADLE_BUILD_FILE, "generate a gradle build file using the Kotlin DSL", gradleBuildFile); addSwitch(GRADLE_BUILD_FILE, "generate a gradle build file using the Kotlin DSL", gradleBuildFile);
addSwitch(SWAGGER_ANNOTATIONS, "generate swagger annotations to go alongside controllers and models", swaggerAnnotations); addSwitch(SWAGGER_ANNOTATIONS, "generate swagger annotations to go alongside controllers and models", swaggerAnnotations);
addSwitch(SERVICE_INTERFACE, "generate service interfaces to go alongside controllers. In most " + addSwitch(SERVICE_INTERFACE, "generate service interfaces to go alongside controllers. In most " +
@ -149,7 +123,7 @@ public class KotlinSpringServerCodegen extends AbstractKotlinCodegen
addSwitch(SERVICE_IMPLEMENTATION, "generate stub service implementations that extends service " + addSwitch(SERVICE_IMPLEMENTATION, "generate stub service implementations that extends service " +
"interfaces. If this is set to true service interfaces will also be generated", serviceImplementation); "interfaces. If this is set to true service interfaces will also be generated", serviceImplementation);
addSwitch(USE_BEANVALIDATION, "Use BeanValidation API annotations to validate data types", useBeanValidation); addSwitch(USE_BEANVALIDATION, "Use BeanValidation API annotations to validate data types", useBeanValidation);
addSwitch(REACTIVE, "use coroutines for reactive behavior", reactive);
supportedLibraries.put(SPRING_BOOT, "Spring-boot Server application."); supportedLibraries.put(SPRING_BOOT, "Spring-boot Server application.");
setLibrary(SPRING_BOOT); setLibrary(SPRING_BOOT);
@ -240,6 +214,14 @@ public class KotlinSpringServerCodegen extends AbstractKotlinCodegen
this.useBeanValidation = useBeanValidation; this.useBeanValidation = useBeanValidation;
} }
public boolean isReactive() {
return reactive;
}
public void setReactive(boolean reactive) {
this.reactive = reactive;
}
@Override @Override
public CodegenType getTag() { public CodegenType getTag() {
return CodegenType.SERVER; return CodegenType.SERVER;
@ -332,6 +314,14 @@ public class KotlinSpringServerCodegen extends AbstractKotlinCodegen
} }
writePropertyBack(USE_BEANVALIDATION, useBeanValidation); writePropertyBack(USE_BEANVALIDATION, useBeanValidation);
if (additionalProperties.containsKey(REACTIVE) && library.equals(SPRING_BOOT)) {
this.setReactive(convertPropertyToBoolean(REACTIVE));
// spring webflux doesn't support @ControllerAdvice
this.setExceptionHandler(false);
}
writePropertyBack(REACTIVE, reactive);
writePropertyBack(EXCEPTION_HANDLER, exceptionHandler);
modelTemplateFiles.put("model.mustache", ".kt"); modelTemplateFiles.put("model.mustache", ".kt");
apiTemplateFiles.put("api.mustache", ".kt"); apiTemplateFiles.put("api.mustache", ".kt");
supportingFiles.add(new SupportingFile("README.mustache", "", "README.md")); supportingFiles.add(new SupportingFile("README.mustache", "", "README.md"));
@ -524,16 +514,16 @@ public class KotlinSpringServerCodegen extends AbstractKotlinCodegen
private void doDataTypeAssignment(final String returnType, DataTypeAssigner dataTypeAssigner) { private void doDataTypeAssignment(final String returnType, DataTypeAssigner dataTypeAssigner) {
if (returnType == null) { if (returnType == null) {
dataTypeAssigner.setReturnType("Unit"); dataTypeAssigner.setReturnType("Unit");
} else if (returnType.startsWith("List")) { } else if (returnType.startsWith("kotlin.collections.List")) {
int end = returnType.lastIndexOf(">"); int end = returnType.lastIndexOf(">");
if (end > 0) { if (end > 0) {
dataTypeAssigner.setReturnType(returnType.substring("List<".length(), end).trim()); dataTypeAssigner.setReturnType(returnType.substring("kotlin.collections.List<".length(), end).trim());
dataTypeAssigner.setReturnContainer("List"); dataTypeAssigner.setReturnContainer("List");
} }
} else if (returnType.startsWith("Map")) { } else if (returnType.startsWith("kotlin.collections.Map")) {
int end = returnType.lastIndexOf(">"); int end = returnType.lastIndexOf(">");
if (end > 0) { if (end > 0) {
dataTypeAssigner.setReturnType(returnType.substring("Map<".length(), end).split(",")[1].trim()); dataTypeAssigner.setReturnType(returnType.substring("kotlin.collections.Map<".length(), end).split(",")[1].trim());
dataTypeAssigner.setReturnContainer("Map"); dataTypeAssigner.setReturnContainer("Map");
} }
} }

View File

@ -28,6 +28,8 @@ import io.swagger.v3.oas.models.Paths;
import io.swagger.v3.oas.models.info.Info; import io.swagger.v3.oas.models.info.Info;
import org.openapitools.codegen.*; import org.openapitools.codegen.*;
import org.openapitools.codegen.config.GlobalSettings; import org.openapitools.codegen.config.GlobalSettings;
import org.openapitools.codegen.meta.GeneratorMetadata;
import org.openapitools.codegen.meta.Stability;
import org.openapitools.codegen.utils.URLPathUtils; import org.openapitools.codegen.utils.URLPathUtils;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
@ -58,6 +60,11 @@ public class NodeJSServerCodegen extends DefaultCodegen implements CodegenConfig
public NodeJSServerCodegen() { public NodeJSServerCodegen() {
super(); super();
// mark the generator as deprecated in the documentation
generatorMetadata = GeneratorMetadata.newBuilder(generatorMetadata)
.stability(Stability.DEPRECATED)
.build();
// set the output folder here // set the output folder here
outputFolder = "generated-code/nodejs"; outputFolder = "generated-code/nodejs";
@ -142,7 +149,7 @@ public class NodeJSServerCodegen extends DefaultCodegen implements CodegenConfig
*/ */
@Override @Override
public String getName() { public String getName() {
return "nodejs-server"; return "nodejs-server-deprecated";
} }
/** /**
@ -153,7 +160,7 @@ public class NodeJSServerCodegen extends DefaultCodegen implements CodegenConfig
*/ */
@Override @Override
public String getHelp() { public String getHelp() {
return "Generates a nodejs server library using the swagger-tools project. By default, " + return "[DEPRECATED] Generates a nodejs server library using the swagger-tools project. By default, " +
"it will also generate service classes--which you can disable with the `-Dnoservice` environment variable."; "it will also generate service classes--which you can disable with the `-Dnoservice` environment variable.";
} }
@ -303,6 +310,8 @@ public class NodeJSServerCodegen extends DefaultCodegen implements CodegenConfig
message.append(System.lineSeparator()).append(System.lineSeparator()) message.append(System.lineSeparator()).append(System.lineSeparator())
.append("=======================================================================================") .append("=======================================================================================")
.append(System.lineSeparator()) .append(System.lineSeparator())
.append("IMPORTANT: The nodejs-server generator has been deprecated.")
.append(System.lineSeparator())
.append("Currently, Node.js server doesn't work as its dependency doesn't support OpenAPI Spec3.") .append("Currently, Node.js server doesn't work as its dependency doesn't support OpenAPI Spec3.")
.append(System.lineSeparator()) .append(System.lineSeparator())
.append("For further details, see https://github.com/OpenAPITools/openapi-generator/issues/34") .append("For further details, see https://github.com/OpenAPITools/openapi-generator/issues/34")

View File

@ -28,7 +28,7 @@ public class OpenAPIYamlGenerator extends DefaultCodegen implements CodegenConfi
private static final Logger LOGGER = LoggerFactory.getLogger(OpenAPIYamlGenerator.class); private static final Logger LOGGER = LoggerFactory.getLogger(OpenAPIYamlGenerator.class);
protected String outputFile = "openapi.yaml"; protected String outputFile = "openapi/openapi.yaml";
public OpenAPIYamlGenerator() { public OpenAPIYamlGenerator() {
super(); super();
@ -36,9 +36,6 @@ public class OpenAPIYamlGenerator extends DefaultCodegen implements CodegenConfi
outputFolder = "generated-code/openapi-yaml"; outputFolder = "generated-code/openapi-yaml";
cliOptions.add(new CliOption(OUTPUT_NAME, "output filename")); cliOptions.add(new CliOption(OUTPUT_NAME, "output filename"));
supportingFiles.add(new SupportingFile("README.md", "", "README.md")); supportingFiles.add(new SupportingFile("README.md", "", "README.md"));
supportingFiles.add(new SupportingFile("openapi.mustache",
"openapi",
"openapi.yaml"));
} }
@Override @Override
@ -56,13 +53,14 @@ public class OpenAPIYamlGenerator extends DefaultCodegen implements CodegenConfi
return "Creates a static openapi.yaml file (OpenAPI spec v3)."; return "Creates a static openapi.yaml file (OpenAPI spec v3).";
} }
@Override @Override
public void processOpts() { public void processOpts() {
super.processOpts(); super.processOpts();
if (additionalProperties.containsKey(OUTPUT_NAME)) { if (additionalProperties.containsKey(OUTPUT_NAME)) {
this.outputFile = additionalProperties.get(OUTPUT_NAME).toString(); outputFile = additionalProperties.get(OUTPUT_NAME).toString();
} }
LOGGER.info("Output file [outputFile={}]", outputFile);
supportingFiles.add(new SupportingFile("openapi.mustache", outputFile));
} }
@Override @Override
@ -71,7 +69,6 @@ public class OpenAPIYamlGenerator extends DefaultCodegen implements CodegenConfi
return super.postProcessSupportingFileData(objs); return super.postProcessSupportingFileData(objs);
} }
@Override @Override
public String escapeQuotationMark(String input) { public String escapeQuotationMark(String input) {
// just return the original string // just return the original string

View File

@ -167,6 +167,7 @@ public class PerlClientCodegen extends DefaultCodegen implements CodegenConfig {
supportingFiles.add(new SupportingFile("README.mustache", "", "README.md")); supportingFiles.add(new SupportingFile("README.mustache", "", "README.md"));
supportingFiles.add(new SupportingFile("gitignore.mustache", "", ".gitignore")); supportingFiles.add(new SupportingFile("gitignore.mustache", "", ".gitignore"));
supportingFiles.add(new SupportingFile("git_push.sh.mustache", "", "git_push.sh")); supportingFiles.add(new SupportingFile("git_push.sh.mustache", "", "git_push.sh"));
supportingFiles.add(new SupportingFile("travis.mustache", "", ".travis.yml"));
} }
@Override @Override

View File

@ -103,8 +103,10 @@ public class RClientCodegen extends DefaultCodegen implements CodegenConfig {
typeMapping.put("file", "data.frame"); typeMapping.put("file", "data.frame");
typeMapping.put("binary", "data.frame"); typeMapping.put("binary", "data.frame");
typeMapping.put("ByteArray", "character"); typeMapping.put("ByteArray", "character");
typeMapping.put("map", "object"); typeMapping.put("map", "map");
typeMapping.put("object", "object");
importMapping.clear();
cliOptions.clear(); cliOptions.clear();
cliOptions.add(new CliOption(CodegenConstants.PACKAGE_NAME, "R package name (convention: lowercase).") cliOptions.add(new CliOption(CodegenConstants.PACKAGE_NAME, "R package name (convention: lowercase).")
.defaultValue("openapi")); .defaultValue("openapi"));
@ -288,10 +290,10 @@ public class RClientCodegen extends DefaultCodegen implements CodegenConfig {
if (ModelUtils.isArraySchema(p)) { if (ModelUtils.isArraySchema(p)) {
ArraySchema ap = (ArraySchema) p; ArraySchema ap = (ArraySchema) p;
Schema inner = ap.getItems(); Schema inner = ap.getItems();
return getTypeDeclaration(inner); return getSchemaType(p) + "[" + getTypeDeclaration(inner)+ "]";
} else if (ModelUtils.isMapSchema(p)) { } else if (ModelUtils.isMapSchema(p)) {
Schema inner = ModelUtils.getAdditionalProperties(p); Schema inner = ModelUtils.getAdditionalProperties(p);
return getTypeDeclaration(inner); return getSchemaType(p) + "(" + getTypeDeclaration(inner) + ")";
} }
// Not using the supertype invocation, because we want to UpperCamelize // Not using the supertype invocation, because we want to UpperCamelize

View File

@ -91,7 +91,7 @@ public class RubyClientCodegen extends AbstractRubyCodegen {
// local variable names used in API methods (endpoints) // local variable names used in API methods (endpoints)
for (String word : Arrays.asList( for (String word : Arrays.asList(
"local_var_path", "query_params", "header_params", "_header_accept", "_header_accept_result", "local_var_path", "query_params", "header_params", "_header_accept", "_header_accept_result",
"_header_content_type", "form_params", "post_body", "auth_names")) { "_header_content_type", "form_params", "post_body", "auth_names", "send")) {
reservedWords.add(word.toLowerCase(Locale.ROOT)); reservedWords.add(word.toLowerCase(Locale.ROOT));
} }

View File

@ -123,8 +123,7 @@ public class RustClientCodegen extends DefaultCodegen implements CodegenConfig {
// TODO(bcourtine): review file mapping. // TODO(bcourtine): review file mapping.
// I tried to map as "std::io::File", but Reqwest multipart file requires a "AsRef<Path>" param. // I tried to map as "std::io::File", but Reqwest multipart file requires a "AsRef<Path>" param.
// Getting a file from a Path is simple, but the opposite is difficult. So I map as "std::path::Path". // Getting a file from a Path is simple, but the opposite is difficult. So I map as "std::path::Path".
// Reference is required here because Path does not implement the "Sized" trait. typeMapping.put("file", "std::path::PathBuf");
typeMapping.put("file", "&std::path::Path");
typeMapping.put("binary", "::models::File"); typeMapping.put("binary", "::models::File");
typeMapping.put("ByteArray", "String"); typeMapping.put("ByteArray", "String");
typeMapping.put("object", "Value"); typeMapping.put("object", "Value");
@ -151,6 +150,12 @@ public class RustClientCodegen extends DefaultCodegen implements CodegenConfig {
setLibrary(HYPER_LIBRARY); setLibrary(HYPER_LIBRARY);
} }
@Override
public Map<String, Object> postProcessModels(Map<String, Object> objs) {
// process enum in models
return postProcessModelsEnum(objs);
}
@Override @Override
public void processOpts() { public void processOpts() {
super.processOpts(); super.processOpts();
@ -488,25 +493,25 @@ public class RustClientCodegen extends DefaultCodegen implements CodegenConfig {
@Override @Override
public String toEnumVarName(String name, String datatype) { public String toEnumVarName(String name, String datatype) {
if (name.length() == 0) { if (name.length() == 0) {
return "EMPTY"; return "Empty";
} }
// number // number
if ("int".equals(datatype) || "double".equals(datatype) || "float".equals(datatype)) { if ("int".equals(datatype) || "double".equals(datatype) || "float".equals(datatype)) {
String varName = name; String varName = name;
varName = varName.replaceAll("-", "MINUS_"); varName = varName.replaceAll("-", "Minus");
varName = varName.replaceAll("\\+", "PLUS_"); varName = varName.replaceAll("\\+", "Plus");
varName = varName.replaceAll("\\.", "_DOT_"); varName = varName.replaceAll("\\.", "Dot");
return varName; return varName;
} }
// for symbol, e.g. $, # // for symbol, e.g. $, #
if (getSymbolName(name) != null) { if (getSymbolName(name) != null) {
return getSymbolName(name).toUpperCase(Locale.ROOT); return getSymbolName(name);
} }
// string // string
String enumName = sanitizeName(underscore(name).toUpperCase(Locale.ROOT)); String enumName = sanitizeName(camelize(name));
enumName = enumName.replaceFirst("^_", ""); enumName = enumName.replaceFirst("^_", "");
enumName = enumName.replaceFirst("_$", ""); enumName = enumName.replaceFirst("_$", "");
@ -519,7 +524,9 @@ public class RustClientCodegen extends DefaultCodegen implements CodegenConfig {
@Override @Override
public String toEnumName(CodegenProperty property) { public String toEnumName(CodegenProperty property) {
String enumName = underscore(toModelName(property.name)).toUpperCase(Locale.ROOT); // camelize the enum name
// phone_number => PhoneNumber
String enumName = camelize(toModelName(property.name));
// remove [] for array or map of enum // remove [] for array or map of enum
enumName = enumName.replace("[]", ""); enumName = enumName.replace("[]", "");

View File

@ -358,7 +358,15 @@ public class ScalaPlayFrameworkServerCodegen extends AbstractScalaCodegen implem
@Override @Override
public String toEnumName(CodegenProperty property) { public String toEnumName(CodegenProperty property) {
return camelize(property.name); return camelizeStripReservedEscape(property.name);
}
public String camelizeStripReservedEscape(String str) {
if (str.startsWith("`") && str.endsWith("`")) {
str = str.substring(1, str.length() - 1);
}
return camelize(str);
} }
@Override @Override

View File

@ -21,7 +21,6 @@ import com.samskivert.mustache.Mustache;
import io.swagger.v3.oas.models.OpenAPI; import io.swagger.v3.oas.models.OpenAPI;
import io.swagger.v3.oas.models.Operation; import io.swagger.v3.oas.models.Operation;
import io.swagger.v3.oas.models.PathItem; import io.swagger.v3.oas.models.PathItem;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.tuple.Pair; import org.apache.commons.lang3.tuple.Pair;
import org.openapitools.codegen.*; import org.openapitools.codegen.*;
import org.openapitools.codegen.languages.features.BeanValidationFeatures; import org.openapitools.codegen.languages.features.BeanValidationFeatures;
@ -117,7 +116,7 @@ public class SpringCodegen extends AbstractJavaCodegen
cliOptions.add(CliOption.newBoolean(INTERFACE_ONLY, "Whether to generate only API interface stubs without the server files.", interfaceOnly)); cliOptions.add(CliOption.newBoolean(INTERFACE_ONLY, "Whether to generate only API interface stubs without the server files.", interfaceOnly));
cliOptions.add(CliOption.newBoolean(DELEGATE_PATTERN, "Whether to generate the server files using the delegate pattern", delegatePattern)); cliOptions.add(CliOption.newBoolean(DELEGATE_PATTERN, "Whether to generate the server files using the delegate pattern", delegatePattern));
cliOptions.add(CliOption.newBoolean(SINGLE_CONTENT_TYPES, "Whether to select only one produces/consumes content-type by operation.", singleContentTypes)); cliOptions.add(CliOption.newBoolean(SINGLE_CONTENT_TYPES, "Whether to select only one produces/consumes content-type by operation.", singleContentTypes));
cliOptions.add(CliOption.newBoolean(JAVA_8, "use java8 default interface", java8)); updateJava8CliOptions();
cliOptions.add(CliOption.newBoolean(ASYNC, "use async Callable controllers", async)); cliOptions.add(CliOption.newBoolean(ASYNC, "use async Callable controllers", async));
cliOptions.add(CliOption.newBoolean(REACTIVE, "wrap responses in Mono/Flux Reactor types (spring-boot only)", reactive)); cliOptions.add(CliOption.newBoolean(REACTIVE, "wrap responses in Mono/Flux Reactor types (spring-boot only)", reactive));
cliOptions.add(new CliOption(RESPONSE_WRAPPER, "wrap the responses in given type (Future,Callable,CompletableFuture,ListenableFuture,DeferredResult,HystrixCommand,RxObservable,RxSingle or fully qualified type)")); cliOptions.add(new CliOption(RESPONSE_WRAPPER, "wrap the responses in given type (Future,Callable,CompletableFuture,ListenableFuture,DeferredResult,HystrixCommand,RxObservable,RxSingle or fully qualified type)"));
@ -142,6 +141,13 @@ public class SpringCodegen extends AbstractJavaCodegen
} }
private void updateJava8CliOptions() {
CliOption option = cliOptions.stream().filter(o -> JAVA_8.equals(o.getOpt())).findFirst()
.orElseThrow(() -> new RuntimeException("Missing java8 option"));
Map<String, String> java8ModeOptions = option.getEnum();
java8ModeOptions.put("true", "Use Java 8 classes such as Base64. Use java8 default interface when a responseWrapper is used");
}
@Override @Override
public CodegenType getTag() { public CodegenType getTag() {
return CodegenType.SERVER; return CodegenType.SERVER;

View File

@ -84,14 +84,12 @@ import {{{invokerPackage}}}.auth.*;
import {{{modelPackage}}}.*; import {{{modelPackage}}}.*;
import {{{package}}}.{{{classname}}}; import {{{package}}}.{{{classname}}};
import java.io.File;
import java.util.*;
public class {{{classname}}}Example { public class {{{classname}}}Example {
public static void main(String[] args) { public static void main(String[] args) {
{{#hasAuthMethods}}ApiClient defaultClient = Configuration.getDefaultApiClient(); ApiClient defaultClient = Configuration.getDefaultApiClient();
{{#authMethods}}{{#isBasic}} defaultClient.setBasePath("{{{basePath}}}");
{{#hasAuthMethods}}{{#authMethods}}{{#isBasic}}
// Configure HTTP basic authorization: {{{name}}} // Configure HTTP basic authorization: {{{name}}}
HttpBasicAuth {{{name}}} = (HttpBasicAuth) defaultClient.getAuthentication("{{{name}}}"); HttpBasicAuth {{{name}}} = (HttpBasicAuth) defaultClient.getAuthentication("{{{name}}}");
{{{name}}}.setUsername("YOUR USERNAME"); {{{name}}}.setUsername("YOUR USERNAME");
@ -107,7 +105,7 @@ public class {{{classname}}}Example {
{{/authMethods}} {{/authMethods}}
{{/hasAuthMethods}} {{/hasAuthMethods}}
{{{classname}}} apiInstance = new {{{classname}}}(); {{{classname}}} apiInstance = new {{{classname}}}(defaultClient);
{{#allParams}} {{#allParams}}
{{{dataType}}} {{{paramName}}} = {{{example}}}; // {{{dataType}}} | {{{description}}} {{{dataType}}} {{{paramName}}} = {{{example}}}; // {{{dataType}}} | {{{description}}}
{{/allParams}} {{/allParams}}
@ -116,6 +114,9 @@ public class {{{classname}}}Example {
System.out.println(result);{{/returnType}} System.out.println(result);{{/returnType}}
} catch (ApiException e) { } catch (ApiException e) {
System.err.println("Exception when calling {{{classname}}}#{{{operationId}}}"); System.err.println("Exception when calling {{{classname}}}#{{{operationId}}}");
System.err.println("Status code: " + e.getCode());
System.err.println("Reason: " + e.getResponseBody());
System.err.println("Response headers: " + e.getResponseHeaders());
e.printStackTrace(); e.printStackTrace();
} }
} }

View File

@ -23,41 +23,50 @@ Method | HTTP request | Description
### Example ### Example
```java ```java
// Import classes:{{#hasAuthMethods}} // Import classes:
//import {{{invokerPackage}}}.ApiClient;{{/hasAuthMethods}} import {{{invokerPackage}}}.ApiClient;
//import {{{invokerPackage}}}.ApiException;{{#hasAuthMethods}} import {{{invokerPackage}}}.ApiException;
//import {{{invokerPackage}}}.Configuration; import {{{invokerPackage}}}.Configuration;{{#hasAuthMethods}}
//import {{{invokerPackage}}}.auth.*;{{/hasAuthMethods}} import {{{invokerPackage}}}.auth.*;{{/hasAuthMethods}}
//import {{{package}}}.{{{classname}}}; import {{{invokerPackage}}}.models.*;
import {{{package}}}.{{{classname}}};
{{#hasAuthMethods}} public class Example {
ApiClient defaultClient = Configuration.getDefaultApiClient(); public static void main(String[] args) {
{{#authMethods}}{{#isBasic}} ApiClient defaultClient = Configuration.getDefaultApiClient();
// Configure HTTP basic authorization: {{{name}}} defaultClient.setBasePath("{{{basePath}}}");
HttpBasicAuth {{{name}}} = (HttpBasicAuth) defaultClient.getAuthentication("{{{name}}}"); {{#hasAuthMethods}}
{{{name}}}.setUsername("YOUR USERNAME"); {{#authMethods}}{{#isBasic}}
{{{name}}}.setPassword("YOUR PASSWORD");{{/isBasic}}{{#isApiKey}} // Configure HTTP basic authorization: {{{name}}}
// Configure API key authorization: {{{name}}} HttpBasicAuth {{{name}}} = (HttpBasicAuth) defaultClient.getAuthentication("{{{name}}}");
ApiKeyAuth {{{name}}} = (ApiKeyAuth) defaultClient.getAuthentication("{{{name}}}"); {{{name}}}.setUsername("YOUR USERNAME");
{{{name}}}.setApiKey("YOUR API KEY"); {{{name}}}.setPassword("YOUR PASSWORD");{{/isBasic}}{{#isApiKey}}
// Uncomment the following line to set a prefix for the API key, e.g. "Token" (defaults to null) // Configure API key authorization: {{{name}}}
//{{{name}}}.setApiKeyPrefix("Token");{{/isApiKey}}{{#isOAuth}} ApiKeyAuth {{{name}}} = (ApiKeyAuth) defaultClient.getAuthentication("{{{name}}}");
// Configure OAuth2 access token for authorization: {{{name}}} {{{name}}}.setApiKey("YOUR API KEY");
OAuth {{{name}}} = (OAuth) defaultClient.getAuthentication("{{{name}}}"); // Uncomment the following line to set a prefix for the API key, e.g. "Token" (defaults to null)
{{{name}}}.setAccessToken("YOUR ACCESS TOKEN");{{/isOAuth}} //{{{name}}}.setApiKeyPrefix("Token");{{/isApiKey}}{{#isOAuth}}
{{/authMethods}} // Configure OAuth2 access token for authorization: {{{name}}}
{{/hasAuthMethods}} OAuth {{{name}}} = (OAuth) defaultClient.getAuthentication("{{{name}}}");
{{{name}}}.setAccessToken("YOUR ACCESS TOKEN");{{/isOAuth}}
{{/authMethods}}
{{/hasAuthMethods}}
{{{classname}}} apiInstance = new {{{classname}}}(); {{{classname}}} apiInstance = new {{{classname}}}(defaultClient);
{{#allParams}} {{#allParams}}
{{{dataType}}} {{{paramName}}} = {{{example}}}; // {{{dataType}}} | {{{description}}} {{{dataType}}} {{{paramName}}} = {{{example}}}; // {{{dataType}}} | {{{description}}}
{{/allParams}} {{/allParams}}
try { try {
{{#returnType}}{{{returnType}}} result = {{/returnType}}apiInstance.{{{operationId}}}({{#allParams}}{{{paramName}}}{{#hasMore}}, {{/hasMore}}{{/allParams}});{{#returnType}} {{#returnType}}{{{returnType}}} result = {{/returnType}}apiInstance.{{{operationId}}}({{#allParams}}{{{paramName}}}{{#hasMore}}, {{/hasMore}}{{/allParams}});{{#returnType}}
System.out.println(result);{{/returnType}} System.out.println(result);{{/returnType}}
} catch (ApiException e) { } catch (ApiException e) {
System.err.println("Exception when calling {{{classname}}}#{{{operationId}}}"); System.err.println("Exception when calling {{{classname}}}#{{{operationId}}}");
System.err.println("Status code: " + e.getCode());
System.err.println("Reason: " + e.getResponseBody());
System.err.println("Response headers: " + e.getResponseHeaders());
e.printStackTrace(); e.printStackTrace();
}
}
} }
``` ```
@ -82,5 +91,14 @@ Name | Type | Description | Notes
- **Content-Type**: {{#consumes}}{{{mediaType}}}{{#hasMore}}, {{/hasMore}}{{/consumes}}{{^consumes}}Not defined{{/consumes}} - **Content-Type**: {{#consumes}}{{{mediaType}}}{{#hasMore}}, {{/hasMore}}{{/consumes}}{{^consumes}}Not defined{{/consumes}}
- **Accept**: {{#produces}}{{{mediaType}}}{{#hasMore}}, {{/hasMore}}{{/produces}}{{^produces}}Not defined{{/produces}} - **Accept**: {{#produces}}{{{mediaType}}}{{#hasMore}}, {{/hasMore}}{{/produces}}{{^produces}}Not defined{{/produces}}
{{#responses.0}}
### HTTP response details
| Status code | Description | Response headers |
|-------------|-------------|------------------|
{{#responses}}
| **{{code}}** | {{message}} | {{#headers}} * {{baseName}} - {{description}} <br> {{/headers}}{{^headers.0}} - {{/headers.0}} |
{{/responses}}
{{/responses.0}}
{{/operation}} {{/operation}}
{{/operations}} {{/operations}}

View File

@ -808,6 +808,8 @@ public class ApiClient {
* Update query and header parameters based on authentication settings. * Update query and header parameters based on authentication settings.
* *
* @param authNames The authentications to apply * @param authNames The authentications to apply
* @param queryParams List of query parameters
* @param headerParams Map of header parameters
*/ */
protected void updateParamsForAuth(String[] authNames, List<Pair> queryParams, Map<String, String> headerParams) { protected void updateParamsForAuth(String[] authNames, List<Pair> queryParams, Map<String, String> headerParams) {
for (String authName : authNames) { for (String authName : authNames) {

View File

@ -4,6 +4,10 @@ package {{invokerPackage}};
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
{{#caseInsensitiveResponseHeaders}}
import java.util.Map.Entry;
import java.util.TreeMap;
{{/caseInsensitiveResponseHeaders}}
/** /**
* API response returned by API call. * API response returned by API call.
@ -30,7 +34,13 @@ public class ApiResponse<T> {
*/ */
public ApiResponse(int statusCode, Map<String, List<String>> headers, T data) { public ApiResponse(int statusCode, Map<String, List<String>> headers, T data) {
this.statusCode = statusCode; this.statusCode = statusCode;
this.headers = headers; {{#caseInsensitiveResponseHeaders}}
Map<String, List<String>> responseHeaders = new TreeMap<String, List<String>>(String.CASE_INSENSITIVE_ORDER);
for(Entry<String, List<String>> entry : headers.entrySet()){
responseHeaders.put(entry.getKey().toLowerCase(), entry.getValue());
}
{{/caseInsensitiveResponseHeaders}}
this.headers = {{#caseInsensitiveResponseHeaders}}responseHeaders{{/caseInsensitiveResponseHeaders}}{{^caseInsensitiveResponseHeaders}}headers{{/caseInsensitiveResponseHeaders}};
this.data = data; this.data = data;
} }

View File

@ -50,6 +50,15 @@ public class {{classname}} {
* @return {{returnType}} * @return {{returnType}}
{{/returnType}} {{/returnType}}
* @throws ApiException if fails to make API call * @throws ApiException if fails to make API call
{{#responses.0}}
* @http.response.details
<table summary="Response Details" border="1">
<tr><td> Status Code </td><td> Description </td><td> Response Headers </td></tr>
{{#responses}}
<tr><td> {{code}} </td><td> {{message}} </td><td> {{#headers}} * {{baseName}} - {{description}} <br> {{/headers}}{{^headers.0}} - {{/headers.0}} </td></tr>
{{/responses}}
</table>
{{/responses.0}}
{{#isDeprecated}} {{#isDeprecated}}
* @deprecated * @deprecated
{{/isDeprecated}} {{/isDeprecated}}
@ -75,10 +84,17 @@ public class {{classname}} {
{{#allParams}} {{#allParams}}
* @param {{paramName}} {{description}}{{#required}} (required){{/required}}{{^required}} (optional{{#defaultValue}}, default to {{.}}{{/defaultValue}}){{/required}} * @param {{paramName}} {{description}}{{#required}} (required){{/required}}{{^required}} (optional{{#defaultValue}}, default to {{.}}{{/defaultValue}}){{/required}}
{{/allParams}} {{/allParams}}
{{#returnType}}
* @return ApiResponse&lt;{{#returnType}}{{returnType}}{{/returnType}}{{^returnType}}Void{{/returnType}}&gt; * @return ApiResponse&lt;{{#returnType}}{{returnType}}{{/returnType}}{{^returnType}}Void{{/returnType}}&gt;
{{/returnType}}
* @throws ApiException if fails to make API call * @throws ApiException if fails to make API call
{{#responses.0}}
* @http.response.details
<table summary="Response Details" border="1">
<tr><td> Status Code </td><td> Description </td><td> Response Headers </td></tr>
{{#responses}}
<tr><td> {{code}} </td><td> {{message}} </td><td> {{#headers}} * {{baseName}} - {{description}} <br> {{/headers}}{{^headers.0}} - {{/headers.0}} </td></tr>
{{/responses}}
</table>
{{/responses.0}}
{{#isDeprecated}} {{#isDeprecated}}
* @deprecated * @deprecated
{{/isDeprecated}} {{/isDeprecated}}

View File

@ -0,0 +1,96 @@
{{>licenseInfo}}
package {{invokerPackage}};
import java.util.Map;
import java.util.List;
{{#caseInsensitiveResponseHeaders}}
import java.util.Map.Entry;
import java.util.TreeMap;
{{/caseInsensitiveResponseHeaders}}
{{>generatedAnnotation}}
public class ApiException extends{{#useRuntimeException}} RuntimeException {{/useRuntimeException}}{{^useRuntimeException}} Exception {{/useRuntimeException}}{
private int code = 0;
private Map<String, List<String>> responseHeaders = null;
private String responseBody = null;
public ApiException() {}
public ApiException(Throwable throwable) {
super(throwable);
}
public ApiException(String message) {
super(message);
}
public ApiException(String message, Throwable throwable, int code, Map<String, List<String>> responseHeaders, String responseBody) {
super(message, throwable);
this.code = code;
{{#caseInsensitiveResponseHeaders}}
Map<String, List<String>> headers = new TreeMap<String, List<String>>(String.CASE_INSENSITIVE_ORDER);
for(Entry<String, List<String>> entry : responseHeaders.entrySet()){
headers.put(entry.getKey().toLowerCase(), entry.getValue());
}
{{/caseInsensitiveResponseHeaders}}
this.responseHeaders = {{#caseInsensitiveResponseHeaders}}headers{{/caseInsensitiveResponseHeaders}}{{^caseInsensitiveResponseHeaders}}responseHeaders{{/caseInsensitiveResponseHeaders}};
this.responseBody = responseBody;
}
public ApiException(String message, int code, Map<String, List<String>> responseHeaders, String responseBody) {
this(message, (Throwable) null, code, responseHeaders, responseBody);
}
public ApiException(String message, Throwable throwable, int code, Map<String, List<String>> responseHeaders) {
this(message, throwable, code, responseHeaders, null);
}
public ApiException(int code, Map<String, List<String>> responseHeaders, String responseBody) {
this((String) null, (Throwable) null, code, responseHeaders, responseBody);
}
public ApiException(int code, String message) {
super(message);
this.code = code;
}
public ApiException(int code, String message, Map<String, List<String>> responseHeaders, String responseBody) {
this(code, message);
{{#caseInsensitiveResponseHeaders}}
Map<String, List<String>> headers = new TreeMap<String, List<String>>(String.CASE_INSENSITIVE_ORDER);
for(Entry<String, List<String>> entry : responseHeaders.entrySet()){
headers.put(entry.getKey().toLowerCase(), entry.getValue());
}
{{/caseInsensitiveResponseHeaders}}
this.responseHeaders = {{#caseInsensitiveResponseHeaders}}headers{{/caseInsensitiveResponseHeaders}}{{^caseInsensitiveResponseHeaders}}responseHeaders{{/caseInsensitiveResponseHeaders}};
this.responseBody = responseBody;
}
/**
* Get the HTTP status code.
*
* @return HTTP status code
*/
public int getCode() {
return code;
}
/**
* Get the HTTP response headers.
*
* @return A map of list of string
*/
public Map<String, List<String>> getResponseHeaders() {
return responseHeaders;
}
/**
* Get the HTTP response body.
*
* @return Response body in the form of string
*/
public String getResponseBody() {
return responseBody;
}
}

View File

@ -170,6 +170,15 @@
<goals> <goals>
<goal>jar</goal> <goal>jar</goal>
</goals> </goals>
<configuration>
<tags>
<tag>
<name>http.response.details</name>
<placement>a</placement>
<head>Http Response Details:</head>
</tag>
</tags>
</configuration>
</execution> </execution>
</executions> </executions>
</plugin> </plugin>
@ -226,6 +235,13 @@
<artifactId>jersey-client</artifactId> <artifactId>jersey-client</artifactId>
<version>${jersey-version}</version> <version>${jersey-version}</version>
</dependency> </dependency>
{{^supportJava6}}
<dependency>
<groupId>org.glassfish.jersey.inject</groupId>
<artifactId>jersey-hk2</artifactId>
<version>${jersey-version}</version>
</dependency>
{{/supportJava6}}
<dependency> <dependency>
<groupId>org.glassfish.jersey.media</groupId> <groupId>org.glassfish.jersey.media</groupId>
<artifactId>jersey-media-multipart</artifactId> <artifactId>jersey-media-multipart</artifactId>

View File

@ -4,6 +4,10 @@ package {{invokerPackage}};
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
{{#caseInsensitiveResponseHeaders}}
import java.util.Map.Entry;
import java.util.TreeMap;
{{/caseInsensitiveResponseHeaders}}
/** /**
* API response returned by API call. * API response returned by API call.
@ -30,7 +34,13 @@ public class ApiResponse<T> {
*/ */
public ApiResponse(int statusCode, Map<String, List<String>> headers, T data) { public ApiResponse(int statusCode, Map<String, List<String>> headers, T data) {
this.statusCode = statusCode; this.statusCode = statusCode;
this.headers = headers; {{#caseInsensitiveResponseHeaders}}
Map<String, List<String>> responseHeaders = new TreeMap<String, List<String>>(String.CASE_INSENSITIVE_ORDER);
for(Entry<String, List<String>> entry : headers.entrySet()){
responseHeaders.put(entry.getKey().toLowerCase(), entry.getValue());
}
{{/caseInsensitiveResponseHeaders}}
this.headers = {{#caseInsensitiveResponseHeaders}}responseHeaders{{/caseInsensitiveResponseHeaders}}{{^caseInsensitiveResponseHeaders}}headers{{/caseInsensitiveResponseHeaders}};
this.data = data; this.data = data;
} }

View File

@ -0,0 +1,96 @@
{{>licenseInfo}}
package {{invokerPackage}};
import java.util.Map;
import java.util.List;
{{#caseInsensitiveResponseHeaders}}
import java.util.Map.Entry;
import java.util.TreeMap;
{{/caseInsensitiveResponseHeaders}}
{{>generatedAnnotation}}
public class ApiException extends{{#useRuntimeException}} RuntimeException {{/useRuntimeException}}{{^useRuntimeException}} Exception {{/useRuntimeException}}{
private int code = 0;
private Map<String, List<String>> responseHeaders = null;
private String responseBody = null;
public ApiException() {}
public ApiException(Throwable throwable) {
super(throwable);
}
public ApiException(String message) {
super(message);
}
public ApiException(String message, Throwable throwable, int code, Map<String, List<String>> responseHeaders, String responseBody) {
super(message, throwable);
this.code = code;
{{#caseInsensitiveResponseHeaders}}
Map<String, List<String>> headers = new TreeMap<String, List<String>>(String.CASE_INSENSITIVE_ORDER);
for(Entry<String, List<String>> entry : responseHeaders.entrySet()){
headers.put(entry.getKey().toLowerCase(), entry.getValue());
}
{{/caseInsensitiveResponseHeaders}}
this.responseHeaders = {{#caseInsensitiveResponseHeaders}}headers{{/caseInsensitiveResponseHeaders}}{{^caseInsensitiveResponseHeaders}}responseHeaders{{/caseInsensitiveResponseHeaders}};
this.responseBody = responseBody;
}
public ApiException(String message, int code, Map<String, List<String>> responseHeaders, String responseBody) {
this(message, (Throwable) null, code, responseHeaders, responseBody);
}
public ApiException(String message, Throwable throwable, int code, Map<String, List<String>> responseHeaders) {
this(message, throwable, code, responseHeaders, null);
}
public ApiException(int code, Map<String, List<String>> responseHeaders, String responseBody) {
this((String) null, (Throwable) null, code, responseHeaders, responseBody);
}
public ApiException(int code, String message) {
super(message);
this.code = code;
}
public ApiException(int code, String message, Map<String, List<String>> responseHeaders, String responseBody) {
this(code, message);
{{#caseInsensitiveResponseHeaders}}
Map<String, List<String>> headers = new TreeMap<String, List<String>>(String.CASE_INSENSITIVE_ORDER);
for(Entry<String, List<String>> entry : responseHeaders.entrySet()){
headers.put(entry.getKey().toLowerCase(), entry.getValue());
}
{{/caseInsensitiveResponseHeaders}}
this.responseHeaders = {{#caseInsensitiveResponseHeaders}}headers{{/caseInsensitiveResponseHeaders}}{{^caseInsensitiveResponseHeaders}}responseHeaders{{/caseInsensitiveResponseHeaders}};
this.responseBody = responseBody;
}
/**
* Get the HTTP status code.
*
* @return HTTP status code
*/
public int getCode() {
return code;
}
/**
* Get the HTTP response headers.
*
* @return A map of list of string
*/
public Map<String, List<String>> getResponseHeaders() {
return responseHeaders;
}
/**
* Get the HTTP response body.
*
* @return Response body in the form of string
*/
public String getResponseBody() {
return responseBody;
}
}

View File

@ -126,15 +126,15 @@ if(hasProperty('target') && target == 'android') {
} }
dependencies { dependencies {
compile 'io.swagger:swagger-annotations:1.5.21' compile 'io.swagger:swagger-annotations:1.5.22'
compile 'com.squareup.okhttp3:okhttp:3.13.1' compile 'com.squareup.okhttp3:okhttp:3.14.2'
compile 'com.squareup.okhttp3:logging-interceptor:3.13.1' compile 'com.squareup.okhttp3:logging-interceptor:3.14.2'
compile 'com.google.code.gson:gson:2.8.5' compile 'com.google.code.gson:gson:2.8.5'
compile 'io.gsonfire:gson-fire:1.8.3' compile 'io.gsonfire:gson-fire:1.8.3'
{{#hasOAuthMethods}} {{#hasOAuthMethods}}
compile group: 'org.apache.oltu.oauth2', name: 'org.apache.oltu.oauth2.client', version: '1.0.1' compile group: 'org.apache.oltu.oauth2', name: 'org.apache.oltu.oauth2.client', version: '1.0.1'
{{/hasOAuthMethods}} {{/hasOAuthMethods}}
compile group: 'org.apache.commons', name: 'commons-lang3', version: '3.8.1' compile group: 'org.apache.commons', name: 'commons-lang3', version: '3.9'
{{#joda}} {{#joda}}
compile 'joda-time:joda-time:2.9.9' compile 'joda-time:joda-time:2.9.9'
{{/joda}} {{/joda}}

View File

@ -9,11 +9,11 @@ lazy val root = (project in file(".")).
publishArtifact in (Compile, packageDoc) := false, publishArtifact in (Compile, packageDoc) := false,
resolvers += Resolver.mavenLocal, resolvers += Resolver.mavenLocal,
libraryDependencies ++= Seq( libraryDependencies ++= Seq(
"io.swagger" % "swagger-annotations" % "1.5.21", "io.swagger" % "swagger-annotations" % "1.5.22",
"com.squareup.okhttp3" % "okhttp" % "3.13.1", "com.squareup.okhttp3" % "okhttp" % "3.14.2",
"com.squareup.okhttp3" % "logging-interceptor" % "3.13.1", "com.squareup.okhttp3" % "logging-interceptor" % "3.14.2",
"com.google.code.gson" % "gson" % "2.8.5", "com.google.code.gson" % "gson" % "2.8.5",
"org.apache.commons" % "commons-lang3" % "3.8.1", "org.apache.commons" % "commons-lang3" % "3.9",
{{#hasOAuthMethods}} {{#hasOAuthMethods}}
"org.apache.oltu.oauth2" % "org.apache.oltu.oauth2.client" % "1.0.1", "org.apache.oltu.oauth2" % "org.apache.oltu.oauth2.client" % "1.0.1",
{{/hasOAuthMethods}} {{/hasOAuthMethods}}

View File

@ -298,9 +298,9 @@
<maven.compiler.target>${java.version}</maven.compiler.target> <maven.compiler.target>${java.version}</maven.compiler.target>
<gson-fire-version>1.8.3</gson-fire-version> <gson-fire-version>1.8.3</gson-fire-version>
<swagger-core-version>1.5.21</swagger-core-version> <swagger-core-version>1.5.21</swagger-core-version>
<okhttp-version>3.14.0</okhttp-version> <okhttp-version>3.14.2</okhttp-version>
<gson-version>2.8.5</gson-version> <gson-version>2.8.5</gson-version>
<commons-lang3-version>3.8.1</commons-lang3-version> <commons-lang3-version>3.9</commons-lang3-version>
{{#joda}} {{#joda}}
<jodatime-version>2.9.9</jodatime-version> <jodatime-version>2.9.9</jodatime-version>
{{/joda}} {{/joda}}

View File

@ -94,6 +94,11 @@
<artifactId>springfox-swagger-ui</artifactId> <artifactId>springfox-swagger-ui</artifactId>
<version>${springfox-version}</version> <version>${springfox-version}</version>
</dependency> </dependency>
<dependency>
<groupId>javax.xml.bind</groupId>
<artifactId>jaxb-api</artifactId>
<version>2.2.11</version>
</dependency>
{{/useSpringfox}} {{/useSpringfox}}
{{^useSpringfox}} {{^useSpringfox}}
<dependency> <dependency>

View File

@ -137,6 +137,16 @@
<artifactId>spring-web</artifactId> <artifactId>spring-web</artifactId>
<version>${spring-version}</version> <version>${spring-version}</version>
</dependency> </dependency>
<dependency>
<groupId>javax.annotation</groupId>
<artifactId>javax.annotation-api</artifactId>
<version>1.3.2</version>
</dependency>
<dependency>
<groupId>javax.xml.bind</groupId>
<artifactId>jaxb-api</artifactId>
<version>2.2.11</version>
</dependency>
{{#useSpringfox}} {{#useSpringfox}}
<!--SpringFox dependencies--> <!--SpringFox dependencies-->
<dependency> <dependency>

View File

@ -1 +1 @@
{{#isQueryParam}}{{#useBeanValidation}}{{>beanValidationQueryParams}}{{/useBeanValidation}}@ApiParam(value = "{{{description}}}"{{#required}}, required = true{{/required}}{{#allowableValues}}, allowableValues = "{{#values}}{{{.}}}{{^-last}}, {{/-last}}{{#-last}}{{/-last}}{{/values}}"{{/allowableValues}}{{^isContainer}}{{#defaultValue}}, defaultValue = {{^isString}}"{{/isString}}{{#isString}}{{#isEnum}}"{{/isEnum}}{{/isString}}{{{defaultValue}}}{{^isString}}"{{/isString}}{{#isString}}{{#isEnum}}"{{/isEnum}}{{/isString}}{{/defaultValue}}{{/isContainer}}) {{#useBeanValidation}}@Valid{{/useBeanValidation}} @RequestParam(value = "{{baseName}}"{{#required}}, required = true{{/required}}{{^required}}, required = false{{/required}}{{^isContainer}}{{#defaultValue}}, defaultValue={{^isString}}"{{/isString}}{{#isString}}{{#isEnum}}"{{/isEnum}}{{/isString}}{{{defaultValue}}}{{^isString}}"{{/isString}}{{#isString}}{{#isEnum}}"{{/isEnum}}{{/isString}}{{/defaultValue}}{{/isContainer}}) {{>optionalDataType}} {{paramName}}{{/isQueryParam}} {{#isQueryParam}}{{#useBeanValidation}}{{>beanValidationQueryParams}}{{/useBeanValidation}}@ApiParam(value = "{{{description}}}"{{#required}}, required = true{{/required}}{{#allowableValues}}, allowableValues = "{{#values}}{{{.}}}{{^-last}}, {{/-last}}{{#-last}}{{/-last}}{{/values}}"{{/allowableValues}}{{^isContainer}}{{#defaultValue}}, defaultValue = {{^isString}}"{{/isString}}{{#isString}}{{#isEnum}}"{{/isEnum}}{{/isString}}{{{defaultValue}}}{{^isString}}"{{/isString}}{{#isString}}{{#isEnum}}"{{/isEnum}}{{/isString}}{{/defaultValue}}{{/isContainer}}) {{#useBeanValidation}}@Valid{{/useBeanValidation}}{{^isModel}} @RequestParam(value = "{{baseName}}"{{#required}}, required = true{{/required}}{{^required}}, required = false{{/required}}{{^isContainer}}{{#defaultValue}}, defaultValue={{^isString}}"{{/isString}}{{#isString}}{{#isEnum}}"{{/isEnum}}{{/isString}}{{{defaultValue}}}{{^isString}}"{{/isString}}{{#isString}}{{#isEnum}}"{{/isEnum}}{{/isString}}{{/defaultValue}}{{/isContainer}}){{/isModel}} {{>optionalDataType}} {{paramName}}{{/isQueryParam}}

View File

@ -18,7 +18,8 @@ Module system
To build an compile the flow typed sources to javascript use: To build an compile the flow typed sources to javascript use:
``` ```
npm install npm install
npm run build # The dependency `babel-preset-react-app` requires that you specify `NODE_ENV` or `BABEL_ENV` environment variables
env BABEL_ENV={YOUR_ENV} npm run build
``` ```
### Publishing ### Publishing

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