Compare commits

...

103 Commits

Author SHA1 Message Date
William Cheng
4e511d9c99 test py libs with experimental 2020-09-28 09:59:45 +08:00
William Cheng
7a98580f45 Merge branch 'master' of https://github.com/openapitools/openapi-generator 2020-09-28 09:35:24 +08:00
William Cheng
b72d5ca81e comment out php test to fix travis failure 2020-09-28 09:29:36 +08:00
henryh-force
ec815ca33a [Apex] better handling of different content-type in the response (#7515)
* PR7500

* update samples

Co-authored-by: William Cheng <wing328hk@gmail.com>
2020-09-27 21:10:14 +08:00
Dalibor Karlović
2c59f1dc8c [php] Small tweaks for php generator (#7376) 2020-09-27 12:42:51 +03:00
Grigory Entin
a5ee2e0454 [Swift5] Fixed spelling for promise. (#7516) 2020-09-27 16:13:21 +08:00
Jim Schubert
cb4b03fcf3 [Core, HTML2] Rendered docs are incomplete (#7510)
Co-authored-by: Malachi Jones <malachi.jones@metaswitch.com>
2020-09-25 09:07:18 -04:00
Hui Yu
f608803a40 [C][Client]Support data callback function (#7467) 2020-09-25 20:34:17 +08:00
翠 / green
9ace82ae14 [typescript-axios] replace optional chaining (#7476)
To avoid requiring TypeScript above 3.7.2.
refs #7455
2020-09-25 14:27:29 +02:00
翠 / green
5472943134 [typescript-axios] fix refining query (#7475) 2020-09-25 14:01:04 +02:00
Ghufran Zahidi
d6bfecf2ef [powershell] Updated the Api doc with httpsiging script snippet. (#7499)
* Added the httpsigning code snippet for api doc

* Updated the sample

* update samples

Co-authored-by: William Cheng <wing328hk@gmail.com>
2020-09-25 16:54:14 +08:00
Hippolyte HENRY
9ba943318a [go][client] Fix API docs example generation (#7489)
* [go][client] Fix API docs example

* Generate samples
2020-09-25 14:45:18 +08:00
Jim Schubert
f3fbc7d782 [ci][test] Fix samples (#7509) 2020-09-24 23:42:04 -04:00
Marvin1912
5f3d974a08 [bug][Java] Honor instantiationMap for default values for array, map, set (#4982)
Co-authored-by: Jim Schubert <james.schubert@gmail.com>
2020-09-24 23:25:13 -04:00
Aidan Hobson Sayers
9778d970ac Fix stringifying of ~= (#7460)
Fixes #4069
2020-09-25 10:48:57 +08:00
William Cheng
5dffbabc74 minor formatting change (#7503) 2020-09-25 10:16:26 +08:00
Hippolyte HENRY
7b1563326a [ruby] Fix generation when generateAliasAsModel is enabled (#7419) 2020-09-24 22:08:57 -04:00
Jim Schubert
49760f7a34 [sonar][ci] Fixes some new recommended "bug" fixes found via Sonar (#7508) 2020-09-24 22:02:11 -04:00
William Cheng
596bbb9c58 Add option to set recursion limit (#7491)
* add option to set recursion limit

* fix test failure

* update doc

* add tests

* add missing import

* rename option to recursionLimit
2020-09-24 11:47:22 -07:00
William Cheng
29ca272a95 regenerate java pkmst petstore samples (#7502) 2020-09-25 00:25:23 +08:00
William Cheng
5ebf26e0d2 fix issue without http signature auth (#7504) 2020-09-24 23:56:50 +08:00
Jiri Kuncar
bc799b2488 [ruby] Support for per-operation servers (#7415)
* Support server configuration per operation

* regenerated+tests

* base_url fix

* support not templated urls

* revert update of ruby docs
2020-09-24 11:21:43 -04:00
William Cheng
7dd4fd1d98 Add a link to react native tutorial (#7505)
Add a link to react native tutorial
2020-09-24 22:24:56 +08:00
Thomas Beckmann
bdc964a6c1 update of Objective-C model-body.mustache to support discriminator.mappedModels (#7471)
Co-authored-by: Thomas Beckmann <thomas.beckmann@mway.io>
2020-09-24 17:44:14 +08:00
William Cheng
6612c16624 update samples 2020-09-24 16:37:20 +08:00
Jim Schubert
874c2a19d8 [ci] Sonar bug fixes (#7497)
* Fixing java:S3599 - Avoid double brace initializer

Because Double Brace Initialization (DBI) creates an anonymous class with a
reference to the instance of the owning object, its use can lead to memory
leaks if the anonymous inner class is returned and held by other objects. Even
when there's no leak, DBI is so obscure that it's bound to confuse most
maintainers.

* Fix incorrect List.contains typed check

* Avoid potential NPE in DefaultCodegen

* [fsharp] Remove unused boolean and log

* Fix potential NPE in Haskell http client

* Fix potential bugs in JavaCXFExtServerCodegen, found by static analysis
2020-09-24 00:20:40 -04:00
Ghufran Zahidi
94ed8187f9 fixed the backslash issue (#7492) 2020-09-24 10:07:19 +08:00
Ghufran Zahidi
56c9f0dc1e Fix the range check condition (#7482) 2020-09-24 10:02:04 +08:00
Jim Schubert
6e937ba9f9 [batch] Option to clean files before generation (#7465) 2020-09-23 08:50:23 -04:00
Jim Schubert
1716ee3154 [java][groovy] Fix mangled src paths in outputs on Windows (#7487) 2020-09-23 00:03:37 -04:00
William Cheng
d2aabc5f80 remove haskell stack installation in shippable ci (#7481) 2020-09-23 11:49:03 +08:00
William Cheng
8c78f13a41 remove hardcoded PetApi (#7483) 2020-09-22 11:45:29 -07:00
William Cheng
04b39cc86b remove SWGApiResponse.m (not used) (#7478) 2020-09-22 22:34:48 +08:00
William Cheng
2157d526e1 update samples 2020-09-22 20:45:22 +08:00
翠 / green
a5fcb17416 [typescript-axios] support "x-enum-descriptions" (#7477)
refs #1693 #1752
2020-09-22 12:55:09 +02:00
William Cheng
96bba3769b switch to another spec with more oneOf def (#7470) 2020-09-22 08:50:57 +08:00
William Cheng
f8c20c22e1 remove old csharp files under integration tests folder (#7466) 2020-09-22 07:42:41 +08:00
Peter Somogyvari
27680214fd feat(typescript-axios): injectable FormData (#7455)
Signed-off-by: Peter Somogyvari <peter.metz@unarin.com>
2020-09-21 09:07:10 +02:00
William Cheng
7fa02ee5f0 use typeMapping instead of postProcessParameter (#7457) 2020-09-21 15:05:43 +08:00
Aidan Hobson Sayers
be151fca64 Fix Rust codegen for AnyType (#7461) 2020-09-21 13:36:43 +08:00
William Cheng
985c4b36a7 [Ruby] fix port in the Ruby client (#7464)
* fix port in ruby client

* use serverPort instead

* update samples, skip if port is 80
2020-09-21 13:23:45 +08:00
Jim Schubert
a29d9a9ff4 [samples] Regenerate 2020-09-20 23:27:48 -04:00
Sebastien Rosset
4f27939879 [core] Add model cache to speed up code generation (#7250) 2020-09-20 22:15:32 -04:00
William Cheng
8cd503f194 Add a link to a post about angular reactiveforms (#7463) 2020-09-21 10:04:39 +08:00
Philipp Paris
c7d5275b62 [java] jaxrs (all) add usetags option (#6130)
* Adds "useTags" option to all jaxrs code generators (AbstractJAXRSServerCodegen):
  - jaxrs-jersey
  - jaxrs-spec
  - jaxrs-cxf-cdi
  - jaxrs-resteasy
  - jaxrs-cxf
  - jaxrs-cxf-extended
  - java-msf4j
  - jaxrs-resteasy-eap
* jaxrs-spec
  - Changed handling of root paths: e.g "/:", "/{id}:" to simplify code and create a more consistent behaviour
    -- old: use tag for classname
    -- new: use tag only if useTags is enabled, use "DefaultApi" if not
* @path class level annotation
  - for all generators above and the microprofile generator (uses same jaxrs postprocessing)
  - extended the "commonPath" to contain more than only the root path if possible
  - e.g. "/group1/subgroup1/op1" -> "/group1/subgroup1" is moved to class level annotation
2020-09-20 21:18:07 -04:00
Jim Schubert
3ca6bc2518 [sonar] Java 11, use -nsu, exclude maven/online projects (#7459) 2020-09-20 16:02:29 -04:00
spacether
35d42728d9 Adds free form model generation in python-experimental (#7373)
* Adds free form model generation in python-experimental

* Adds hasValidation property to codegenModel

* Adds separate variable val

* Samples regenerated

* Updates test_some_object.py

* Adds two more boolean conditions

* Runs ensure up to date

* Updates tests to check that models are or are not generated

* Removes unused import

* Updates model names in java test

* Removes unneeded test

* Cleans up tests
2020-09-20 10:55:54 -07:00
William Cheng
77f24a4234 [C#][netcore] replace tabs with 4-space (#7456)
* replace tab with 4-space

* add space after if
2020-09-21 00:08:31 +08:00
Yuriy Belenko
5675d5fe61 Fix bug when variables key doesn't exist (#7429) 2020-09-20 20:49:00 +08:00
Francesco Guardiani
80bef2f79a Update Vert.x Web template to Vert.x 4 (#7364)
* Update Vert.x Web template to Vert.x 4

Signed-off-by: Francesco Guardiani <francescoguard@gmail.com>

* Bad pom

Signed-off-by: Francesco Guardiani <francescoguard@gmail.com>

* Bad pom 2

Signed-off-by: Francesco Guardiani <francescoguard@gmail.com>

* Stick to Java 8

Signed-off-by: Francesco Guardiani <francescoguard@gmail.com>

* Latest vert.x 4

Signed-off-by: Francesco Guardiani <francescoguard@gmail.com>
2020-09-19 15:43:08 +08:00
William Cheng
ea559b5e20 [C#][NetCore] add multi-server support (#7433)
* multi server support in C# netcore clients

* switch to IReadOnlyDictionary

* minor fixes, add tests
2020-09-19 15:07:12 +08:00
Ghufz
92f7a306a1 [csharp-netcore]Http signing for csharp-netcore sdk (#7437)
* HTTPSigning implementation for CSharpSDK

* Updated the sample for HTTPSigning

* Updated the sample2 for HTTPSigning

* update samples

* HTTPSigning_For_Async

* update samples

Co-authored-by: William Cheng <wing328hk@gmail.com>
2020-09-19 12:09:35 +08:00
dtiller
3f7a3f2b59 [TYPO] [WEBCLIENT] Issue 7425: Fixed comments that referred to RestTemplate. (#7445)
* Issue 7425: Fixed comments that referred to RestTemplate.

* Ran genreate-samples.sh

* Re-ran generate-samples.sh against all configs.

* update samples

Co-authored-by: William Cheng <wing328hk@gmail.com>
2020-09-19 12:07:35 +08:00
Jim Schubert
29ed2342e5 Update sonar.yml
Add a 'sonar' branch to sonar scanning
2020-09-18 21:35:38 -04:00
William Cheng
874daad7e7 delete oudated objc files (#7449) 2020-09-18 18:27:33 +08:00
William Cheng
ef42977097 remove old test, regenerate js clients (#7448) 2020-09-18 14:14:23 +08:00
Adam Gray
7424489607 Fix scala-sttp enum generation (#7432)
* #7431 fix sttp enum generation

* avoid unnecessary sample changes
2020-09-18 10:59:45 +08:00
William Cheng
9754748321 [Perl] clean up old files and regenerate Perl petstore clients (#7439)
* clean up old files and regenrate perl petstore

* update samples
2020-09-18 10:30:32 +08:00
William Cheng
bfe4a7ff87 rename ts axios test (#7442) 2020-09-18 10:23:52 +08:00
Mahir Kothary
ca5d384081 [bug][typescript] Fix node client generator import file paths (#7410) 2020-09-17 21:46:39 -04:00
William Cheng
620f8db3d6 Add a link to PS blog post (#7444) 2020-09-17 18:56:59 +08:00
Fabio Mazzone
6a4aed91ca [javascript][client] Add gitignore to template (#7438)
* [javascript][client] add gitignore template file

* [javascript][client] update samples
2020-09-17 17:18:27 +08:00
dtiller
6909c888d2 [cli] Batch: support multiple/nested !include directive (#7354)
Co-authored-by: Jim Schubert <james.schubert@gmail.com>
2020-09-16 22:45:26 -04:00
Ella
bb00d88283 [kotlin] Fix optional header params in openhttp client (#7341)
This commit adjusts the kotlin openhttp api template to ignore null headers when building the request rather than convert them to "null" string
2020-09-16 22:09:38 -04:00
Nicholas Muesch
32c591d9a7 Support multiple api keys in python example documentation (#7417)
* Support multiple api keys in config option

* Regenerate samples

* Update rest of examples
2020-09-15 13:40:48 -07:00
Slavek Kabrda
be40dbe540 [Go][client] Re-add deleted model template files (#7423)
* [Go][client] Re-add deleted model template files

* Regenerate samples
2020-09-15 22:25:45 +08:00
William Cheng
c04d9cd59a rename debugging variables (#7422) 2020-09-15 21:25:52 +08:00
William Cheng
c44865279a replace spaces with tabs (#7421) 2020-09-15 18:13:07 +08:00
William Cheng
0b6229607f Add a link to Instana Blog (#7420) 2020-09-15 17:07:10 +08:00
Hippolyte HENRY
8dd3e561fa Use canonical path for template dir (#7388) 2020-09-14 12:22:14 -04:00
Gmtstephane
4e05912ae7 [GO][SERVER] Implement response code (#7397)
* Feature(template) add response with status code generation

* Generate Samples

* update samples

Co-authored-by: William Cheng <wing328hk@gmail.com>
2020-09-14 23:14:53 +08:00
spacether
8556cb8d71 Adds fix for issue 7372 (#7383) 2020-09-14 17:18:43 +08:00
typhoon2k
0173acd1d3 Fix package declaration (https://github.com/OpenAPITools/openapi-generator/issues/7122). (#7395) 2020-09-14 16:59:49 +08:00
Jim Schubert
bf0bd29ef1 [core][feature] User custom added templates (#7366) 2020-09-12 18:09:59 -04:00
Jason Lee
1a709a731b [Java] add cli option to ignore anyOf in enum (#4498)
Co-authored-by: Jim Schubert <james.schubert@gmail.com>
2020-09-12 18:09:39 -04:00
William Cheng
8fad36c898 [Go] minor format change, deprecate "withGoCodegenComment" option (#7375)
* use tab in comment, remove withGoCodegenComment

* deprecated option
2020-09-12 22:05:10 +08:00
Falanwe
634e3eb838 [cpp-ue4] add support for Content-Type containing charset (#7379) 2020-09-12 22:04:45 +08:00
Jean-François Côté
09200eb04e Update the for play 2.7 (#7398)
* Fix the new package that deal with Configuration (the old one is depecrated)

* First version to support Play Framework 2.7

* Fix small problems that prevent compilation of each samples. Now everything is compiling perfectly
2020-09-12 22:01:56 +08:00
Jim Schubert
684b77166b [docs] Add notes on Windows classpath modification (#7404) 2020-09-11 21:42:18 -04:00
William Cheng
0a2ef5a725 [C#][netcore] better support for additional properties in the payload (#7396)
* add OpenAPIAdditionalPropertiesConverter

* fix buges

* fix writeJson

* better code comment

* move converter to model

* use JsonExtensionData

* update hashcode, equal, tostring and more

* update samples
2020-09-12 01:39:19 +08:00
Ghufz
00e20ffb2c Fix the ECDSA signature issue for PowerShellSDK (#7386)
* Fix the ECDSA signature issue for PowerShellSDK

* updated the sample for ECDSA HTTPSigning

* fix the sample doc
2020-09-11 12:35:44 +08:00
Jean-François Côté
df441fe2ee Fix the new package that deal with Configuration (the old one is depecrated) (#7391) 2020-09-11 12:11:37 +08:00
William Cheng
f396da4c7e update vonage logo (#7387) 2020-09-10 18:53:45 +08:00
Jim Schubert
1eb8c2991d [gradle][plugin] Fix tests (#7384)
Tests running under Gradle 5.6.4 were breaking due to a change in
informational output. It's not clear when this was introduced, but it
looks like the upgrade to Gradle 5.6.4 may have stopped running tests
during builds.
2020-09-09 23:42:33 -04:00
Andrey Mochalov
4d8ac0e055 [typescript] Fix incorrect enum literal case (#7378)
* Fix incorrect enum values for typescript clients

* Fix incorrect enum values for typescript clients

* Fix incorrect enum values for typescript clients
2020-09-09 15:58:45 +02:00
JR Andreassen
37de486c43 Rust reqwest/api_mustache Missing api Vec in parameter (#7049)
* Rust reqwest/api_mustache Missing api Vec in parameter

Not using #isListContainer in parameters

* incorrect value for supportAsync

supportAsync set to "false" should be false

* Sample updates for CI

* Fixed Double Vec

Only check for special case...  "dataType" case includes Vec

* update samples

* remove old files

Co-authored-by: William Cheng <wing328hk@gmail.com>
2020-09-09 21:56:31 +08:00
Michael Wirth
7b6cc2032a [kotlin] Fix imports of generated class (#7314) 2020-09-08 20:56:48 -04:00
sbu
e7f83595e5 Properly decode $ref (#7191)
* Properly decode $ref
fixes #5720

* Specify decoding encoding

* Nicer syntax

* UTF-8 typo

* Unescape special characters

* Change order of unescaping to prevent escaped sequences by accident

* Comment for special decoding

Co-authored-by: Jim Schubert <james.schubert@gmail.com>

* Add unit test for simple ref decoding

Co-authored-by: Jim Schubert <james.schubert@gmail.com>
2020-09-08 23:12:56 +08:00
William Cheng
67ba67ef96 fix typo, update caption 2020-09-08 18:25:16 +08:00
Ramanth Addala
c39aef2a79 feat(r): retry configuration for status codes (#5925)
* feat(r): retry configuration for status codes

* fix(r) : fixing review comments
2020-09-08 14:34:32 +08:00
Gichan Im
f9514705a1 [json][codegen] Add option: outputFileName (#7348) 2020-09-07 15:29:47 +08:00
Ghufz
7ac7974ef5 RSACng class is not supported on linux replacing it by RSA (#7349)
* RSACng class is not supported on linux replacing it by RSA

* update PS samples

Co-authored-by: William Cheng <wing328hk@gmail.com>
2020-09-07 15:24:36 +08:00
Pete Kruskall
089e1f7271 Adds cookie auth support to ApiKeyAuth in dart2 templates (#7346)
* Adds cookie auth support to dart2 templates

* Updating pet store sample templates
2020-09-06 22:54:46 +08:00
Jim Schubert
9a6e3fa74a [js][flowtype] Bump lodash from 4.17.15 to 4.17.19 (#7359)
Bumps [lodash](https://github.com/lodash/lodash) from 4.17.15 to 4.17.19.
- [Release notes](https://github.com/lodash/lodash/releases)
- [Commits](https://github.com/lodash/lodash/compare/4.17.15...4.17.19)
2020-09-06 22:53:52 +08:00
Markus Wandersee
06434fcfce Bugfix swift5 code generation 2966 (#7301)
* Bugfix StackOverflow Crash in Swift5 Code Generation (#2966)

* Bugfix StackOverflow Crash in Swift5 Code Generation (#2966)

* Bugfix StackOverflow Crash in Swift5 Code Generation (#2966)
2020-09-06 22:05:16 +08:00
spacether
681e821b71 Syncs validation properties for arraymodels (#7357)
* Syncs validation properties for arraymodels

* Adds arrayModelHasValidation test
2020-09-05 18:02:00 -07:00
Ryan Rishi
2d5b2726d0 Subclass Python exceptions (#7321)
* Subclass Python exceptions:
- UnauthorizedException (401)
- ForbiddenException (403)
- NotFoundException (404)
- ServiceException [500 - 599]

Fixes #2151

* add generated sample code

* use Python 2 flavor inheritance

* regenerate samples
2020-09-05 10:22:04 -07:00
spacether
b38968456a Adds fix for issue7262 and a test of it (#7328)
* Adds fix for issue7262 and a test of it

* Updates inline schema to not include properties

* Adds null check of discriminator

* Updates issue sample file
2020-09-05 08:51:51 -07:00
William Cheng
dd42e0e428 add spacether to pom developer section (#7355) 2020-09-05 23:48:47 +08:00
Hui Yu
0e2e031ece [C][Client][Clang Static Analyzer] Fix uninitialized argument value for valueHeader_ and valueForm_ (#7332) 2020-09-04 21:37:31 +08:00
Robin Eggenkamp
5e512e8aa4 Remove duplicate jackson-datatype-jsr310 dependency (#7338) 2020-09-04 21:35:13 +08:00
Falanwe
662c77a283 [cpp-ue4] add support for empty response (#7333) 2020-09-04 21:32:29 +08:00
William Cheng
2fd23f505e Prepare 5.0.0-SNAPSHOT (#7347)
* Revert "Prepare 5.0.0-beta2 release (#7345)"

This reverts commit 212b4f7847.

* update readme
2020-09-04 15:31:54 +08:00
1795 changed files with 61979 additions and 24101 deletions

View File

@@ -11,8 +11,8 @@ assignees: ''
- [ ] Have you provided a full/minimal spec to reproduce the issue?
- [ ] Have you validated the input using an OpenAPI validator ([example](https://apidevtools.org/swagger-parser/online/))?
- [ ] Have you [tested with the latest master](https://github.com/OpenAPITools/openapi-generator/wiki/FAQ#how-to-test-with-the-latest-master-of-openapi-generator) to confirm the issuue still exists?
- [ ] Have you search for related issues/PRs?
- [ ] Have you [tested with the latest master](https://github.com/OpenAPITools/openapi-generator/wiki/FAQ#how-to-test-with-the-latest-master-of-openapi-generator) to confirm the issue still exists?
- [ ] Have you searched for related issues/PRs?
- [ ] What's the actual output vs expected output?
- [ ] [Optional] Sponsorship to speed up the bug fix or feature request ([example](https://github.com/OpenAPITools/openapi-generator/issues/6178))

View File

@@ -4,6 +4,7 @@ on:
branches:
- master
- '[4-9]+.[0-9]+.x'
- sonar
jobs:
build:
@@ -12,13 +13,13 @@ jobs:
steps:
- uses: actions/checkout@v1
- name: Set up JDK 1.8
- name: Set up JDK 11
uses: actions/setup-java@v1
with:
java-version: 1.8
java-version: 11
- name: Compile with Maven
run: mvn clean package jacoco:report
run: mvn -B -q clean install jacoco:report
- name: Jacoco Aggregate
run: mvn jacoco:report-aggregate
- name: Publish to Sonar
run: mvn -B -q sonar:sonar -Dsonar.projectKey=OpenAPITools_openapi-generator -Dsonar.organization=openapitools -Dsonar.host.url=https://sonarcloud.io -Dsonar.login=${{ secrets.SONAR_LOGIN }} -Dsonar.branch.name=${GITHUB_REF##*/}
run: mvn -B -q -nsu sonar:sonar -Dsonar.projectKey=OpenAPITools_openapi-generator -Dsonar.organization=openapitools -Dsonar.host.url=https://sonarcloud.io -Dsonar.login=${{ secrets.SONAR_LOGIN }} -Dsonar.branch.name=${GITHUB_REF##*/}

View File

@@ -103,7 +103,8 @@ The OpenAPI Specification has undergone 3 revisions since initial creation in 20
| 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/) | TBD | Major release with breaking changes (no fallback) |
| 5.0.0-beta2 (upcoming beta release) [SNAPSHOT](https://oss.sonatype.org/content/repositories/snapshots/org/openapitools/openapi-generator-cli/5.0.0-SNAPSHOT/) | 30.07.2020 | Major beta release with breaking changes (no fallback) |
| 5.0.0-beta3 (upcoming beta release) [SNAPSHOT](https://oss.sonatype.org/content/repositories/snapshots/org/openapitools/openapi-generator-cli/5.0.0-SNAPSHOT/) | 01.11.2020 | Major beta release with breaking changes (no fallback) |
| [5.0.0-beta2](https://github.com/OpenAPITools/openapi-generator/releases/tag/v5.0.0-beta2) (latest beta release) | 04.09.2020 | Major beta release with breaking changes (no fallback) |
| [5.0.0-beta](https://github.com/OpenAPITools/openapi-generator/releases/tag/v5.0.0-beta) (latest beta release) | 30.06.2020 | Major beta release with breaking changes (no fallback) |
| [4.3.1](https://github.com/OpenAPITools/openapi-generator/releases/tag/v4.3.1) (latest stable release) | 06.05.2020 | Patch release (enhancements, bug fixes, etc) |
@@ -161,16 +162,16 @@ See the different versions of the [openapi-generator-cli](https://mvnrepository.
<!-- 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):
JAR location: `https://repo1.maven.org/maven2/org/openapitools/openapi-generator-cli/5.0.0-beta/openapi-generator-cli-5.0.0-beta.jar`
JAR location: `https://repo1.maven.org/maven2/org/openapitools/openapi-generator-cli/5.0.0-beta2/openapi-generator-cli-5.0.0-beta2.jar`
For **Mac/Linux** users:
```sh
wget https://repo1.maven.org/maven2/org/openapitools/openapi-generator-cli/5.0.0-beta/openapi-generator-cli-5.0.0-beta.jar -O openapi-generator-cli.jar
wget https://repo1.maven.org/maven2/org/openapitools/openapi-generator-cli/5.0.0-beta2/openapi-generator-cli-5.0.0-beta2.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.
```
Invoke-WebRequest -OutFile openapi-generator-cli.jar https://repo1.maven.org/maven2/org/openapitools/openapi-generator-cli/5.0.0-beta/openapi-generator-cli-5.0.0-beta.jar
Invoke-WebRequest -OutFile openapi-generator-cli.jar https://repo1.maven.org/maven2/org/openapitools/openapi-generator-cli/5.0.0-beta2/openapi-generator-cli-5.0.0-beta2.jar
```
After downloading the JAR, run `java -jar openapi-generator-cli.jar help` to show the usage.
@@ -392,10 +393,10 @@ openapi-generator version
```
<!-- RELEASE_VERSION -->
Or install a particular OpenAPI Generator version (e.g. v5.0.0-beta):
Or install a particular OpenAPI Generator version (e.g. v5.0.0-beta2):
```sh
npm install @openapitools/openapi-generator-cli@cli-5.0.0-beta -g
npm install @openapitools/openapi-generator-cli@cli-5.0.0-beta2 -g
```
Or install it as dev-dependency:
@@ -419,7 +420,7 @@ 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`)
<!-- RELEASE_VERSION -->
You can also download the JAR (latest release) directly from [maven.org](https://repo1.maven.org/maven2/org/openapitools/openapi-generator-cli/5.0.0-beta/openapi-generator-cli-5.0.0-beta.jar)
You can also download the JAR (latest release) directly from [maven.org](https://repo1.maven.org/maven2/org/openapitools/openapi-generator-cli/5.0.0-beta2/openapi-generator-cli-5.0.0-beta2.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`
@@ -770,9 +771,13 @@ Here are some companies/projects (alphabetical order) using OpenAPI Generator in
- 2020-07-20 - [Datadog API client libraries now available for Java and Go](https://www.datadoghq.com/blog/java-go-libraries/) by Jordan Obey at [Datadog Blog](https://www.datadoghq.com/blog)
- 2020-07-23 - [Generate Client SDK for .NET Core using Open Api](https://dev.to/no0law1/generate-client-sdk-for-net-core-using-open-api-2dgh) by [Nuno Reis](https://dev.to/no0law1)
- 2020-07-26 - [Dartのhttp_interceptorライブラリを使うと配列のクエリパラメータが消えてしまう件の応急処置](https://qiita.com/gyamoto/items/eeeff81b6770487319ed) by [@gyamoto](https://qiita.com/gyamoto)
- 2020-08-01 - [Generate Angular ReactiveForms from Swagger/OpenAPI](https://dev.to/martinmcwhorter/generate-angular-reactiveforms-from-swagger-openapi-35h9) by [Martin McWhorter](https://dev.to/martinmcwhorter)
- 2020-08-03 - [Criando Bibliotecas para APIs RESTful com OpenAPI, Swagger Editor e OpenAPI Generator](https://medium.com/@everisBrasil/criando-bibliotecas-para-apis-restful-com-openapi-swagger-editor-e-openapi-generator-75349a6420fd) by [everis Brasil (an NTT DATA Company)](https://medium.com/@everisBrasil)
- 2020-08-19 - [マイクロサービスを連携してみよう](https://thinkit.co.jp/article/17704) by [岡井 裕矢(おかい ゆうや)](https://thinkit.co.jp/author/17588), [泉 勝(いずみ まさる)](https://thinkit.co.jp/author/17705) at [Think ITシンクイット](https://thinkit.co.jp/)
- 2020-08-25 - [OpenAPI Generator と TypeScript で型安全にフロントエンド開発をしている話](https://tech.smarthr.jp/entry/2020/08/25/135631) at [SmartHR Tech Blog](https://tech.smarthr.jp/)
- 2020-09-10 - [Introduction to OpenAPI with Instana](https://www.instana.com/blog/introduction-to-openapi-with-instana/) by [Cedric Ziel](https://www.instana.com/blog/author/cedricziel/) at [Instana Blog](https://www.instana.com/blog/)
- 2020-09-17 - [Generate PowerShellSDK using openapi-generator](https://medium.com/@ghufz.learn/generate-powershellsdk-using-openapi-generator-33b700891e33) by [Ghufran Zahidi](https://medium.com/@ghufz.learn)
- 2020-09-24 - [How to automate API code generation (OpenAPI/Swagger) and boost productivity - Tutorial with React Native featuring TypeScript](https://medium.com/@sceleski/how-to-automate-api-code-generation-openapi-swagger-and-boost-productivity-1176a0056d8a) by [Sanjin Celeski](https://medium.com/@sceleski)
## [6 - About Us](#table-of-contents)

View File

@@ -1,7 +1,9 @@
# for .net standard
generatorName: csharp-netcore
outputDir: samples/client/petstore/csharp-netcore/OpenAPIClient
inputSpec: modules/openapi-generator/src/test/resources/3_0/petstore-with-fake-endpoints-models-for-testing.yaml
inputSpec: modules/openapi-generator/src/test/resources/3_0/java/petstore-with-fake-endpoints-models-for-testing-with-http-signature.yaml
templateDir: modules/openapi-generator/src/main/resources/csharp-netcore
additionalProperties:
packageGuid: '{321C8C3F-0156-40C1-AE42-D59761FB9B6C}'
useCompareNetObjects: "true"
useCompareNetObjects: true
disallowAdditionalPropertiesIfNotPresent: false

View File

@@ -1,7 +1,7 @@
generatorName: java-vertx-web
outputDir: samples/server/petstore/java-vertx-web/rx
outputDir: samples/server/petstore/java-vertx-web
inputSpec: modules/openapi-generator/src/test/resources/3_0/petstore.yaml
templateDir: modules/openapi-generator/src/main/resources/JavaVertXWebServer
additionalProperties:
hideGenerationTimestamp: "true"
artifactId: java-vertx-web-rx-server
artifactId: java-vertx-web-server

View File

@@ -1,4 +1,4 @@
generatorName: python
generatorName: python-experimental
outputDir: samples/client/petstore/python-asyncio
library: asyncio
inputSpec: modules/openapi-generator/src/test/resources/2_0/petstore-with-fake-endpoints-models-for-testing.yaml

View File

@@ -4,3 +4,4 @@ inputSpec: modules/openapi-generator/src/test/resources/3_0/python-experimental/
templateDir: modules/openapi-generator/src/main/resources/python
additionalProperties:
packageName: petstore_api
recursionLimit: "1234"

View File

@@ -1,4 +1,4 @@
generatorName: python
generatorName: python-experimental
outputDir: samples/client/petstore/python-tornado
library: tornado
inputSpec: modules/openapi-generator/src/test/resources/2_0/petstore-with-fake-endpoints-models-for-testing.yaml

View File

@@ -0,0 +1,9 @@
generatorName: ruby
outputDir: samples/openapi3/client/features/dynamic-servers/ruby/
inputSpec: modules/openapi-generator/src/test/resources/3_0/features/dynamic-servers.yaml
templateDir: modules/openapi-generator/src/main/resources/ruby-client
additionalProperties:
gemVersion: 1.0.0
moduleName: DynamicServers
gemName: dynamic_servers
skipFormModel: "true"

View File

@@ -0,0 +1,12 @@
generatorName: ruby
outputDir: samples/openapi3/client/features/generate-alias-as-model/ruby-client/
library: typhoeus
inputSpec: modules/openapi-generator/src/test/resources/3_0/features/generate-alias-as-model.yaml
templateDir: modules/openapi-generator/src/main/resources/ruby-client
additionalProperties:
gemVersion: 1.0.0
moduleName: Petstore
gemName: petstore
skipFormModel: "true"
strictSpecBehavior: false
generateAliasAsModel: true

View File

@@ -4,5 +4,5 @@ library: reqwest
inputSpec: modules/openapi-generator/src/test/resources/2_0/petstore.yaml
templateDir: modules/openapi-generator/src/main/resources/rust
additionalProperties:
supportAsync: "false"
supportAsync: false
packageName: petstore-reqwest

View File

@@ -11,6 +11,7 @@ if [ ! -f "$executable" ]; then
fi
export JAVA_OPTS="${JAVA_OPTS} -ea -server -Duser.timezone=UTC"
export BATCH_OPTS="${BATCH_OPTS:-}"
files=()
args=()
@@ -61,6 +62,6 @@ else
# shellcheck disable=SC2086
# shellcheck disable=SC2068
java ${JAVA_OPTS} -jar "$executable" batch --includes-base-dir "${root}" --fail-fast -- ${files[@]}
java ${JAVA_OPTS} -jar "$executable" batch ${BATCH_OPTS} --includes-base-dir "${root}" --fail-fast -- ${files[@]}
fi

View File

@@ -3,6 +3,77 @@ id: customization
title: Customization
---
## User-defined Templates
The most common scenario for user customization is to override the built-in templates with small modifications. That scenario's documentation is in our [templating](./templating.md) page, and differs from user-defined templates.
Prior to release 5.0.0, whenever a user wanted to include templates which weren't built-in or weren't known to the generator at compile time, they'd need to follow the more involved approach of creating a custom generator as documented later in this document. Beginning in 5.0.0, a user may now provide additional supporting files and extensions to built-in templates via configuration. This feature requires using the external configuration file feature.
Consider that you might want to add some static documentation such as `AUTHORS.md` and a custom tooling script. Rather than a single file for API definitions you also want an implementation file and a separate interface file for each.
You might have an external configuration file named `config.yaml` which defines additional properties like this for a `kotlin` client generator:
```yaml
additionalProperties:
artifactId: kotlin-petstore-client
serializableModel: "true"
dateLibrary: java8
```
You would generate via CLI with the command:
```shell script
openapi-generator generate -g kotlin -i spec.yaml -o outdir -c config.yaml
```
To support the above scenario with custom templates, ensure that you're pointing to your custom template directory and add a `files` node with template file definitions to your config:
```
templateDir: my_custom_templates
additionalProperties:
artifactId: kotlin-petstore-client
serializableModel: "true"
dateLibrary: java8
files:
AUTHORS.md: {}
api_interfaces.mustache:
templateType: API
destinationFilename: Interface.kt
api.mustache:
templateType: API
destinationFilename: Impl.kt
other/check.mustache:
folder: scripts
destinationFilename: check.sh
templateType: SupportingFiles
```
The keys under the `files` node are your template filenames. These honor the same resolution order as all other templates.
The above configuration will do the following:
* Copy `my_custom_templates/AUTHORS.md` to the generated output directory without processing via the template engine (due to template file extension). The empty object definition following `AUTHORS.md` allows the tool to infer the target output filename in the root of the output directory.
* Compile a user-provided `my_custom_templates/api_interfaces.mustache` following our usual API template compilation logic. That is, one file will be created per API; APIs are generated defined according to tags in your spec documentation. The destination filename of `Interface.kt` will act as a suffix for the filename. So, a tag of `Equipment` will output a corresponding `EquipmentInterface.kt`.
* Because `api.mustache` is the same mustache filename as used in your target generator (`kotlin` in this example), we support the following:
- The destination filename provides a suffix for the generated output. APIs generate per tag in your specification. So, a tag of `Equipment` will output a corresponding `EquipmentImpl.kt`. This option will be used whether `api.mustache` targets a user customized template or a built-in template.
- The built-in template will be used if you haven't provided an customized template. The kotlin generator defines the suffix as simply `.kt`, so this scenario would modify only the generated file suffixes according to the previous bullet point.
- Your `api.mustache` will be used if it exists in your custom template directory. For generators with library options, such as `jvm-okhttp3` in the kotlin generator, your file must exist in the same relative location as the embedded template. For kotlin using the `jvm-okhttp3` library option, this file would need to be located at `my_custom_templates/libraries/jvm-okhttp/api.mustache`. See [templating](./templating.md) for more details.
* Compile `my_custom_templates/other/check.mustache` with the supporting files bundle, and output to `scripts/check.sh` in your output directory. Note that we don't currently support setting file flags on output, so scripts such as these will either have to be sourced rather than executed, or have file flags set separately after generation (external to our tooling).
The `templateType` option will default to `SupportingFiles`, so the option for `other/check.mustache` is redundant and provided to demonstrate the full template file configuration options. The available template types are:
* API
* APIDocs
* APITests
* Model
* ModelDocs
* ModelTests
* SupportingFiles
Excluding `SupportingFiles`, each of the above options may result in multiple files. API related types create a file per API. Model related types create a file for each model.
Note that user-defined templates will merge with built-in template definitions. If a supporting file with the sample template file path exists, it will be replaced with the user-defined template, otherwise the user-defined template will be added to the list of template files to compile. If the generator's built-in template is `model_docs.mustache` and you define `model-docs.mustache`, this will result in duplicated model docs (if `destinationFilename` differs) or undefined behavior as whichever template compiles last will overwrite the previous model docs (if `destinationFilename` matches the extension or suffix in the generator's code).
## Custom Generator (and Template)
<a id="creating-a-new-template"></a> If none of the built-in generators suit your needs and you need to do more than just modify the mustache templates to tweak generated code, you can create a brand new generator and its associated templates. OpenAPI Generator can help with this, using the `meta` command:
@@ -20,7 +91,12 @@ These names can be anything you like. If you are building a client for the white
### Use your new generator with the CLI
To compile your library, enter the `out/generators/my-codegen` directory, run `mvn package` and execute the generator:
To compile your library, enter the `out/generators/my-codegen` directory, run `mvn package`.
**NOTE** Running your custom generator requires adding it to the classpath. This differs on [Windows](https://docs.oracle.com/javase/8/docs/technotes/tools/windows/classpath.html) slightly from [unix](https://docs.oracle.com/javase/8/docs/technotes/tools/unix/classpath.html).
If you are running a Windows Subsystem for Linux or a shell such as gitbash, and have issues with the unix variant, try the Windows syntax below.
Now, execute the generator:
```sh
java -cp out/generators/my-codegen/target/my-codegen-openapi-generator-1.0.0.jar:modules/openapi-generator-cli/target/openapi-generator-cli.jar org.openapitools.codegen.OpenAPIGenerator
@@ -28,7 +104,7 @@ java -cp out/generators/my-codegen/target/my-codegen-openapi-generator-1.0.0.jar
For Windows users, you will need to use `;` instead of `:` in the classpath, e.g.
```
java -cp out/generators/my-codegen/target/my-codegen-openapi-generator-1.0.0.jar;modules/openapi-generator-cli/target/openapi-generator-cli.jar org.openapitools.codegen.OpenAPIGenerator
java -cp "out/generators/my-codegen/target/my-codegen-openapi-generator-1.0.0.jar;modules/openapi-generator-cli/target/openapi-generator-cli.jar" org.openapitools.codegen.OpenAPIGenerator
```
Note the `my-codegen` is an option for `-g` now, and you can use the usual arguments for generating your code:
@@ -42,7 +118,7 @@ java -cp out/codegens/customCodegen/target/my-codegen-openapi-generator-1.0.0.ja
For Windows users:
```
java -cp out/codegens/customCodegen/target/my-codegen-openapi-generator-1.0.0.jar;modules/openapi-generator-cli/target/openapi-generator-cli.jar \
java -cp "out/codegens/customCodegen/target/my-codegen-openapi-generator-1.0.0.jar;modules/openapi-generator-cli/target/openapi-generator-cli.jar" \
org.openapitools.codegen.OpenAPIGenerator generate -g my-codegen \
-i https://raw.githubusercontent.com/openapitools/openapi-generator/master/modules/openapi-generator/src/test/resources/2_0/petstore.yaml \
-o ./out/myClient

View File

@@ -16,7 +16,6 @@ sidebar_label: go
|structPrefix|whether to prefix struct with the class name. e.g. DeletePetOpts =&gt; PetApiDeletePetOpts| |false|
|useOneOfDiscriminatorLookup|Use the discriminator's mapping in oneOf to speed up the model lookup. IMPORTANT: Validation (e.g. one and onlye one match in oneOf's schemas) will be skipped.| |false|
|withAWSV4Signature|whether to include AWS v4 signature support| |false|
|withGoCodegenComment|whether to include Go codegen comment to disable Go Lint and collapse by default in GitHub 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|
## IMPORT MAPPING

View File

@@ -24,6 +24,7 @@ sidebar_label: groovy
|fullJavaUtil|whether to use fully qualified name for classes under java.util. This option only works for Java API client| |false|
|groupId|groupId in generated pom.xml| |org.openapitools|
|hideGenerationTimestamp|Hides the generation timestamp when files are generated.| |false|
|ignoreAnyOfInEnum|Ignore anyOf keyword in enum| |false|
|invokerPackage|root package for generated code| |org.openapitools.api|
|java8|Use Java8 classes instead of third party equivalents. Starting in 5.x, JDK8 is the default and the support for JDK7, JDK6 has been dropped|<dl><dt>**true**</dt><dd>Use Java 8 classes such as Base64</dd><dt>**false**</dt><dd>Various third party libraries as needed</dd></dl>|true|
|legacyDiscriminatorBehavior|This flag is used by OpenAPITools codegen to influence the processing of the discriminator attribute in OpenAPI documents. This flag has no impact if the OAS document does not use the discriminator attribute. The default value of this flag is set in each language-specific code generator (e.g. Python, Java, go...)using the method toModelName. Note to developers supporting a language generator in OpenAPITools; to fully support the discriminator attribute as defined in the OAS specification 3.x, language generators should set this flag to true by default; however this requires updating the mustache templates to generate a language-specific discriminator lookup function that iterates over {{#mappedModels}} and does not iterate over {{children}}, {{#anyOf}}, or {{#oneOf}}.|<dl><dt>**true**</dt><dd>The mapping in the discriminator includes descendent schemas that allOf inherit from self and the discriminator mapping schemas in the OAS document.</dd><dt>**false**</dt><dd>The mapping in the discriminator includes any descendent schemas that allOf inherit from self, any oneOf schemas, any anyOf schemas, any x-discriminator-values, and the discriminator mapping schemas in the OAS document AND Codegen validates that oneOf and anyOf schemas contain the required discriminator and throws an error if the discriminator is missing.</dd></dl>|true|

View File

@@ -26,6 +26,7 @@ sidebar_label: java-inflector
|fullJavaUtil|whether to use fully qualified name for classes under java.util. This option only works for Java API client| |false|
|groupId|groupId in generated pom.xml| |org.openapitools|
|hideGenerationTimestamp|Hides the generation timestamp when files are generated.| |false|
|ignoreAnyOfInEnum|Ignore anyOf keyword in enum| |false|
|invokerPackage|root package for generated code| |org.openapitools.controllers|
|java8|Use Java8 classes instead of third party equivalents. Starting in 5.x, JDK8 is the default and the support for JDK7, JDK6 has been dropped|<dl><dt>**true**</dt><dd>Use Java 8 classes such as Base64</dd><dt>**false**</dt><dd>Various third party libraries as needed</dd></dl>|true|
|legacyDiscriminatorBehavior|This flag is used by OpenAPITools codegen to influence the processing of the discriminator attribute in OpenAPI documents. This flag has no impact if the OAS document does not use the discriminator attribute. The default value of this flag is set in each language-specific code generator (e.g. Python, Java, go...)using the method toModelName. Note to developers supporting a language generator in OpenAPITools; to fully support the discriminator attribute as defined in the OAS specification 3.x, language generators should set this flag to true by default; however this requires updating the mustache templates to generate a language-specific discriminator lookup function that iterates over {{#mappedModels}} and does not iterate over {{children}}, {{#anyOf}}, or {{#oneOf}}.|<dl><dt>**true**</dt><dd>The mapping in the discriminator includes descendent schemas that allOf inherit from self and the discriminator mapping schemas in the OAS document.</dd><dt>**false**</dt><dd>The mapping in the discriminator includes any descendent schemas that allOf inherit from self, any oneOf schemas, any anyOf schemas, any x-discriminator-values, and the discriminator mapping schemas in the OAS document AND Codegen validates that oneOf and anyOf schemas contain the required discriminator and throws an error if the discriminator is missing.</dd></dl>|true|

View File

@@ -26,6 +26,7 @@ sidebar_label: java-msf4j
|fullJavaUtil|whether to use fully qualified name for classes under java.util. This option only works for Java API client| |false|
|groupId|groupId in generated pom.xml| |org.openapitools|
|hideGenerationTimestamp|Hides the generation timestamp when files are generated.| |false|
|ignoreAnyOfInEnum|Ignore anyOf keyword in enum| |false|
|implFolder|folder for generated implementation code| |src/main/java|
|invokerPackage|root package for generated code| |org.openapitools.api|
|java8|Use Java8 classes instead of third party equivalents. Starting in 5.x, JDK8 is the default and the support for JDK7, JDK6 has been dropped|<dl><dt>**true**</dt><dd>Use Java 8 classes such as Base64</dd><dt>**false**</dt><dd>Various third party libraries as needed</dd></dl>|true|
@@ -50,6 +51,7 @@ sidebar_label: java-msf4j
|sourceFolder|source folder for generated code| |src/main/java|
|title|a title describing the application| |OpenAPI Server|
|useBeanValidation|Use BeanValidation API annotations| |true|
|useTags|use tags for creating interface and controller classnames| |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|
## IMPORT MAPPING

View File

@@ -28,6 +28,7 @@ sidebar_label: java-pkmst
|fullJavaUtil|whether to use fully qualified name for classes under java.util. This option only works for Java API client| |false|
|groupId|groupId in generated pom.xml| |com.prokarma|
|hideGenerationTimestamp|Hides the generation timestamp when files are generated.| |false|
|ignoreAnyOfInEnum|Ignore anyOf keyword in enum| |false|
|invokerPackage|root package for generated code| |com.prokarma.pkmst.controller|
|java8|Use Java8 classes instead of third party equivalents. Starting in 5.x, JDK8 is the default and the support for JDK7, JDK6 has been dropped|<dl><dt>**true**</dt><dd>Use Java 8 classes such as Base64</dd><dt>**false**</dt><dd>Various third party libraries as needed</dd></dl>|true|
|legacyDiscriminatorBehavior|This flag is used by OpenAPITools codegen to influence the processing of the discriminator attribute in OpenAPI documents. This flag has no impact if the OAS document does not use the discriminator attribute. The default value of this flag is set in each language-specific code generator (e.g. Python, Java, go...)using the method toModelName. Note to developers supporting a language generator in OpenAPITools; to fully support the discriminator attribute as defined in the OAS specification 3.x, language generators should set this flag to true by default; however this requires updating the mustache templates to generate a language-specific discriminator lookup function that iterates over {{#mappedModels}} and does not iterate over {{children}}, {{#anyOf}}, or {{#oneOf}}.|<dl><dt>**true**</dt><dd>The mapping in the discriminator includes descendent schemas that allOf inherit from self and the discriminator mapping schemas in the OAS document.</dd><dt>**false**</dt><dd>The mapping in the discriminator includes any descendent schemas that allOf inherit from self, any oneOf schemas, any anyOf schemas, any x-discriminator-values, and the discriminator mapping schemas in the OAS document AND Codegen validates that oneOf and anyOf schemas contain the required discriminator and throws an error if the discriminator is missing.</dd></dl>|true|

View File

@@ -30,6 +30,7 @@ sidebar_label: java-play-framework
|groupId|groupId in generated pom.xml| |org.openapitools|
|handleExceptions|Add a 'throw exception' to each controller function. Add also a custom error handler where you can put your custom logic| |true|
|hideGenerationTimestamp|Hides the generation timestamp when files are generated.| |false|
|ignoreAnyOfInEnum|Ignore anyOf keyword in enum| |false|
|invokerPackage|root package for generated code| |org.openapitools.api|
|java8|Use Java8 classes instead of third party equivalents. Starting in 5.x, JDK8 is the default and the support for JDK7, JDK6 has been dropped|<dl><dt>**true**</dt><dd>Use Java 8 classes such as Base64</dd><dt>**false**</dt><dd>Various third party libraries as needed</dd></dl>|true|
|legacyDiscriminatorBehavior|This flag is used by OpenAPITools codegen to influence the processing of the discriminator attribute in OpenAPI documents. This flag has no impact if the OAS document does not use the discriminator attribute. The default value of this flag is set in each language-specific code generator (e.g. Python, Java, go...)using the method toModelName. Note to developers supporting a language generator in OpenAPITools; to fully support the discriminator attribute as defined in the OAS specification 3.x, language generators should set this flag to true by default; however this requires updating the mustache templates to generate a language-specific discriminator lookup function that iterates over {{#mappedModels}} and does not iterate over {{children}}, {{#anyOf}}, or {{#oneOf}}.|<dl><dt>**true**</dt><dd>The mapping in the discriminator includes descendent schemas that allOf inherit from self and the discriminator mapping schemas in the OAS document.</dd><dt>**false**</dt><dd>The mapping in the discriminator includes any descendent schemas that allOf inherit from self, any oneOf schemas, any anyOf schemas, any x-discriminator-values, and the discriminator mapping schemas in the OAS document AND Codegen validates that oneOf and anyOf schemas contain the required discriminator and throws an error if the discriminator is missing.</dd></dl>|true|

View File

@@ -26,6 +26,7 @@ sidebar_label: java-undertow-server
|fullJavaUtil|whether to use fully qualified name for classes under java.util. This option only works for Java API client| |false|
|groupId|groupId in generated pom.xml| |org.openapitools|
|hideGenerationTimestamp|Hides the generation timestamp when files are generated.| |false|
|ignoreAnyOfInEnum|Ignore anyOf keyword in enum| |false|
|invokerPackage|root package for generated code| |org.openapitools.handler|
|java8|Use Java8 classes instead of third party equivalents. Starting in 5.x, JDK8 is the default and the support for JDK7, JDK6 has been dropped|<dl><dt>**true**</dt><dd>Use Java 8 classes such as Base64</dd><dt>**false**</dt><dd>Various third party libraries as needed</dd></dl>|true|
|legacyDiscriminatorBehavior|This flag is used by OpenAPITools codegen to influence the processing of the discriminator attribute in OpenAPI documents. This flag has no impact if the OAS document does not use the discriminator attribute. The default value of this flag is set in each language-specific code generator (e.g. Python, Java, go...)using the method toModelName. Note to developers supporting a language generator in OpenAPITools; to fully support the discriminator attribute as defined in the OAS specification 3.x, language generators should set this flag to true by default; however this requires updating the mustache templates to generate a language-specific discriminator lookup function that iterates over {{#mappedModels}} and does not iterate over {{children}}, {{#anyOf}}, or {{#oneOf}}.|<dl><dt>**true**</dt><dd>The mapping in the discriminator includes descendent schemas that allOf inherit from self and the discriminator mapping schemas in the OAS document.</dd><dt>**false**</dt><dd>The mapping in the discriminator includes any descendent schemas that allOf inherit from self, any oneOf schemas, any anyOf schemas, any x-discriminator-values, and the discriminator mapping schemas in the OAS document AND Codegen validates that oneOf and anyOf schemas contain the required discriminator and throws an error if the discriminator is missing.</dd></dl>|true|

View File

@@ -26,6 +26,7 @@ sidebar_label: java-vertx-web
|fullJavaUtil|whether to use fully qualified name for classes under java.util. This option only works for Java API client| |false|
|groupId|groupId in generated pom.xml| |org.openapitools|
|hideGenerationTimestamp|Hides the generation timestamp when files are generated.| |false|
|ignoreAnyOfInEnum|Ignore anyOf keyword in enum| |false|
|invokerPackage|root package for generated code| |org.openapitools.vertxweb.server|
|java8|Use Java8 classes instead of third party equivalents. Starting in 5.x, JDK8 is the default and the support for JDK7, JDK6 has been dropped|<dl><dt>**true**</dt><dd>Use Java 8 classes such as Base64</dd><dt>**false**</dt><dd>Various third party libraries as needed</dd></dl>|true|
|legacyDiscriminatorBehavior|This flag is used by OpenAPITools codegen to influence the processing of the discriminator attribute in OpenAPI documents. This flag has no impact if the OAS document does not use the discriminator attribute. The default value of this flag is set in each language-specific code generator (e.g. Python, Java, go...)using the method toModelName. Note to developers supporting a language generator in OpenAPITools; to fully support the discriminator attribute as defined in the OAS specification 3.x, language generators should set this flag to true by default; however this requires updating the mustache templates to generate a language-specific discriminator lookup function that iterates over {{#mappedModels}} and does not iterate over {{children}}, {{#anyOf}}, or {{#oneOf}}.|<dl><dt>**true**</dt><dd>The mapping in the discriminator includes descendent schemas that allOf inherit from self and the discriminator mapping schemas in the OAS document.</dd><dt>**false**</dt><dd>The mapping in the discriminator includes any descendent schemas that allOf inherit from self, any oneOf schemas, any anyOf schemas, any x-discriminator-values, and the discriminator mapping schemas in the OAS document AND Codegen validates that oneOf and anyOf schemas contain the required discriminator and throws an error if the discriminator is missing.</dd></dl>|true|

View File

@@ -26,6 +26,7 @@ sidebar_label: java-vertx
|fullJavaUtil|whether to use fully qualified name for classes under java.util. This option only works for Java API client| |false|
|groupId|groupId in generated pom.xml| |org.openapitools|
|hideGenerationTimestamp|Hides the generation timestamp when files are generated.| |false|
|ignoreAnyOfInEnum|Ignore anyOf keyword in enum| |false|
|invokerPackage|root package for generated code| |org.openapitools|
|java8|Use Java8 classes instead of third party equivalents. Starting in 5.x, JDK8 is the default and the support for JDK7, JDK6 has been dropped|<dl><dt>**true**</dt><dd>Use Java 8 classes such as Base64</dd><dt>**false**</dt><dd>Various third party libraries as needed</dd></dl>|true|
|legacyDiscriminatorBehavior|This flag is used by OpenAPITools codegen to influence the processing of the discriminator attribute in OpenAPI documents. This flag has no impact if the OAS document does not use the discriminator attribute. The default value of this flag is set in each language-specific code generator (e.g. Python, Java, go...)using the method toModelName. Note to developers supporting a language generator in OpenAPITools; to fully support the discriminator attribute as defined in the OAS specification 3.x, language generators should set this flag to true by default; however this requires updating the mustache templates to generate a language-specific discriminator lookup function that iterates over {{#mappedModels}} and does not iterate over {{children}}, {{#anyOf}}, or {{#oneOf}}.|<dl><dt>**true**</dt><dd>The mapping in the discriminator includes descendent schemas that allOf inherit from self and the discriminator mapping schemas in the OAS document.</dd><dt>**false**</dt><dd>The mapping in the discriminator includes any descendent schemas that allOf inherit from self, any oneOf schemas, any anyOf schemas, any x-discriminator-values, and the discriminator mapping schemas in the OAS document AND Codegen validates that oneOf and anyOf schemas contain the required discriminator and throws an error if the discriminator is missing.</dd></dl>|true|

View File

@@ -28,6 +28,7 @@ sidebar_label: java
|fullJavaUtil|whether to use fully qualified name for classes under java.util. This option only works for Java API client| |false|
|groupId|groupId in generated pom.xml| |org.openapitools|
|hideGenerationTimestamp|Hides the generation timestamp when files are generated.| |false|
|ignoreAnyOfInEnum|Ignore anyOf keyword in enum| |false|
|invokerPackage|root package for generated code| |org.openapitools.client|
|java8|Use Java8 classes instead of third party equivalents. Starting in 5.x, JDK8 is the default and the support for JDK7, JDK6 has been dropped|<dl><dt>**true**</dt><dd>Use Java 8 classes such as Base64</dd><dt>**false**</dt><dd>Various third party libraries as needed</dd></dl>|true|
|legacyDiscriminatorBehavior|This flag is used by OpenAPITools codegen to influence the processing of the discriminator attribute in OpenAPI documents. This flag has no impact if the OAS document does not use the discriminator attribute. The default value of this flag is set in each language-specific code generator (e.g. Python, Java, go...)using the method toModelName. Note to developers supporting a language generator in OpenAPITools; to fully support the discriminator attribute as defined in the OAS specification 3.x, language generators should set this flag to true by default; however this requires updating the mustache templates to generate a language-specific discriminator lookup function that iterates over {{#mappedModels}} and does not iterate over {{children}}, {{#anyOf}}, or {{#oneOf}}.|<dl><dt>**true**</dt><dd>The mapping in the discriminator includes descendent schemas that allOf inherit from self and the discriminator mapping schemas in the OAS document.</dd><dt>**false**</dt><dd>The mapping in the discriminator includes any descendent schemas that allOf inherit from self, any oneOf schemas, any anyOf schemas, any x-discriminator-values, and the discriminator mapping schemas in the OAS document AND Codegen validates that oneOf and anyOf schemas contain the required discriminator and throws an error if the discriminator is missing.</dd></dl>|true|

View File

@@ -28,6 +28,7 @@ sidebar_label: jaxrs-cxf-cdi
|generatePom|Whether to generate pom.xml if the file does not already exist.| |true|
|groupId|groupId in generated pom.xml| |org.openapitools|
|hideGenerationTimestamp|Hides the generation timestamp when files are generated.| |false|
|ignoreAnyOfInEnum|Ignore anyOf keyword in enum| |false|
|implFolder|folder for generated implementation code| |src/main/java|
|interfaceOnly|Whether to generate only API interface stubs without the server files.| |false|
|invokerPackage|root package for generated code| |org.openapitools.api|
@@ -56,6 +57,7 @@ sidebar_label: jaxrs-cxf-cdi
|title|a title describing the application| |OpenAPI Server|
|useBeanValidation|Use BeanValidation API annotations| |true|
|useSwaggerAnnotations|Whether to generate Swagger annotations.| |true|
|useTags|use tags for creating interface and controller classnames| |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|
## IMPORT MAPPING

View File

@@ -26,6 +26,7 @@ sidebar_label: jaxrs-cxf-client
|fullJavaUtil|whether to use fully qualified name for classes under java.util. This option only works for Java API client| |false|
|groupId|groupId in generated pom.xml| |org.openapitools|
|hideGenerationTimestamp|Hides the generation timestamp when files are generated.| |false|
|ignoreAnyOfInEnum|Ignore anyOf keyword in enum| |false|
|invokerPackage|root package for generated code| |org.openapitools.api|
|java8|Use Java8 classes instead of third party equivalents. Starting in 5.x, JDK8 is the default and the support for JDK7, JDK6 has been dropped|<dl><dt>**true**</dt><dd>Use Java 8 classes such as Base64</dd><dt>**false**</dt><dd>Various third party libraries as needed</dd></dl>|true|
|legacyDiscriminatorBehavior|This flag is used by OpenAPITools codegen to influence the processing of the discriminator attribute in OpenAPI documents. This flag has no impact if the OAS document does not use the discriminator attribute. The default value of this flag is set in each language-specific code generator (e.g. Python, Java, go...)using the method toModelName. Note to developers supporting a language generator in OpenAPITools; to fully support the discriminator attribute as defined in the OAS specification 3.x, language generators should set this flag to true by default; however this requires updating the mustache templates to generate a language-specific discriminator lookup function that iterates over {{#mappedModels}} and does not iterate over {{children}}, {{#anyOf}}, or {{#oneOf}}.|<dl><dt>**true**</dt><dd>The mapping in the discriminator includes descendent schemas that allOf inherit from self and the discriminator mapping schemas in the OAS document.</dd><dt>**false**</dt><dd>The mapping in the discriminator includes any descendent schemas that allOf inherit from self, any oneOf schemas, any anyOf schemas, any x-discriminator-values, and the discriminator mapping schemas in the OAS document AND Codegen validates that oneOf and anyOf schemas contain the required discriminator and throws an error if the discriminator is missing.</dd></dl>|true|

View File

@@ -32,6 +32,7 @@ sidebar_label: jaxrs-cxf-extended
|generateSpringBootApplication|Generate Spring Boot application| |false|
|groupId|groupId in generated pom.xml| |org.openapitools|
|hideGenerationTimestamp|Hides the generation timestamp when files are generated.| |false|
|ignoreAnyOfInEnum|Ignore anyOf keyword in enum| |false|
|implFolder|folder for generated implementation code| |src/main/java|
|invokerPackage|root package for generated code| |org.openapitools.api|
|java8|Use Java8 classes instead of third party equivalents. Starting in 5.x, JDK8 is the default and the support for JDK7, JDK6 has been dropped|<dl><dt>**true**</dt><dd>Use Java 8 classes such as Base64</dd><dt>**false**</dt><dd>Various third party libraries as needed</dd></dl>|true|
@@ -70,6 +71,7 @@ sidebar_label: jaxrs-cxf-extended
|useSpringAnnotationConfig|Use Spring Annotation Config| |false|
|useSwaggerFeature|Use Swagger Feature| |false|
|useSwaggerUI|Use Swagger UI| |false|
|useTags|use tags for creating interface and controller classnames| |true|
|useWadlFeature|Use WADL Feature| |false|
|withXml|whether to include support for application/xml content type and include XML annotations in the model (works with libraries that provide support for JSON and XML)| |false|

View File

@@ -31,6 +31,7 @@ sidebar_label: jaxrs-cxf
|generateSpringBootApplication|Generate Spring Boot application| |false|
|groupId|groupId in generated pom.xml| |org.openapitools|
|hideGenerationTimestamp|Hides the generation timestamp when files are generated.| |false|
|ignoreAnyOfInEnum|Ignore anyOf keyword in enum| |false|
|implFolder|folder for generated implementation code| |src/main/java|
|invokerPackage|root package for generated code| |org.openapitools.api|
|java8|Use Java8 classes instead of third party equivalents. Starting in 5.x, JDK8 is the default and the support for JDK7, JDK6 has been dropped|<dl><dt>**true**</dt><dd>Use Java 8 classes such as Base64</dd><dt>**false**</dt><dd>Various third party libraries as needed</dd></dl>|true|
@@ -65,6 +66,7 @@ sidebar_label: jaxrs-cxf
|useSpringAnnotationConfig|Use Spring Annotation Config| |false|
|useSwaggerFeature|Use Swagger Feature| |false|
|useSwaggerUI|Use Swagger UI| |false|
|useTags|use tags for creating interface and controller classnames| |true|
|useWadlFeature|Use WADL Feature| |false|
|withXml|whether to include support for application/xml content type and include XML annotations in the model (works with libraries that provide support for JSON and XML)| |false|

View File

@@ -26,6 +26,7 @@ sidebar_label: jaxrs-jersey
|fullJavaUtil|whether to use fully qualified name for classes under java.util. This option only works for Java API client| |false|
|groupId|groupId in generated pom.xml| |org.openapitools|
|hideGenerationTimestamp|Hides the generation timestamp when files are generated.| |false|
|ignoreAnyOfInEnum|Ignore anyOf keyword in enum| |false|
|implFolder|folder for generated implementation code| |src/main/java|
|invokerPackage|root package for generated code| |org.openapitools.api|
|java8|Use Java8 classes instead of third party equivalents. Starting in 5.x, JDK8 is the default and the support for JDK7, JDK6 has been dropped|<dl><dt>**true**</dt><dd>Use Java 8 classes such as Base64</dd><dt>**false**</dt><dd>Various third party libraries as needed</dd></dl>|true|

View File

@@ -27,6 +27,7 @@ sidebar_label: jaxrs-resteasy-eap
|generateJbossDeploymentDescriptor|Generate Jboss Deployment Descriptor| |true|
|groupId|groupId in generated pom.xml| |org.openapitools|
|hideGenerationTimestamp|Hides the generation timestamp when files are generated.| |false|
|ignoreAnyOfInEnum|Ignore anyOf keyword in enum| |false|
|implFolder|folder for generated implementation code| |src/main/java|
|invokerPackage|root package for generated code| |org.openapitools.api|
|java8|Use Java8 classes instead of third party equivalents. Starting in 5.x, JDK8 is the default and the support for JDK7, JDK6 has been dropped|<dl><dt>**true**</dt><dd>Use Java 8 classes such as Base64</dd><dt>**false**</dt><dd>Various third party libraries as needed</dd></dl>|true|
@@ -51,6 +52,7 @@ sidebar_label: jaxrs-resteasy-eap
|title|a title describing the application| |OpenAPI Server|
|useBeanValidation|Use BeanValidation API annotations| |true|
|useSwaggerFeature|Use dynamic Swagger generator| |false|
|useTags|use tags for creating interface and controller classnames| |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|
## IMPORT MAPPING

View File

@@ -27,6 +27,7 @@ sidebar_label: jaxrs-resteasy
|generateJbossDeploymentDescriptor|Generate Jboss Deployment Descriptor| |false|
|groupId|groupId in generated pom.xml| |org.openapitools|
|hideGenerationTimestamp|Hides the generation timestamp when files are generated.| |false|
|ignoreAnyOfInEnum|Ignore anyOf keyword in enum| |false|
|implFolder|folder for generated implementation code| |src/main/java|
|invokerPackage|root package for generated code| |org.openapitools.api|
|java8|Use Java8 classes instead of third party equivalents. Starting in 5.x, JDK8 is the default and the support for JDK7, JDK6 has been dropped|<dl><dt>**true**</dt><dd>Use Java 8 classes such as Base64</dd><dt>**false**</dt><dd>Various third party libraries as needed</dd></dl>|true|
@@ -50,6 +51,7 @@ sidebar_label: jaxrs-resteasy
|sourceFolder|source folder for generated code| |src/main/java|
|title|a title describing the application| |OpenAPI Server|
|useBeanValidation|Use BeanValidation API annotations| |true|
|useTags|use tags for creating interface and controller classnames| |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|
## IMPORT MAPPING

View File

@@ -28,6 +28,7 @@ sidebar_label: jaxrs-spec
|generatePom|Whether to generate pom.xml if the file does not already exist.| |true|
|groupId|groupId in generated pom.xml| |org.openapitools|
|hideGenerationTimestamp|Hides the generation timestamp when files are generated.| |false|
|ignoreAnyOfInEnum|Ignore anyOf keyword in enum| |false|
|implFolder|folder for generated implementation code| |src/main/java|
|interfaceOnly|Whether to generate only API interface stubs without the server files.| |false|
|invokerPackage|root package for generated code| |org.openapitools.api|
@@ -56,6 +57,7 @@ sidebar_label: jaxrs-spec
|title|a title describing the application| |OpenAPI Server|
|useBeanValidation|Use BeanValidation API annotations| |true|
|useSwaggerAnnotations|Whether to generate Swagger annotations.| |true|
|useTags|use tags for creating interface and controller classnames| |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|
## IMPORT MAPPING

View File

@@ -9,6 +9,7 @@ sidebar_label: openapi
|disallowAdditionalPropertiesIfNotPresent|Specify the behavior when the 'additionalProperties' keyword is not present in the OAS document. If false: the 'additionalProperties' implementation is compliant with the OAS and JSON schema specifications. If true: when the 'additionalProperties' keyword is not present in a schema, the value of 'additionalProperties' is set to false, i.e. no additional properties are allowed. Note: this mode is not compliant with the JSON schema specification. This is the original openapi-generator behavior.This setting is currently ignored for OAS 2.0 documents: 1) When the 'additionalProperties' keyword is not present in a 2.0 schema, additional properties are NOT allowed. 2) Boolean values of the 'additionalProperties' keyword are ignored. It's as if additional properties are NOT allowed.Note: the root cause are issues #1369 and #1371, which must be resolved in the swagger-parser project.|<dl><dt>**false**</dt><dd>The 'additionalProperties' implementation is compliant with the OAS and JSON schema specifications.</dd><dt>**true**</dt><dd>when the 'additionalProperties' keyword is not present in a schema, the value of 'additionalProperties' is automatically set to false, i.e. no additional properties are allowed. Note: this mode is not compliant with the JSON schema specification. This is the original openapi-generator behavior.</dd></dl>|true|
|ensureUniqueParams|Whether to ensure parameter names are unique in an operation (rename parameters that are not).| |true|
|legacyDiscriminatorBehavior|This flag is used by OpenAPITools codegen to influence the processing of the discriminator attribute in OpenAPI documents. This flag has no impact if the OAS document does not use the discriminator attribute. The default value of this flag is set in each language-specific code generator (e.g. Python, Java, go...)using the method toModelName. Note to developers supporting a language generator in OpenAPITools; to fully support the discriminator attribute as defined in the OAS specification 3.x, language generators should set this flag to true by default; however this requires updating the mustache templates to generate a language-specific discriminator lookup function that iterates over {{#mappedModels}} and does not iterate over {{children}}, {{#anyOf}}, or {{#oneOf}}.|<dl><dt>**true**</dt><dd>The mapping in the discriminator includes descendent schemas that allOf inherit from self and the discriminator mapping schemas in the OAS document.</dd><dt>**false**</dt><dd>The mapping in the discriminator includes any descendent schemas that allOf inherit from self, any oneOf schemas, any anyOf schemas, any x-discriminator-values, and the discriminator mapping schemas in the OAS document AND Codegen validates that oneOf and anyOf schemas contain the required discriminator and throws an error if the discriminator is missing.</dd></dl>|true|
|outputFileName|Output file name| |openapi.json|
|prependFormOrBodyParameters|Add form or body parameters to the beginning of the parameter list.| |false|
|sortModelPropertiesByRequiredFlag|Sort model properties to place required parameters before optional parameters.| |true|
|sortParamsByRequiredFlag|Sort method arguments to place required parameters before optional parameters.| |true|

View File

@@ -12,6 +12,7 @@ sidebar_label: python-experimental
|packageUrl|python package URL.| |null|
|packageVersion|python package version.| |1.0.0|
|projectName|python project name in setup.py (e.g. petstore-api).| |null|
|recursionLimit|Set the recursion limit. If not set, use the system default value.| |null|
|useNose|use the nose test framework| |false|
## IMPORT MAPPING

View File

@@ -12,6 +12,7 @@ sidebar_label: python
|packageUrl|python package URL.| |null|
|packageVersion|python package version.| |1.0.0|
|projectName|python project name in setup.py (e.g. petstore-api).| |null|
|recursionLimit|Set the recursion limit. If not set, use the system default value.| |null|
|sortParamsByRequiredFlag|Sort method arguments to place required parameters before optional parameters.| |true|
|useNose|use the nose test framework| |false|

View File

@@ -34,6 +34,9 @@ sidebar_label: ruby-on-rails
| Type/Alias | Instantiated By |
| ---------- | --------------- |
|array|Array|
|map|Hash|
|set|Set|
## LANGUAGE PRIMITIVES

View File

@@ -33,6 +33,9 @@ sidebar_label: ruby-sinatra
| Type/Alias | Instantiated By |
| ---------- | --------------- |
|array|Array|
|map|Hash|
|set|Set|
## LANGUAGE PRIMITIVES

View File

@@ -35,6 +35,9 @@ sidebar_label: ruby
| Type/Alias | Instantiated By |
| ---------- | --------------- |
|array|Array|
|map|Hash|
|set|Set|
## LANGUAGE PRIMITIVES

View File

@@ -32,6 +32,7 @@ sidebar_label: spring
|groupId|groupId in generated pom.xml| |org.openapitools|
|hateoas|Use Spring HATEOAS library to allow adding HATEOAS links| |false|
|hideGenerationTimestamp|Hides the generation timestamp when files are generated.| |false|
|ignoreAnyOfInEnum|Ignore anyOf keyword in enum| |false|
|implicitHeaders|Skip header parameters in the generated API methods using @ApiImplicitParams annotation.| |false|
|interfaceOnly|Whether to generate only API interface stubs without the server files.| |false|
|invokerPackage|root package for generated code| |org.openapitools.api|

View File

@@ -48,7 +48,9 @@ java -cp /path/totemplate-classpath-example-1.0-SNAPSHOT.jar:modules/openapi-gen
-g html -o template-example -t templates/htmlDocs
```
Note that our template directory is relative to the resource directory of the JAR defined on the classpath.
**NOTE** Running your custom generator in the example above requires adding it to the classpath. This differs on [Windows](https://docs.oracle.com/javase/8/docs/technotes/tools/windows/classpath.html) slightly from [unix](https://docs.oracle.com/javase/8/docs/technotes/tools/unix/classpath.html).
Take note that our template directory is relative to the resource directory of the JAR defined on the classpath.
### Retrieving Templates
@@ -470,7 +472,9 @@ java $JAVA_OPTS -cp /your/path/build/libs/pebble-template-adapter-1.0-SNAPSHOT-a
--global-property models,modelDocs,modelTests,apis,apiTests,apiDocs
```
Notice how we've targeted our custom template engine adapter via `-e pebble`. If you don't include the SPI file under `META-INF/services`, you'll need to specify the exact classpath: `org.openapitools.examples.templating.PebbleTemplateAdapter`. Notice that the target class here matches the Kotlin class name. This is because of the `@file:JvmName` annotation.
**NOTE** Running your custom generator requires adding it to the classpath. This differs on [Windows](https://docs.oracle.com/javase/8/docs/technotes/tools/windows/classpath.html) slightly from [unix](https://docs.oracle.com/javase/8/docs/technotes/tools/unix/classpath.html).
In the above example, we've targeted our custom template engine adapter via `-e pebble`. If you don't include the SPI file under `META-INF/services`, you'll need to specify the exact classpath: `org.openapitools.examples.templating.PebbleTemplateAdapter`. Notice that the target class here matches the Kotlin class name. This is because of the `@file:JvmName` annotation.
Congratulations on creating a custom templating engine adapter!

View File

@@ -602,7 +602,7 @@ openapi-generator generate -i petstore.yaml -g typescript-fetch -o out \
The `batch` command allows you to move all CLI arguments supported by the `generate` command into a YAML or JSON file.
*NOTE*: This command supports an additional `!include` property which may point to another "shared" file, the base path to which can be
modified by `--includes-base-dir`.
modified by `--includes-base-dir`. Starting with 5.0.0, the `!batch` command supports multiple `!include` properties, either sequential or nested. In order to support multiple `!include` properties in a JSON file, the property name can have a suffix, e.g. `!include1`, `!include2`, etc. The suffix have no meaning other than providing unique property names.
```bash
openapi-generator help batch

View File

@@ -4,7 +4,7 @@
<groupId>org.openapitools</groupId>
<artifactId>openapi-generator-project</artifactId>
<!-- RELEASE_VERSION -->
<version>5.0.0-beta2</version>
<version>5.0.0-SNAPSHOT</version>
<!-- /RELEASE_VERSION -->
<relativePath>../..</relativePath>
</parent>

View File

@@ -39,15 +39,16 @@ import java.util.stream.Collectors;
import static org.apache.commons.lang3.StringEscapeUtils.escapeHtml4;
import static org.apache.commons.lang3.StringUtils.isEmpty;
@SuppressWarnings({"unused","java:S106"})
@SuppressWarnings({"unused","java:S106", "java:S1192"})
@Command(name = "config-help", description = "Config help for chosen lang")
public class ConfigHelp extends OpenApiGeneratorCommand {
private static final Logger LOGGER = LoggerFactory.getLogger(Generate.class);
private static final Logger LOGGER = LoggerFactory.getLogger(ConfigHelp.class);
private static final String FORMAT_TEXT = "text";
private static final String FORMAT_MARKDOWN = "markdown";
private static final String FORMAT_YAMLSAMPLE = "yamlsample";
private static final int FEATURE_SET_DISPLAY_WIDTH= 20;
@Option(name = {"-g",
"--generator-name"}, title = "generator name", description = "generator to get config help for")
@@ -147,7 +148,7 @@ public class ConfigHelp extends OpenApiGeneratorCommand {
LOGGER.error("[error] Check the spelling of the generator's name and try again.");
System.exit(1);
} catch (IOException e) {
e.printStackTrace();
LOGGER.error("Unexpected error", e);
}
}
@@ -396,7 +397,7 @@ public class ConfigHelp extends OpenApiGeneratorCommand {
String definedByKey = "Defined By";
int maxNameLength = flattened.stream().map(FeatureSet.FeatureSetFlattened::getFeatureName).mapToInt(String::length).max().orElse(nameKey.length());
int maxSupportedLength = supportedKey.length();
int definedInLength = 20;
int definedInLength = FEATURE_SET_DISPLAY_WIDTH;
String format = "%-" + maxNameLength + "s\t%-" + maxSupportedLength + "s\t%-" + definedInLength + "s";
flattened.forEach(featureSet -> {

View File

@@ -18,16 +18,23 @@ package org.openapitools.codegen.cmd;
import ch.qos.logback.classic.Level;
import ch.qos.logback.classic.LoggerContext;
import com.fasterxml.jackson.core.JsonFactory;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonToken;
import com.fasterxml.jackson.core.TreeNode;
import com.fasterxml.jackson.databind.*;
import com.fasterxml.jackson.databind.deser.BeanDeserializerModifier;
import com.fasterxml.jackson.databind.deser.std.DelegatingDeserializer;
import com.fasterxml.jackson.databind.module.SimpleModule;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.fasterxml.jackson.databind.util.TokenBuffer;
import io.airlift.airline.Arguments;
import io.airlift.airline.Command;
import io.airlift.airline.Option;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.openapitools.codegen.ClientOptInput;
import org.openapitools.codegen.CodegenConfig;
@@ -40,6 +47,7 @@ import org.slf4j.LoggerFactory;
import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
@@ -71,6 +79,9 @@ public class GenerateBatch extends OpenApiGeneratorCommand {
@Option(name = {"--fail-fast"}, description = "fail fast on any errors")
private Boolean failFast;
@Option(name = {"--clean"}, description = "clean output of previously written files before generation")
private Boolean clean;
@Option(name = {"--timeout"}, description = "execution timeout (minutes)")
private Integer timeout;
@@ -143,7 +154,10 @@ public class GenerateBatch extends OpenApiGeneratorCommand {
ExecutorService executor = Executors.newFixedThreadPool(numThreads);
// Execute each configurator on a separate pooled thread.
configurators.forEach(configurator -> executor.execute(new GenerationRunner(configurator, rootDir, Boolean.TRUE.equals(failFast))));
configurators.forEach(configurator -> {
GenerationRunner runner = new GenerationRunner(configurator, rootDir, Boolean.TRUE.equals(failFast), Boolean.TRUE.equals(clean));
executor.execute(runner);
});
executor.shutdown();
@@ -172,11 +186,13 @@ public class GenerateBatch extends OpenApiGeneratorCommand {
private final CodegenConfigurator configurator;
private final Path rootDir;
private final boolean exitOnError;
private final boolean clean;
private GenerationRunner(CodegenConfigurator configurator, Path rootDir, boolean failFast) {
private GenerationRunner(CodegenConfigurator configurator, Path rootDir, boolean failFast, boolean clean) {
this.configurator = configurator;
this.rootDir = rootDir;
this.exitOnError = failFast;
this.clean = clean;
}
/**
@@ -192,7 +208,7 @@ public class GenerateBatch extends OpenApiGeneratorCommand {
*/
@Override
public void run() {
String name = "";
String name = null;
try {
GlobalSettings.reset();
@@ -204,6 +220,10 @@ public class GenerateBatch extends OpenApiGeneratorCommand {
Path updated = rootDir.resolve(target);
config.setOutputDir(updated.toString());
if (this.clean) {
cleanPreviousFiles(name, updated);
}
System.out.printf(Locale.ROOT, "[%s] Generating %s (outputs to %s)…%n", Thread.currentThread().getName(), name, updated.toString());
DefaultGenerator defaultGenerator = new DefaultGenerator();
@@ -228,6 +248,28 @@ public class GenerateBatch extends OpenApiGeneratorCommand {
GlobalSettings.reset();
}
}
private void cleanPreviousFiles(final String name, Path outDir) throws IOException {
System.out.printf(Locale.ROOT, "[%s] Cleaning previous contents for %s in %s…%n", Thread.currentThread().getName(), name, outDir.toString());
Path filesMeta = Paths.get(outDir.toAbsolutePath().toString(), ".openapi-generator", "FILES");
if (filesMeta.toFile().exists()) {
FileUtils.readLines(filesMeta.toFile(), StandardCharsets.UTF_8).forEach(relativePath -> {
if (!StringUtils.startsWith(relativePath, ".")) {
Path file = outDir.resolve(relativePath).toAbsolutePath();
// hack: disallow directory traversal outside of output directory. we don't want to delete wrong files.
if (file.toString().startsWith(outDir.toAbsolutePath().toString())) {
try {
Files.delete(file);
} catch (Throwable e) {
System.out.printf(Locale.ROOT, "[%s] Generator %s failed to clean file %s…%n", Thread.currentThread().getName(), name, file);
}
}
} else {
System.out.printf(Locale.ROOT, "[%s] Generator %s skip cleaning special filename %s…%n", Thread.currentThread().getName(), name, relativePath);
}
});
}
}
}
static SimpleModule getCustomDeserializationModel(final File includesDir) {
@@ -268,35 +310,51 @@ public class GenerateBatch extends OpenApiGeneratorCommand {
@Override
public Object deserialize(JsonParser p, DeserializationContext ctx) throws IOException {
TreeNode node = p.readValueAsTree();
JsonNode include = (JsonNode) node.get(INCLUDE);
ObjectMapper codec = (ObjectMapper) ctx.getParser().getCodec();
if (include != null) {
String ref = include.textValue();
if (ref != null) {
File includeFile = scanDir != null ? new File(scanDir, ref) : new File(ref);
if (includeFile.exists()) {
// load the file into the tree node and continue parsing as normal
((ObjectNode) node).remove(INCLUDE);
TreeNode includeNode;
try (JsonParser includeParser = codec.getFactory().createParser(includeFile)) {
includeNode = includeParser.readValueAsTree();
}
ObjectReader reader = codec.readerForUpdating(node);
TreeNode updated = reader.readValue(includeNode.traverse());
JsonParser updatedParser = updated.traverse();
updatedParser.nextToken();
return super.deserialize(updatedParser, ctx);
}
}
}
JsonParser newParser = node.traverse();
TokenBuffer buffer = new TokenBuffer(p);
recurse(buffer, p, codec, false);
JsonParser newParser = buffer.asParser(codec);
newParser.nextToken();
return super.deserialize(newParser, ctx);
}
private void recurse(TokenBuffer buffer, JsonParser p, ObjectMapper codec, boolean skipOuterbraces) throws IOException {
boolean firstToken = true;
JsonToken token;
while ((token = p.nextToken()) != null) {
String name = p.currentName();
if (skipOuterbraces && firstToken && JsonToken.START_OBJECT.equals(token)) {
continue;
}
if (skipOuterbraces && p.getParsingContext().inRoot() && JsonToken.END_OBJECT.equals(token)) {
continue;
}
if (JsonToken.VALUE_NULL.equals(token)) {
continue;
}
if (name != null && JsonToken.FIELD_NAME.equals(token) && name.startsWith(INCLUDE)) {
p.nextToken();
String fileName = p.getText();
if (fileName != null) {
File includeFile = scanDir != null ? new File(scanDir, fileName) : new File(fileName);
if (includeFile.exists()) {
recurse(buffer, codec.getFactory().createParser(includeFile), codec, true);
}
}
} else {
buffer.copyCurrentEvent(p);
}
firstToken = false;
}
}
}
}

View File

@@ -144,8 +144,8 @@ public class Meta extends OpenApiGeneratorCommand {
return support -> {
try {
File destinationFolder =
new File(new File(targetDir.getAbsolutePath()), support.folder);
File outputFile = new File(destinationFolder, support.destinationFilename);
new File(new File(targetDir.getAbsolutePath()), support.getFolder());
File outputFile = new File(destinationFolder, support.getDestinationFilename());
TemplateManager templateProcessor = new TemplateManager(
new TemplateManagerOptions(false, false),
@@ -153,13 +153,13 @@ public class Meta extends OpenApiGeneratorCommand {
new TemplatePathLocator[]{ new CommonTemplateContentLocator("codegen") }
);
String template = templateProcessor.readTemplate(new File(TEMPLATE_DIR_CLASSPATH, support.templateFile).getPath());
String template = templateProcessor.readTemplate(new File(TEMPLATE_DIR_CLASSPATH, support.getTemplateFile()).getPath());
String formatted = template;
Mustache.TemplateLoader loader = name -> templateProcessor.getTemplateReader(name.concat(MUSTACHE_EXTENSION));
if (support.templateFile.endsWith(MUSTACHE_EXTENSION)) {
if (support.getTemplateFile().endsWith(MUSTACHE_EXTENSION)) {
LOGGER.info("writing file to {}", outputFile.getAbsolutePath());
formatted =
Mustache.compiler().withLoader(loader).defaultValue("")

View File

@@ -28,6 +28,12 @@ public class GenerateBatchTest {
private static final String JAXRS_DATELIB_J8_YAML = "jaxrs-datelib-j8.yaml";
private static final String JAXRS_DATELIB_J8_YAML_INCLUDE_JSON = "jaxrs-datelib-j8-yaml-include.json";
private static final String JAXRS_DATELIB_J8_JSON_INCLUDE_YAML = "jaxrs-datelib-j8-json-include.yaml";
private static final String JAXRS_DATELIB_J8_DOUBLE_JSON = "jaxrs-datelib-j8-double.json";
private static final String JAXRS_DATELIB_J8_DOUBLE_YAML = "jaxrs-datelib-j8-double.yaml";
private static final String JAXRS_DATELIB_J8_NESTED_JSON = "jaxrs-datelib-j8-nested.json";
private static final String JAXRS_DATELIB_J8_NESTED_YAML = "jaxrs-datelib-j8-nested.yaml";
private static final String JAXRS_DATELIB_J8_NESTED_PROPERTY_MERGE_YAML = "jaxrs-datelib-j8-nested-property-merge.yaml";
Path workingDirectory;
@BeforeTest
@@ -40,7 +46,12 @@ public class GenerateBatchTest {
return new Object[][] {
{JAXRS_DATELIB_J8_JSON},
{JAXRS_DATELIB_J8_YAML},
{JAXRS_DATELIB_J8_JSON_INCLUDE_YAML}
{JAXRS_DATELIB_J8_JSON_INCLUDE_YAML},
{JAXRS_DATELIB_J8_DOUBLE_JSON},
{JAXRS_DATELIB_J8_DOUBLE_YAML},
{JAXRS_DATELIB_J8_NESTED_JSON},
{JAXRS_DATELIB_J8_NESTED_YAML},
{JAXRS_DATELIB_J8_NESTED_PROPERTY_MERGE_YAML}
};
}

View File

@@ -0,0 +1,4 @@
{
"!include": "jaxrs-datelib-j8.json",
"!include1": "common/jaxrs-datelib-j8.json"
}

View File

@@ -0,0 +1,2 @@
"!include": jaxrs-datelib-j8.yaml
"!include": common/jaxrs-datelib-j8.yaml

View File

@@ -0,0 +1,11 @@
---
"!include": common/jaxrs-datelib-j8.yaml
generatorName: jaxrs-jersey
# We expect this property to be ignored because it exists in the importing file
outputDir: outputDir-should-be-ignored
inputSpec: batch/specs/petstore.yaml
# This map should be ignored since it exists in the importing file
# We may want to consider merging additionalProperties, but that would depend on user need
additionalProperties:
hideGenerationTimestamp: true
serverPort: 'should-be-ignored'

View File

@@ -0,0 +1,9 @@
{
"!include": "common/jaxrs-datelib-j8.json",
"generatorName": "jaxrs-jersey",
"outputDir": "outputDir",
"additionalProperties": {
"hideGenerationTimestamp": true,
"serverPort": "8082"
}
}

View File

@@ -0,0 +1,7 @@
---
"!include": common/jaxrs-datelib-j8.yaml
generatorName: jaxrs-jersey
outputDir: outputDir
additionalProperties:
hideGenerationTimestamp: true
serverPort: '8082'

View File

@@ -0,0 +1,7 @@
---
"!include": jaxrs-datelib-j8-nested-include-property-merge.yaml
# We expect this one to "win"
outputDir: outputDir
additionalProperties:
hideGenerationTimestamp: true
serverPort: '8082'

View File

@@ -0,0 +1,4 @@
{
"!include": "jaxrs-datelib-j8-nested-include.json",
"inputSpec": "batch/specs/petstore.yaml"
}

View File

@@ -0,0 +1,3 @@
---
"!include": jaxrs-datelib-j8-nested-include.yaml
inputSpec: batch/specs/petstore.yaml

View File

@@ -6,7 +6,7 @@
<artifactId>openapi-generator-project</artifactId>
<groupId>org.openapitools</groupId>
<!-- RELEASE_VERSION -->
<version>5.0.0-beta2</version>
<version>5.0.0-SNAPSHOT</version>
<!-- /RELEASE_VERSION -->
<relativePath>../..</relativePath>
</parent>

View File

@@ -0,0 +1,125 @@
package org.openapitools.codegen.api;
import java.util.Objects;
import java.util.StringJoiner;
/**
* TemplateDefinition is a type which defines the basics of a template file and target output location.
*/
@SuppressWarnings("unused")
public class TemplateDefinition {
private final String templateFile;
private final String folder;
private final String destinationFilename;
protected TemplateFileType templateType;
/**
* <p>Constructor for TemplateDefinition.</p>
*
* @param templateFile a template path relative to user template or embedded template.
* @param destinationFilename a target output location for the file, relative to the output directory.
*/
public TemplateDefinition(String templateFile, String destinationFilename) {
this(templateFile, "", destinationFilename);
}
/**
* Parameter-less constructor for TemplateDefinition, used for simplified serialization (see DynamicSettings).
*/
public TemplateDefinition() {
this("", "", "");
}
/**
* <p>Constructor for TemplateDefinition.</p>
*
* @param templateFile a template path relative to user template or embedded template.
* @param folder a folder in the target output directory in which to place the target file.
* @param destinationFilename a target output location for the file, relative to the output directory.
*/
public TemplateDefinition(String templateFile, String folder, String destinationFilename) {
if (templateFile == null) throw new IllegalArgumentException("templateFile may not be null.");
if (folder == null) throw new IllegalArgumentException("folder may not be null.");
if (destinationFilename == null) throw new IllegalArgumentException("destinationFilename may not be null.");
this.templateFile = templateFile;
this.folder = folder;
this.destinationFilename = destinationFilename;
this.templateType = TemplateFileType.SupportingFiles;
}
/**
* Gets target output location for the file, relative to the output directory.
*
* @return a target output location for the file, relative to the output directory.
*/
public String getDestinationFilename() {
return destinationFilename;
}
/**
* Gets a folder in the target output directory in which to place the target file.
*
* @return a a folder in the target output directory in which to place the target file.
*/
public String getFolder() {
return folder;
}
/**
* Gets a template path relative to user template or embedded template.
*
* @return a template path relative to user template or embedded template.
*/
public String getTemplateFile() {
return templateFile;
}
/**
* Gets the type of template
*
* @return a {@link TemplateFileType} enum which defines the type of this template.
*/
public TemplateFileType getTemplateType() {
return templateType;
}
/**
* Sets the type of template
*
* @param templateType a {@link TemplateFileType} enum which defines the type of this template
*/
public void setTemplateType(TemplateFileType templateType) {
this.templateType = templateType;
}
/** {@inheritDoc} */
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof TemplateDefinition)) return false;
TemplateDefinition that = (TemplateDefinition) o;
return getTemplateFile().equals(that.getTemplateFile()) &&
getFolder().equals(that.getFolder()) &&
getDestinationFilename().equals(that.getDestinationFilename()) &&
getTemplateType() == that.getTemplateType();
}
/** {@inheritDoc} */
@Override
public int hashCode() {
return Objects.hash(getTemplateFile(), getFolder(), getDestinationFilename(), getTemplateType());
}
/** {@inheritDoc} */
@Override
public String toString() {
return new StringJoiner(", ", TemplateDefinition.class.getSimpleName() + "[", "]")
.add("templateFile='" + templateFile + "'")
.add("folder='" + folder + "'")
.add("destinationFilename='" + destinationFilename + "'")
.add("templateType=" + templateType)
.toString();
}
}

View File

@@ -0,0 +1,61 @@
package org.openapitools.codegen.api;
import java.util.StringJoiner;
/**
* Represents the type of a generator's templating files. These types of template files may be processed differently
* (multiple times per definition, or conditionally based on user or generator configuration).
*/
public enum TemplateFileType {
API(Constants.APIS),
Model(Constants.MODELS),
APIDocs(Constants.API_DOCS),
ModelDocs(Constants.MODEL_DOCS),
APITests(Constants.API_TESTS),
ModelTests(Constants.MODEL_TESTS),
SupportingFiles(Constants.SUPPORTING_FILES);
private final String templateType;
TemplateFileType(String templateType) { this.templateType = templateType; }
/**
* Returns the value for this template file type
*
* @return The template type of this enum.
*/
public String value() { return this.templateType; }
/** {@inheritDoc} */
@Override
public String toString() {
return new StringJoiner(", ", TemplateFileType.class.getSimpleName() + "[", "]")
.add("templateType='" + templateType + "'")
.toString();
}
/**
* Obtains the {@link TemplateFileType} for an input string.
*
* @param templateType a {@link java.lang.String} object.
* @return a {@link TemplateFileType} object.
*/
public static TemplateFileType forTemplateType(String templateType) {
for (TemplateFileType value : values()) {
if (value.templateType.equals(templateType)) {
return value;
}
}
throw new IllegalArgumentException("templateType not found in the available values.");
}
public static class Constants {
public static final String APIS = "apis";
public static final String MODELS = "models";
public static final String SUPPORTING_FILES = "supportingFiles";
public static final String MODEL_TESTS = "modelTests";
public static final String MODEL_DOCS = "modelDocs";
public static final String API_TESTS = "apiTests";
public static final String API_DOCS = "apiDocs";
}
}

View File

@@ -442,7 +442,7 @@ public class WorkflowSettings {
// check to see if the folder exists
if (f.exists() && f.isDirectory()) {
uri = f.toURI();
this.templateDir = Paths.get(uri).toAbsolutePath().toString();
this.templateDir = Paths.get(uri).toAbsolutePath().normalize().toString();
} else {
URL url = this.getClass().getClassLoader().getResource(templateDir);
if (url != null) {

View File

@@ -97,7 +97,7 @@ task validateGoodSpec(type: org.openapitools.generator.gradle.plugin.tasks.Valid
[source,group]
----
plugins {
id "org.openapi.generator" version "5.0.0-beta2"
id "org.openapi.generator" version "4.3.1"
}
----
@@ -113,7 +113,7 @@ buildscript {
// url "https://plugins.gradle.org/m2/"
}
dependencies {
classpath "org.openapitools:openapi-generator-gradle-plugin:5.0.0-beta2"
classpath "org.openapitools:openapi-generator-gradle-plugin:4.3.1"
}
}

View File

@@ -1,5 +1,5 @@
# RELEASE_VERSION
openApiGeneratorVersion=5.0.0-beta2
openApiGeneratorVersion=5.0.0-SNAPSHOT
# /RELEASE_VERSION
# BEGIN placeholders

View File

@@ -1,6 +1,5 @@
#Thu Jan 30 22:14:34 EST 2020
distributionUrl=https\://services.gradle.org/distributions/gradle-5.6.4-all.zip
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
zipStorePath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-5.6.4-all.zip
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists

View File

@@ -1,5 +1,21 @@
#!/usr/bin/env sh
#
# Copyright 2015 the original author or authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
##############################################################################
##
## Gradle start up script for UN*X
@@ -28,7 +44,7 @@ APP_NAME="Gradle"
APP_BASE_NAME=`basename "$0"`
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS=""
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
# Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD="maximum"
@@ -109,8 +125,8 @@ 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
# For Cygwin or MSYS, switch paths to Windows format before running java
if [ "$cygwin" = "true" -o "$msys" = "true" ] ; then
APP_HOME=`cygpath --path --mixed "$APP_HOME"`
CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
JAVACMD=`cygpath --unix "$JAVACMD"`

View File

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

View File

@@ -4,7 +4,7 @@
<groupId>org.openapitools</groupId>
<artifactId>openapi-generator-project</artifactId>
<!-- RELEASE_VERSION -->
<version>5.0.0-beta2</version>
<version>5.0.0-SNAPSHOT</version>
<!-- /RELEASE_VERSION -->
<relativePath>../..</relativePath>
</parent>
@@ -94,6 +94,7 @@
<tasks>
<!-- calls "clean assemble install" -->
<task>clean</task>
<task>check</task>
<task>assemble</task>
<task>publishToMavenLocal</task>
<task>publishPluginMavenPublicationToMavenLocal</task>

View File

@@ -18,5 +18,5 @@ gradle generateGoWithInvalidSpec # expected outcome: BUILD FAILED
The samples can be tested against other versions of the plugin using the `openApiGeneratorVersion` property. For example:
```bash
gradle -PopenApiGeneratorVersion=5.0.0-beta2 openApiValidate
gradle -PopenApiGeneratorVersion=4.3.0 openApiValidate
```

View File

@@ -5,6 +5,7 @@ import org.gradle.testkit.runner.TaskOutcome
import org.testng.annotations.Test
import java.io.File
import kotlin.test.assertEquals
import kotlin.test.assertFalse
import kotlin.test.assertTrue
class GenerateTaskDslTest : TestBase() {
@@ -78,17 +79,17 @@ class GenerateTaskDslTest : TestBase() {
// Act
val resultFirstRun = GradleRunner.create()
.withProjectDir(temp)
.withArguments("openApiGenerate")
.withArguments("openApiGenerate", "--info")
.withPluginClasspath()
.build()
val resultSecondRun = GradleRunner.create()
.withProjectDir(temp)
.withArguments("openApiGenerate")
.withArguments("openApiGenerate", "--info")
.withPluginClasspath()
.build()
// Assert
assertTrue(resultFirstRun.output.contains("Task ':openApiGenerate' is not up-to-date"), "First run should not be up-to-date")
assertFalse(resultFirstRun.output.contains("Task :openApiGenerate UP-TO-DATE"), "First run should not be up-to-date")
assertTrue(resultSecondRun.output.contains("Task :openApiGenerate UP-TO-DATE"), "Task of second run should be up-to-date")
}
@@ -103,7 +104,7 @@ class GenerateTaskDslTest : TestBase() {
// Act
val resultFirstRun = GradleRunner.create()
.withProjectDir(temp)
.withArguments("openApiGenerate", "--build-cache")
.withArguments("openApiGenerate", "--build-cache", "--info")
.withPluginClasspath()
.build()
@@ -113,13 +114,22 @@ class GenerateTaskDslTest : TestBase() {
// re-run
val resultSecondRun = GradleRunner.create()
.withProjectDir(temp)
.withArguments("openApiGenerate", "--build-cache")
.withArguments("openApiGenerate", "--build-cache", "--info")
.withPluginClasspath()
.build()
// re-run without deletes
val resultThirdRun = GradleRunner.create()
.withProjectDir(temp)
.withArguments("openApiGenerate", "--build-cache", "--info")
.withPluginClasspath()
.build()
// Assert
assertTrue(resultFirstRun.output.contains("Task ':openApiGenerate' is not up-to-date"), "First run should not be up-to-date")
assertTrue(resultSecondRun.output.contains("Task :openApiGenerate FROM-CACHE"), "Task of second run should be from cache")
assertTrue(resultFirstRun.output.contains("No history is available."), "First run should not be up-to-date")
assertFalse(resultSecondRun.output.contains("No history is available."), "Task of second run should be from cache")
assertTrue(resultSecondRun.output.contains("has been removed."), "Task of second run should detect cache changes for untracked files")
assertTrue(resultThirdRun.output.contains("Skipping task ':openApiGenerate' as it is up-to-date."), "Task of third run should not require rebuild")
}
@Test

View File

@@ -32,7 +32,7 @@ class ValidateTaskDslTest : TestBase() {
.buildAndFail()
// Assert
assertTrue(result.output.contains("unable to read location `some_location`"), "Unexpected/no message presented to the user for a spec pointing to an invalid URI.")
assertTrue(result.output.contains("some_location' specified for property 'inputSpec' does not exist"), "Unexpected/no message presented to the user for a spec pointing to an invalid URI.")
assertEquals(FAILED, result.task(":openApiValidate")?.outcome,
"Expected a failed run, but found ${result.task(":openApiValidate")?.outcome}")
}

View File

@@ -12,7 +12,7 @@ Add to your `build->plugins` section (default phase is `generate-sources` phase)
<groupId>org.openapitools</groupId>
<artifactId>openapi-generator-maven-plugin</artifactId>
<!-- RELEASE_VERSION -->
<version>5.0.0-beta2</version>
<version>4.3.1</version>
<!-- /RELEASE_VERSION -->
<executions>
<execution>

View File

@@ -13,7 +13,7 @@
<groupId>org.openapitools</groupId>
<artifactId>openapi-generator-maven-plugin</artifactId>
<!-- RELEASE_VERSION -->
<version>5.0.0-beta2</version>
<version>5.0.0-SNAPSHOT</version>
<!-- /RELEASE_VERSION -->
<executions>
<execution>

View File

@@ -19,7 +19,7 @@
<groupId>org.openapitools</groupId>
<artifactId>openapi-generator-maven-plugin</artifactId>
<!-- RELEASE_VERSION -->
<version>5.0.0-beta2</version>
<version>5.0.0-SNAPSHOT</version>
<!-- /RELEASE_VERSION -->
<dependencies>
<dependency>

View File

@@ -13,7 +13,7 @@
<groupId>org.openapitools</groupId>
<artifactId>openapi-generator-maven-plugin</artifactId>
<!-- RELEASE_VERSION -->
<version>5.0.0-beta2</version>
<version>5.0.0-SNAPSHOT</version>
<!-- /RELEASE_VERSION -->
<executions>
<execution>

View File

@@ -13,7 +13,7 @@
<groupId>org.openapitools</groupId>
<artifactId>openapi-generator-maven-plugin</artifactId>
<!-- RELEASE_VERSION -->
<version>5.0.0-beta2</version>
<version>5.0.0-SNAPSHOT</version>
<!-- /RELEASE_VERSION -->
<executions>
<execution>

View File

@@ -5,7 +5,7 @@
<groupId>org.openapitools</groupId>
<artifactId>openapi-generator-project</artifactId>
<!-- RELEASE_VERSION -->
<version>5.0.0-beta2</version>
<version>5.0.0-SNAPSHOT</version>
<!-- /RELEASE_VERSION -->
<relativePath>../..</relativePath>
</parent>
@@ -15,6 +15,7 @@
<description>maven plugin to build modules from OpenAPI Generator</description>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<sonar.exclusions>**/src/main/java/org/openapitools/codegen/plugin/**/*</sonar.exclusions>
</properties>
<dependencies>
<dependency>

View File

@@ -4,7 +4,7 @@
<groupId>org.openapitools</groupId>
<artifactId>openapi-generator-project</artifactId>
<!-- RELEASE_VERSION -->
<version>5.0.0-beta2</version>
<version>5.0.0-SNAPSHOT</version>
<!-- /RELEASE_VERSION -->
<relativePath>../..</relativePath>
</parent>
@@ -19,6 +19,7 @@
<springfox-version>3.0.0</springfox-version>
<junit-version>4.13</junit-version>
<jackson-version>2.10.2</jackson-version>
<sonar.exclusions>**/org/openapitools/codegen/online/**/*</sonar.exclusions>
</properties>
<dependencyManagement>
<dependencies>

View File

@@ -4,7 +4,7 @@
<groupId>org.openapitools</groupId>
<artifactId>openapi-generator-project</artifactId>
<!-- RELEASE_VERSION -->
<version>5.0.0-beta2</version>
<version>5.0.0-SNAPSHOT</version>
<!-- /RELEASE_VERSION -->
<relativePath>../..</relativePath>
</parent>

View File

@@ -20,6 +20,7 @@ package org.openapitools.codegen;
import io.swagger.v3.oas.models.OpenAPI;
import io.swagger.v3.parser.core.models.AuthorizationValue;
import org.openapitools.codegen.api.TemplateDefinition;
import org.openapitools.codegen.auth.AuthParser;
import java.util.List;
@@ -28,6 +29,7 @@ public class ClientOptInput {
private CodegenConfig config;
private OpenAPI openAPI;
private List<AuthorizationValue> auths;
private List<TemplateDefinition> userDefinedTemplates;
public ClientOptInput openAPI(OpenAPI openAPI) {
this.setOpenAPI(openAPI);
@@ -39,6 +41,11 @@ public class ClientOptInput {
return this;
}
public ClientOptInput userDefinedTemplates(List<TemplateDefinition> userDefinedTemplates) {
this.userDefinedTemplates = userDefinedTemplates;
return this;
}
@Deprecated
public ClientOptInput auth(String urlEncodedAuthString) {
this.setAuth(urlEncodedAuthString);
@@ -65,7 +72,14 @@ public class ClientOptInput {
return config;
}
public List<TemplateDefinition> getUserDefinedTemplates() {
// not deprecated as this is added to match other functionality, we need to move to Context<?> instead of ClientOptInput.
return userDefinedTemplates;
}
/**
* Sets the generator/config instance
*
* @deprecated use {@link #config(CodegenConfig)} instead
* @param config codegen config
*/
@@ -84,6 +98,8 @@ public class ClientOptInput {
}
/**
* Sets the OpenAPI document
*
* @deprecated use {@link #openAPI(OpenAPI)} instead
* @param openAPI the specification
*/

View File

@@ -292,4 +292,6 @@ public interface CodegenConfig {
boolean isRemoveEnumValuePrefix();
void setRemoveEnumValuePrefix(boolean removeEnumValuePrefix);
Schema unaliasSchema(Schema schema, Map<String, String> usedImportMappings);
}

View File

@@ -30,6 +30,7 @@ public class CodegenConstants {
public static final String MODEL_DOCS = "modelDocs";
public static final String API_TESTS = "apiTests";
public static final String API_DOCS = "apiDocs";
public static final String WITH_XML = "withXml";
public static final String SKIP_FORM_MODEL = "skipFormModel";
/* /end System Properties */

View File

@@ -550,6 +550,13 @@ public class CodegenModel implements IJsonSchemaValidationProperties {
this.multipleOf = multipleOf;
}
// indicates if the model component has validation on the root level schema
// this will be true when minItems or minProperties is set
public boolean hasValidation() {
boolean val = (maxItems != null || minItems != null || minProperties != null || maxProperties != null || minLength != null || maxLength != null || multipleOf != null || pattern != null || minimum != null || maximum != null || Boolean.TRUE.equals(uniqueItems) || Boolean.TRUE.equals(exclusiveMaximum) || Boolean.TRUE.equals(exclusiveMinimum));
return val;
}
public List<CodegenProperty> getReadOnlyVars() {
return readOnlyVars;
}

View File

@@ -247,6 +247,9 @@ public class DefaultCodegen implements CodegenConfig {
// make openapi available to all methods
protected OpenAPI openAPI;
// A cache to efficiently lookup a Schema instance based on the return value of `toModelName()`.
private Map<String, Schema> modelNameToSchemaCache;
public List<CliOption> cliOptions() {
return cliOptions;
}
@@ -391,19 +394,17 @@ public class DefaultCodegen implements CodegenConfig {
if (this.useOneOfInterfaces) {
// First, add newly created oneOf interfaces
for (CodegenModel cm : addOneOfInterfaces) {
Map<String, Object> modelValue = new HashMap<String, Object>() {{
putAll(additionalProperties());
put("model", cm);
}};
Map<String, Object> modelValue = new HashMap<>(additionalProperties());
modelValue.put("model", cm);
List<Object> modelsValue = Arrays.asList(modelValue);
List<Map<String, String>> importsValue = new ArrayList<Map<String, String>>();
Map<String, Object> objsValue = new HashMap<String, Object>() {{
put("models", modelsValue);
put("package", modelPackage());
put("imports", importsValue);
put("classname", cm.classname);
putAll(additionalProperties);
}};
Map<String, Object> objsValue = new HashMap<>();
objsValue.put("models", modelsValue);
objsValue.put("package", modelPackage());
objsValue.put("imports", importsValue);
objsValue.put("classname", cm.classname);
objsValue.putAll(additionalProperties);
objs.put(cm.name, objsValue);
}
@@ -450,6 +451,23 @@ public class DefaultCodegen implements CodegenConfig {
return objs;
}
/**
* Return a map from model name to Schema for efficient lookup.
*
* @return map from model name to Schema.
*/
protected Map<String, Schema> getModelNameToSchemaCache() {
if (modelNameToSchemaCache == null) {
// Create a cache to efficiently lookup schema based on model name.
Map<String, Schema> m = new HashMap<String, Schema>();
ModelUtils.getSchemas(openAPI).forEach((key, schema) -> {
m.put(toModelName(key), schema);
});
modelNameToSchemaCache = Collections.unmodifiableMap(m);
}
return modelNameToSchemaCache;
}
/**
* Index all CodegenModels by model name.
*
@@ -1293,14 +1311,13 @@ public class DefaultCodegen implements CodegenConfig {
* @param name the variable name
* @return the sanitized variable name
*/
public String toVarName(String name) {
public String toVarName(final String name) {
if (reservedWords.contains(name)) {
return escapeReservedWord(name);
} else if (((CharSequence) name).chars().anyMatch(character -> specialCharReplacements.keySet().contains("" + ((char) character)))) {
return escape(name, specialCharReplacements, null, null);
} else {
return name;
}
return name;
}
/**
@@ -1318,6 +1335,7 @@ public class DefaultCodegen implements CodegenConfig {
return escape(name, specialCharReplacements, null, null);
}
return name;
}
/**
@@ -1558,6 +1576,7 @@ public class DefaultCodegen implements CodegenConfig {
specialCharReplacements.put("<=", "Less_Than_Or_Equal_To");
specialCharReplacements.put(">=", "Greater_Than_Or_Equal_To");
specialCharReplacements.put("!=", "Not_Equal");
specialCharReplacements.put("~=", "Tilde_Equal");
}
/**
@@ -1971,7 +1990,7 @@ public class DefaultCodegen implements CodegenConfig {
return "oneOf<" + String.join(",", names) + ">";
}
protected Schema unaliasSchema(Schema schema, Map<String, String> usedImportMappings) {
public Schema unaliasSchema(Schema schema, Map<String, String> usedImportMappings) {
return ModelUtils.unaliasSchema(this.openAPI, schema, usedImportMappings);
}
@@ -2195,7 +2214,8 @@ public class DefaultCodegen implements CodegenConfig {
}
/**
* Output the proper model name (capitalized).
* Converts the OpenAPI schema name to a model name suitable for the current code generator.
* May be overriden for each programming language.
* In case the name belongs to the TypeSystem it won't be renamed.
*
* @param name the name of the model
@@ -2205,8 +2225,33 @@ public class DefaultCodegen implements CodegenConfig {
return camelize(modelNamePrefix + "_" + name + "_" + modelNameSuffix);
}
private static class NamedSchema {
private NamedSchema(String name, Schema s) {
this.name = name;
this.schema = s;
}
private String name;
private Schema schema;
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
NamedSchema that = (NamedSchema) o;
return Objects.equals(name, that.name) &&
Objects.equals(schema, that.schema);
}
@Override
public int hashCode() {
return Objects.hash(name, schema);
}
}
Map<NamedSchema, CodegenProperty> schemaCodegenPropertyCache = new HashMap<NamedSchema, CodegenProperty>();
/**
* Convert OAS Model object to Codegen Model object
* Convert OAS Model object to Codegen Model object.
*
* @param name the name of the model
* @param schema OAS Model object
@@ -2272,6 +2317,7 @@ public class DefaultCodegen implements CodegenConfig {
m.isArrayModel = true;
m.arrayModelType = fromProperty(name, schema).complexType;
addParentContainer(m, name, schema);
ModelUtils.syncValidationProperties(schema, m);
} else if (schema instanceof ComposedSchema) {
final ComposedSchema composed = (ComposedSchema) schema;
Map<String, Schema> properties = new LinkedHashMap<String, Schema>();
@@ -2490,6 +2536,9 @@ public class DefaultCodegen implements CodegenConfig {
} else { // type is number and without format
m.isNumber = Boolean.TRUE;
}
} else if (ModelUtils.isFreeFormObject(openAPI, schema)) {
addAdditionPropertiesToCodeGenModel(m, schema);
ModelUtils.syncValidationProperties(schema, m);
}
if (Boolean.TRUE.equals(schema.getNullable())) {
@@ -2561,7 +2610,6 @@ public class DefaultCodegen implements CodegenConfig {
postProcessModelProperty(m, prop);
}
}
return m;
}
@@ -2655,7 +2703,8 @@ public class DefaultCodegen implements CodegenConfig {
if (foundDisc != null) {
return foundDisc;
}
if (!!this.getLegacyDiscriminatorBehavior()) {
if (this.getLegacyDiscriminatorBehavior()) {
return null;
}
Discriminator disc = new Discriminator();
@@ -2693,7 +2742,7 @@ public class DefaultCodegen implements CodegenConfig {
throw new RuntimeException("The oneOf schemas have conflicting discriminator property names. " +
"oneOf schemas must have the same property name, but found " + String.join(", ", discriminatorsPropNames));
}
if ((hasDiscriminatorCnt + hasNullTypeCnt) == composedSchema.getOneOf().size() && discriminatorsPropNames.size() == 1) {
if (foundDisc != null && (hasDiscriminatorCnt + hasNullTypeCnt) == composedSchema.getOneOf().size() && discriminatorsPropNames.size() == 1) {
disc.setPropertyName(foundDisc.getPropertyName());
disc.setMapping(foundDisc.getMapping());
return disc;
@@ -2722,7 +2771,7 @@ public class DefaultCodegen implements CodegenConfig {
throw new RuntimeException("The anyOf schemas have conflicting discriminator property names. " +
"anyOf schemas must have the same property name, but found " + String.join(", ", discriminatorsPropNames));
}
if ((hasDiscriminatorCnt + hasNullTypeCnt) == composedSchema.getAnyOf().size() && discriminatorsPropNames.size() == 1) {
if (foundDisc != null && (hasDiscriminatorCnt + hasNullTypeCnt) == composedSchema.getAnyOf().size() && discriminatorsPropNames.size() == 1) {
disc.setPropertyName(foundDisc.getPropertyName());
disc.setMapping(foundDisc.getMapping());
return disc;
@@ -2811,9 +2860,13 @@ public class DefaultCodegen implements CodegenConfig {
List<MappedModel> descendentSchemas = new ArrayList();
Map<String, Schema> schemas = ModelUtils.getSchemas(openAPI);
String currentSchemaName = thisSchemaName;
while (true) {
for (String childName : schemas.keySet()) {
if (childName == thisSchemaName) {
Set<String> keys = schemas.keySet();
int count = 0;
// hack: avoid infinite loop on potential self-references in event our checks fail.
while (100000 > count++) {
for (String childName : keys) {
if (childName.equals(thisSchemaName)) {
continue;
}
Schema child = schemas.get(childName);
@@ -2826,13 +2879,12 @@ public class DefaultCodegen implements CodegenConfig {
if (ref == null) {
// for schemas with no ref, it is not possible to build the discriminator map
// because ref is how we get the model name
// we only hit this use case for a schema with inline composed schemas, and one of those
// schemas also has inline composed schemas
throw new RuntimeException("Invalid inline schema defined in allOf in '" + childName + "'. Per the OpenApi spec, for this case when a composed schema defines a discriminator, the allOf schemas must use $ref. Change this inline definition to a $ref definition");
// we hit this use case when an allOf composed schema contains an inline schema
continue;
}
String parentName = ModelUtils.getSimpleRef(ref);
if (parentName.equals(currentSchemaName)) {
if (queue.contains(childName) || descendentSchemas.contains(childName)) {
if (parentName != null && parentName.equals(currentSchemaName)) {
if (queue.contains(childName) || descendentSchemas.stream().anyMatch(i -> childName.equals(i.getMappingName()))) {
throw new RuntimeException("Stack overflow hit when looking for " + thisSchemaName + " an infinite loop starting and ending at " + childName + " was seen");
}
queue.add(childName);
@@ -2981,7 +3033,13 @@ public class DefaultCodegen implements CodegenConfig {
}
/**
* Convert OAS Property object to Codegen Property object
* Convert OAS Property object to Codegen Property object.
*
* The return value is cached. An internal cache is looked up to determine
* if the CodegenProperty return value has already been instantiated for
* the (String name, Schema p) arguments.
* Any subsequent processing of the CodegenModel return value must be idempotent
* for a given (String name, Schema schema).
*
* @param name name of the property
* @param p OAS property schema
@@ -2993,7 +3051,12 @@ public class DefaultCodegen implements CodegenConfig {
return null;
}
LOGGER.debug("debugging fromProperty for " + name + " : " + p);
NamedSchema ns = new NamedSchema(name, p);
CodegenProperty cpc = schemaCodegenPropertyCache.get(ns);
if (cpc != null) {
LOGGER.debug("Cached fromProperty for " + name + " : " + p.getName());
return cpc;
}
// unalias schema
p = unaliasSchema(p, importMapping);
@@ -3293,6 +3356,7 @@ public class DefaultCodegen implements CodegenConfig {
}
LOGGER.debug("debugging from property return: " + property);
schemaCodegenPropertyCache.put(ns, property);
return property;
}
@@ -3540,7 +3604,10 @@ public class DefaultCodegen implements CodegenConfig {
op.hasReference = schemas != null && schemas.containsKey(op.returnBaseType);
// lookup discriminator
Schema schema = schemas.get(op.returnBaseType);
Schema schema = null;
if (schemas != null) {
schema = schemas.get(op.returnBaseType);
}
if (schema != null) {
CodegenModel cmod = fromModel(op.returnBaseType, schema);
op.discriminator = cmod.discriminator;
@@ -4759,7 +4826,6 @@ public class DefaultCodegen implements CodegenConfig {
final String key = entry.getKey();
final Schema prop = entry.getValue();
if (prop == null) {
LOGGER.warn("Please report the issue. There shouldn't be null property for " + key);
} else {
@@ -6379,6 +6445,9 @@ public class DefaultCodegen implements CodegenConfig {
.featureSet(builder.build()).build();
}
/**
* An map entry for cached sanitized names.
*/
private static class SanitizeNameOptions {
public SanitizeNameOptions(String name, String removeCharRegEx, List<String> exceptions) {
this.name = name;
@@ -6386,7 +6455,7 @@ public class DefaultCodegen implements CodegenConfig {
if (exceptions != null) {
this.exceptions = Collections.unmodifiableList(exceptions);
} else {
this.exceptions = Collections.unmodifiableList(new ArrayList<>());
this.exceptions = Collections.emptyList();
}
}

View File

@@ -17,6 +17,7 @@
package org.openapitools.codegen;
import com.google.common.collect.ImmutableList;
import io.swagger.v3.core.util.Json;
import io.swagger.v3.oas.models.OpenAPI;
import io.swagger.v3.oas.models.Operation;
@@ -29,13 +30,16 @@ import io.swagger.v3.oas.models.media.Schema;
import io.swagger.v3.oas.models.parameters.Parameter;
import io.swagger.v3.oas.models.security.*;
import io.swagger.v3.oas.models.tags.Tag;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.io.comparator.PathFileComparator;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.openapitools.codegen.api.TemplateDefinition;
import org.openapitools.codegen.api.TemplatePathLocator;
import org.openapitools.codegen.api.TemplateProcessor;
import org.openapitools.codegen.config.GlobalSettings;
import org.openapitools.codegen.api.TemplatingEngineAdapter;
import org.openapitools.codegen.api.TemplateFileType;
import org.openapitools.codegen.ignore.CodegenIgnoreProcessor;
import org.openapitools.codegen.languages.PythonClientExperimentalCodegen;
import org.openapitools.codegen.meta.GeneratorMetadata;
@@ -58,6 +62,7 @@ import java.nio.charset.StandardCharsets;
import java.nio.file.Path;
import java.time.ZonedDateTime;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;
import static org.apache.commons.lang3.StringUtils.removeStart;
@@ -86,6 +91,8 @@ public class DefaultGenerator implements Generator {
private Map<String, String> generatorPropertyDefaults = new HashMap<>();
protected TemplateProcessor templateProcessor = null;
private List<TemplateDefinition> userDefinedTemplates = new ArrayList<>();
public DefaultGenerator() {
this(false);
@@ -102,6 +109,10 @@ public class DefaultGenerator implements Generator {
this.opts = opts;
this.openAPI = opts.getOpenAPI();
this.config = opts.getConfig();
List<TemplateDefinition> userFiles = opts.getUserDefinedTemplates();
if (userFiles != null) {
this.userDefinedTemplates = ImmutableList.copyOf(userFiles);
}
TemplateManagerOptions templateManagerOptions = new TemplateManagerOptions(this.config.isEnableMinimalUpdate(),this.config.isSkipOverwrite());
@@ -448,8 +459,19 @@ public class DefaultGenerator implements Generator {
Schema schema = schemas.get(name);
if (ModelUtils.isFreeFormObject(this.openAPI, schema)) { // check to see if it'a a free-form object
LOGGER.info("Model {} not generated since it's a free-form object", name);
continue;
// there are 3 free form use cases
// 1. free form with no validation that is not allOf included in any composed schemas
// 2. free form with validation
// 3. free form that is allOf included in any composed schemas
// this use case arises when using interface schemas
// generators may choose to make models for use case 2 + 3
Schema refSchema = new Schema();
refSchema.set$ref("#/components/schemas/"+name);
Schema unaliasedSchema = config.unaliasSchema(refSchema, config.importMapping());
if (unaliasedSchema.get$ref() == null) {
LOGGER.info("Model {} not generated since it's a free-form object", name);
continue;
}
} else if (ModelUtils.isMapSchema(schema)) { // check to see if it's a "map" model
// A composed schema (allOf, oneOf, anyOf) is considered a Map schema if the additionalproperties attribute is set
// for that composed schema. However, in the case of a composed schema, the properties are defined or referenced
@@ -679,8 +701,8 @@ public class DefaultGenerator implements Generator {
for (SupportingFile support : config.supportingFiles()) {
try {
String outputFolder = config.outputFolder();
if (StringUtils.isNotEmpty(support.folder)) {
outputFolder += File.separator + support.folder;
if (StringUtils.isNotEmpty(support.getFolder())) {
outputFolder += File.separator + support.getFolder();
}
File of = new File(outputFolder);
if (!of.isDirectory()) {
@@ -688,20 +710,20 @@ public class DefaultGenerator implements Generator {
once(LOGGER).debug("Output directory {} not created. It {}.", outputFolder, of.exists() ? "already exists." : "may not have appropriate permissions.");
}
}
String outputFilename = new File(support.destinationFilename).isAbsolute() // split
? support.destinationFilename
: outputFolder + File.separator + support.destinationFilename.replace('/', File.separatorChar);
String outputFilename = new File(support.getDestinationFilename()).isAbsolute() // split
? support.getDestinationFilename()
: outputFolder + File.separator + support.getDestinationFilename().replace('/', File.separatorChar);
boolean shouldGenerate = true;
if (supportingFilesToGenerate != null && !supportingFilesToGenerate.isEmpty()) {
shouldGenerate = supportingFilesToGenerate.contains(support.destinationFilename);
shouldGenerate = supportingFilesToGenerate.contains(support.getDestinationFilename());
}
File written = processTemplateToFile(bundle, support.templateFile, outputFilename, shouldGenerate, CodegenConstants.SUPPORTING_FILES);
File written = processTemplateToFile(bundle, support.getTemplateFile(), outputFilename, shouldGenerate, CodegenConstants.SUPPORTING_FILES);
if (written != null) {
files.add(written);
if (config.isEnablePostProcessFile() && !dryRun) {
config.postProcessFile(written, "api-doc");
config.postProcessFile(written, "supporting-file");
}
}
} catch (Exception e) {
@@ -753,6 +775,9 @@ public class DefaultGenerator implements Generator {
bundle.put("basePathWithoutHost", basePathWithoutHost);
bundle.put("scheme", URLPathUtils.getScheme(url, config));
bundle.put("host", url.getHost());
if (url.getPort() != 80 ) {
bundle.put("port", url.getPort());
}
bundle.put("contextPath", contextPath);
bundle.put("apiInfo", apis);
bundle.put("models", allModels);
@@ -845,6 +870,8 @@ public class DefaultGenerator implements Generator {
config.processOpenAPI(openAPI);
processUserDefinedTemplates();
List<File> files = new ArrayList<>();
// models
List<String> filteredSchemas = ModelUtils.getSchemasUsedOnlyInFormParam(openAPI);
@@ -908,6 +935,76 @@ public class DefaultGenerator implements Generator {
return files;
}
private void processUserDefinedTemplates() {
// TODO: initial behavior is "merge" user defined with built-in templates. consider offering user a "replace" option.
if (userDefinedTemplates != null && !userDefinedTemplates.isEmpty()) {
Map<String, SupportingFile> supportingFilesMap = config.supportingFiles().stream()
.collect(Collectors.toMap(TemplateDefinition::getTemplateFile, Function.identity()));
// TemplateFileType.SupportingFiles
userDefinedTemplates.stream()
.filter(i -> i.getTemplateType().equals(TemplateFileType.SupportingFiles))
.forEach(userDefinedTemplate -> {
SupportingFile newFile = new SupportingFile(
userDefinedTemplate.getTemplateFile(),
userDefinedTemplate.getFolder(),
userDefinedTemplate.getDestinationFilename()
);
if (supportingFilesMap.containsKey(userDefinedTemplate.getTemplateFile())) {
SupportingFile f = supportingFilesMap.get(userDefinedTemplate.getTemplateFile());
config.supportingFiles().remove(f);
if (!f.isCanOverwrite()) {
newFile.doNotOverwrite();
}
}
config.supportingFiles().add(newFile);
});
// Others, excluding TemplateFileType.SupportingFiles
userDefinedTemplates.stream()
.filter(i -> !i.getTemplateType().equals(TemplateFileType.SupportingFiles))
.forEach(userDefinedTemplate -> {
// determine file extension…
// if template is in format api.ts.mustache, we'll extract .ts
// if user has provided an example destination filename, we'll use that extension
String templateFile = userDefinedTemplate.getTemplateFile();
int lastSeparator = templateFile.lastIndexOf('.');
String templateExt = FilenameUtils.getExtension(templateFile.substring(0, lastSeparator));
if (StringUtils.isBlank(templateExt)) {
// hack: destination filename in this scenario might be a suffix like Impl.java
templateExt = userDefinedTemplate.getDestinationFilename();
} else {
templateExt = StringUtils.prependIfMissing(templateExt, ".");
}
switch (userDefinedTemplate.getTemplateType()) {
case API:
config.apiTemplateFiles().put(templateFile, templateExt);
break;
case Model:
config.modelTemplateFiles().put(templateFile, templateExt);
break;
case APIDocs:
config.apiDocTemplateFiles().put(templateFile, templateExt);
break;
case ModelDocs:
config.modelDocTemplateFiles().put(templateFile, templateExt);
break;
case APITests:
config.apiTestTemplateFiles().put(templateFile, templateExt);
break;
case ModelTests:
config.modelTestTemplateFiles().put(templateFile, templateExt);
break;
case SupportingFiles:
// excluded by filter
break;
}
});
}
}
protected File processTemplateToFile(Map<String, Object> templateData, String templateName, String outputFilename, boolean shouldGenerate, String skippedByOption) throws IOException {
String adjustedOutputFilename = outputFilename.replaceAll("//", "/").replace('/', File.separatorChar);
File target = new File(adjustedOutputFilename);

View File

@@ -17,53 +17,28 @@
package org.openapitools.codegen;
import java.util.Objects;
import org.openapitools.codegen.api.TemplateDefinition;
import org.openapitools.codegen.api.TemplateFileType;
public class SupportingFile {
public String templateFile;
public String folder;
public String destinationFilename;
public boolean canOverwrite = true;
import java.util.Objects;
import java.util.StringJoiner;
/**
* Defines the template definition for a "supporting file", that is any file which is generic and not bound to
* api/model definitions and their relevant docs or tests.
*
* Supporting files are generated once for an entire application while api/model bound definitions are generated multiple
* times according to their target use.
*/
public class SupportingFile extends TemplateDefinition {
private boolean canOverwrite = true;
public SupportingFile(String templateFile, String destinationFilename) {
this(templateFile, "", destinationFilename);
}
public SupportingFile(String templateFile, String folder, String destinationFilename) {
this.templateFile = templateFile;
this.folder = folder;
this.destinationFilename = destinationFilename;
}
@Override
public int hashCode() {
return Objects.hash(templateFile, folder, destinationFilename, canOverwrite);
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
SupportingFile that = (SupportingFile) o;
return Objects.equals(templateFile, that.templateFile) &&
Objects.equals(folder, that.folder) &&
Objects.equals(destinationFilename, that.destinationFilename) &&
canOverwrite == that.canOverwrite;
}
@SuppressWarnings("StringBufferReplaceableByString")
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("SupportingFile:").append("\n");
builder.append("\ttemplateFile: ").append(templateFile).append("\n");
builder.append("\tfolder: ").append(folder).append("\n");
builder.append("\tcanOverwrite: ").append(Boolean.valueOf(canOverwrite)).append("\n");
builder.append("\tdestinationFilename: ").append(destinationFilename).append("\n");
return builder.toString();
super(templateFile, folder, destinationFilename);
}
/**
@@ -75,6 +50,54 @@ public class SupportingFile {
canOverwrite = false;
return this;
}
/**
* Sets the type of template
*
* @param templateType a {@link TemplateFileType} enum which defines the type of this template
*/
@Override
public void setTemplateType(TemplateFileType templateType) {
}
/**
* Gets the type of template
*
* @return a {@link TemplateFileType} enum which defines the type of this template.
*/
@Override
public TemplateFileType getTemplateType() {
return TemplateFileType.SupportingFiles;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof SupportingFile)) return false;
if (!super.equals(o)) return false;
SupportingFile that = (SupportingFile) o;
return isCanOverwrite() == that.isCanOverwrite();
}
public boolean isCanOverwrite() {
return canOverwrite;
}
@Override
public int hashCode() {
return Objects.hash(super.hashCode(), isCanOverwrite());
}
@Override
public String toString() {
return new StringJoiner(", ", SupportingFile.class.getSimpleName() + "[", "]")
.add("templateFile='" + getTemplateFile() + "'")
.add("folder='" + getFolder() + "'")
.add("destinationFilename='" + getDestinationFilename() + "'")
.add("canOverwrite=" + isCanOverwrite())
.toString();
}
}

View File

@@ -31,6 +31,7 @@ import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.Validate;
import org.openapitools.codegen.*;
import org.openapitools.codegen.api.TemplateDefinition;
import org.openapitools.codegen.api.TemplatingEngineAdapter;
import org.openapitools.codegen.auth.AuthParser;
import org.openapitools.codegen.utils.ModelUtils;
@@ -72,6 +73,8 @@ public class CodegenConfigurator {
private Map<String, String> serverVariables = new HashMap<>();
private String auth;
private List<TemplateDefinition> userDefinedTemplates = new ArrayList<>();
public CodegenConfigurator() {
}
@@ -86,6 +89,7 @@ public class CodegenConfigurator {
GeneratorSettings generatorSettings = settings.getGeneratorSettings();
WorkflowSettings workflowSettings = settings.getWorkflowSettings();
List<TemplateDefinition> userDefinedTemplateSettings = settings.getFiles();
// We copy "cached" properties into configurator so it is appropriately configured with all settings in external files.
// FIXME: target is to eventually move away from CodegenConfigurator properties except gen/workflow settings.
@@ -120,6 +124,10 @@ public class CodegenConfigurator {
configurator.generatorSettingsBuilder = GeneratorSettings.newBuilder(generatorSettings);
configurator.workflowSettingsBuilder = WorkflowSettings.newBuilder(workflowSettings);
if (userDefinedTemplateSettings != null) {
configurator.userDefinedTemplates.addAll(userDefinedTemplateSettings);
}
return configurator;
}
return null;
@@ -604,7 +612,8 @@ public class CodegenConfigurator {
}
ClientOptInput input = new ClientOptInput()
.config(config);
.config(config)
.userDefinedTemplates(userDefinedTemplates);
return input.openAPI((OpenAPI)context.getSpecDocument());
}

View File

@@ -2,19 +2,21 @@ package org.openapitools.codegen.config;
import com.fasterxml.jackson.annotation.JsonAnySetter;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonUnwrapped;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import org.apache.commons.lang3.StringUtils;
import org.openapitools.codegen.api.TemplateDefinition;
import org.openapitools.codegen.api.TemplateFileType;
import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.*;
import java.util.stream.Collectors;
/**
* Represents a serialization helper of {@link GeneratorSettings} and {@link WorkflowSettings}. When used to deserialize any available Jackson binding input,
* this will accumulate any "unknown properties" into {@link GeneratorSettings#getAdditionalProperties()} as a side effect of calling
* {@link DynamicSettings#getGeneratorSettings()}.
* Represents a serialization helper of {@link org.openapitools.codegen.config.GeneratorSettings} and {@link org.openapitools.codegen.config.WorkflowSettings}. When used to deserialize any available Jackson binding input,
* this will accumulate any "unknown properties" into {@link org.openapitools.codegen.config.GeneratorSettings#getAdditionalProperties()} as a side effect of calling
* {@link org.openapitools.codegen.config.DynamicSettings#getGeneratorSettings()}.
*/
@SuppressWarnings({"unused", "WeakerAccess"})
public class DynamicSettings {
@@ -30,7 +32,33 @@ public class DynamicSettings {
private WorkflowSettings workflowSettings;
/**
* Gets the {@link GeneratorSettings} included in the config object.
* Gets the list of template files allowing user redefinition and addition of templating files
*
* @return A list of template files
*/
public List<TemplateDefinition> getFiles() {
if (files == null) return new ArrayList<>();
return files.entrySet().stream().map(kvp -> {
TemplateDefinition file = kvp.getValue();
String templateFile = kvp.getKey();
String destination = file.getDestinationFilename();
if (TemplateFileType.SupportingFiles.equals(file.getTemplateType()) && StringUtils.isBlank(destination)) {
// this special case allows definitions such as LICENSE:{}
destination = templateFile;
}
TemplateDefinition definition = new TemplateDefinition(templateFile, file.getFolder(), destination);
definition.setTemplateType(file.getTemplateType());
return definition;
}).collect(Collectors.toList());
}
@SuppressWarnings("MismatchedQueryAndUpdateOfCollection")
@JsonProperty("files")
private Map<String, TemplateDefinition> files;
/**
* Gets the {@link org.openapitools.codegen.config.GeneratorSettings} included in the config object.
*
* @return A new instance of settings
*/
@@ -47,7 +75,7 @@ public class DynamicSettings {
}
/**
* Gets the {@link WorkflowSettings} included in the config object.
* Gets the {@link org.openapitools.codegen.config.WorkflowSettings} included in the config object.
*
* @return A new instance of settings
*/
@@ -57,6 +85,9 @@ public class DynamicSettings {
.build();
}
/**
* <p>Constructor for DynamicSettings.</p>
*/
@JsonCreator
public DynamicSettings() { }

View File

@@ -38,11 +38,10 @@ import org.slf4j.LoggerFactory;
import java.io.File;
import java.time.LocalDate;
import java.time.OffsetDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.regex.Pattern;
import java.util.stream.Stream;
import static org.openapitools.codegen.utils.StringUtils.*;
@@ -60,6 +59,7 @@ public abstract class AbstractJavaCodegen extends DefaultCodegen implements Code
public static final String SUPPORT_JAVA6 = "supportJava6";
public static final String DISABLE_HTML_ESCAPING = "disableHtmlEscaping";
public static final String BOOLEAN_GETTER_PREFIX = "booleanGetterPrefix";
public static final String IGNORE_ANYOF_IN_ENUM = "ignoreAnyOfInEnum";
public static final String ADDITIONAL_MODEL_TYPE_ANNOTATIONS = "additionalModelTypeAnnotations";
public static final String DISCRIMINATOR_CASE_SENSITIVE = "discriminatorCaseSensitive";
public static final String OPENAPI_NULLABLE = "openApiNullable";
@@ -85,7 +85,8 @@ public abstract class AbstractJavaCodegen extends DefaultCodegen implements Code
protected String licenseUrl = "http://unlicense.org";
protected String projectFolder = "src/main";
protected String projectTestFolder = "src/test";
protected String sourceFolder = projectFolder + File.separator + "java";
// this must not be OS-specific
protected String sourceFolder = projectFolder + "/java";
protected String testFolder = projectTestFolder + "/java";
protected boolean fullJavaUtil;
protected boolean discriminatorCaseSensitive = true; // True if the discriminator value lookup should be case-sensitive.
@@ -97,6 +98,7 @@ public abstract class AbstractJavaCodegen extends DefaultCodegen implements Code
protected boolean supportJava6 = false;
protected boolean disableHtmlEscaping = false;
protected String booleanGetterPrefix = "get";
protected boolean ignoreAnyOfInEnum = false;
protected String parentGroupId = "";
protected String parentArtifactId = "";
protected String parentVersion = "";
@@ -220,6 +222,7 @@ public abstract class AbstractJavaCodegen extends DefaultCodegen implements Code
cliOptions.add(CliOption.newBoolean(DISABLE_HTML_ESCAPING, "Disable HTML escaping of JSON strings when using gson (needed to avoid problems with byte[] fields)", disableHtmlEscaping));
cliOptions.add(CliOption.newString(BOOLEAN_GETTER_PREFIX, "Set booleanGetterPrefix").defaultValue(this.getBooleanGetterPrefix()));
cliOptions.add(CliOption.newBoolean(IGNORE_ANYOF_IN_ENUM, "Ignore anyOf keyword in enum", ignoreAnyOfInEnum));
cliOptions.add(CliOption.newString(ADDITIONAL_MODEL_TYPE_ANNOTATIONS, "Additional annotations for model type(class level annotations)"));
cliOptions.add(CliOption.newBoolean(OPENAPI_NULLABLE, "Enable OpenAPI Jackson Nullable library", this.openApiNullable));
@@ -259,6 +262,11 @@ public abstract class AbstractJavaCodegen extends DefaultCodegen implements Code
}
additionalProperties.put(BOOLEAN_GETTER_PREFIX, booleanGetterPrefix);
if (additionalProperties.containsKey(IGNORE_ANYOF_IN_ENUM)) {
this.setIgnoreAnyOfInEnum(Boolean.valueOf(additionalProperties.get(IGNORE_ANYOF_IN_ENUM).toString()));
}
additionalProperties.put(IGNORE_ANYOF_IN_ENUM, ignoreAnyOfInEnum);
if (additionalProperties.containsKey(ADDITIONAL_MODEL_TYPE_ANNOTATIONS)) {
String additionalAnnotationsList = additionalProperties.get(ADDITIONAL_MODEL_TYPE_ANNOTATIONS).toString();
@@ -799,17 +807,11 @@ public abstract class AbstractJavaCodegen extends DefaultCodegen implements Code
if (ModelUtils.isArraySchema(schema)) {
final String pattern;
if (ModelUtils.isSet(schema)) {
if (fullJavaUtil) {
pattern = "new java.util.LinkedHashSet<%s>()";
} else {
pattern = "new LinkedHashSet<%s>()";
}
String mapInstantiationType = instantiationTypes().getOrDefault("set", "LinkedHashSet");
pattern = "new " + mapInstantiationType + "<%s>()";
} else {
if (fullJavaUtil) {
pattern = "new java.util.ArrayList<%s>()";
} else {
pattern = "new ArrayList<%s>()";
}
String arrInstantiationType = instantiationTypes().getOrDefault("array", "ArrayList");
pattern = "new " + arrInstantiationType + "<%s>()";
}
Schema<?> items = getSchemaItems((ArraySchema) schema);
@@ -832,12 +834,10 @@ public abstract class AbstractJavaCodegen extends DefaultCodegen implements Code
}
return null;
}
final String pattern;
if (fullJavaUtil) {
pattern = "new java.util.HashMap<%s>()";
} else {
pattern = "new HashMap<%s>()";
}
String mapInstantiationType = instantiationTypes().getOrDefault("map", "HashMap");
final String pattern = "new " + mapInstantiationType + "<%s>()";
if (getAdditionalProperties(schema) == null) {
return null;
}
@@ -1172,6 +1172,28 @@ public abstract class AbstractJavaCodegen extends DefaultCodegen implements Code
}
additionalProperties.put(CodegenConstants.ARTIFACT_VERSION, artifactVersion);
if (ignoreAnyOfInEnum) {
// Alter OpenAPI schemas ignore anyOf keyword if it consist of an enum. Example:
// anyOf:
// - type: string
// enum:
// - ENUM_A
// - ENUM_B
Stream.concat(
Stream.of(openAPI.getComponents().getSchemas()),
openAPI.getComponents().getSchemas().values().stream()
.filter(schema -> schema.getProperties() != null)
.map(Schema::getProperties))
.forEach(schemas -> schemas.replaceAll(
(name, s) -> Stream.of(s)
.filter(schema -> schema instanceof ComposedSchema)
.map(schema -> (ComposedSchema) schema)
.filter(schema -> Objects.nonNull(schema.getAnyOf()))
.flatMap(schema -> schema.getAnyOf().stream())
.filter(schema -> Objects.nonNull(schema.getEnum()))
.findFirst()
.orElse((Schema) s)));
}
}
private static String getAccept(OpenAPI openAPI, Operation operation) {
@@ -1523,6 +1545,10 @@ public abstract class AbstractJavaCodegen extends DefaultCodegen implements Code
this.booleanGetterPrefix = booleanGetterPrefix;
}
public void setIgnoreAnyOfInEnum(boolean ignoreAnyOfInEnum) {
this.ignoreAnyOfInEnum = ignoreAnyOfInEnum;
}
public boolean isOpenApiNullable() {
return openApiNullable;
}

View File

@@ -17,9 +17,11 @@
package org.openapitools.codegen.languages;
import com.google.common.annotations.VisibleForTesting;
import io.swagger.v3.oas.models.OpenAPI;
import io.swagger.v3.oas.models.Operation;
import io.swagger.v3.oas.models.PathItem;
import org.apache.commons.lang3.StringUtils;
import org.openapitools.codegen.*;
import org.openapitools.codegen.languages.features.BeanValidationFeatures;
import org.openapitools.codegen.utils.URLPathUtils;
@@ -30,10 +32,10 @@ import java.io.File;
import java.net.URL;
import java.util.*;
import static org.openapitools.codegen.utils.StringUtils.camelize;
public abstract class AbstractJavaJAXRSServerCodegen extends AbstractJavaCodegen implements BeanValidationFeatures {
public static final String SERVER_PORT = "serverPort";
public static final String USE_TAGS = "useTags";
/**
* Name of the sub-directory in "src/main/resource" where to find the
* Mustache template for the JAX-RS Codegen.
@@ -43,7 +45,9 @@ public abstract class AbstractJavaJAXRSServerCodegen extends AbstractJavaCodegen
protected String testResourcesFolder = "src/test/resources";
protected String title = "OpenAPI Server";
protected String serverPort = "8080";
protected boolean useBeanValidation = true;
protected boolean useTags = false;
private static final Logger LOGGER = LoggerFactory.getLogger(AbstractJavaJAXRSServerCodegen.class);
@@ -72,6 +76,7 @@ public abstract class AbstractJavaJAXRSServerCodegen extends AbstractJavaCodegen
cliOptions.add(new CliOption("title", "a title describing the application").defaultValue(title));
cliOptions.add(CliOption.newBoolean(USE_BEANVALIDATION, "Use BeanValidation API annotations",useBeanValidation));
cliOptions.add(new CliOption(SERVER_PORT, "The port on which the server should be started").defaultValue(serverPort));
cliOptions.add(CliOption.newBoolean(USE_TAGS, "use tags for creating interface and controller classnames"));
}
@@ -93,11 +98,32 @@ public abstract class AbstractJavaJAXRSServerCodegen extends AbstractJavaCodegen
}
if (additionalProperties.containsKey(USE_BEANVALIDATION)) {
this.setUseBeanValidation(convertPropertyToBoolean(USE_BEANVALIDATION));
setUseBeanValidation(convertPropertyToBoolean(USE_BEANVALIDATION));
}
if (additionalProperties.containsKey(USE_TAGS)) {
setUseTags(convertPropertyToBoolean(USE_TAGS));
}
writePropertyBack(USE_BEANVALIDATION, useBeanValidation);
}
@Override
public void addOperationToGroup(String tag, String resourcePath, Operation operation, CodegenOperation co, Map<String, List<CodegenOperation>> operations) {
final String basePath = StringUtils.substringBefore(StringUtils.removeStart(resourcePath, "/"), "/");
if (!StringUtils.isEmpty(basePath)) {
co.subresourceOperation = !co.path.isEmpty();
}
if (useTags) {
super.addOperationToGroup(tag, resourcePath, operation, co, operations);
} else {
co.baseName = basePath;
if (StringUtils.isEmpty(co.baseName) || StringUtils.containsAny(co.baseName, "{", "}")) {
co.baseName = "default";
}
final List<CodegenOperation> opList = operations.computeIfAbsent(co.baseName, k -> new ArrayList<>());
opList.add(co);
}
}
@Override
@@ -151,9 +177,8 @@ public abstract class AbstractJavaJAXRSServerCodegen extends AbstractJavaCodegen
static Map<String, Object> jaxrsPostProcessOperations(Map<String, Object> objs) {
@SuppressWarnings("unchecked")
Map<String, Object> operations = (Map<String, Object>) objs.get("operations");
String commonPath = null;
if (operations != null) {
String commonBaseName = null;
boolean baseNameEquals = true;
@SuppressWarnings("unchecked")
List<CodegenOperation> ops = (List<CodegenOperation>) operations.get("operation");
for (CodegenOperation operation : ops) {
@@ -223,24 +248,18 @@ public abstract class AbstractJavaJAXRSServerCodegen extends AbstractJavaCodegen
} else if ("map".equals(operation.returnContainer)) {
operation.returnContainer = "Map";
}
if(commonBaseName == null) {
commonBaseName = operation.baseName;
} else if(!commonBaseName.equals(operation.baseName)) {
baseNameEquals = false;
if (commonPath == null) {
commonPath = operation.path;
} else {
commonPath = getCommonPath(commonPath, operation.path);
}
}
if(baseNameEquals) {
objs.put("commonPath", commonBaseName);
} else {
for (CodegenOperation operation : ops) {
if(operation.baseName != null) {
operation.path = "/" + operation.baseName + operation.path;
operation.baseName = null;
}
}
objs.put("commonPath", null);
for (CodegenOperation co : ops) {
co.path = StringUtils.removeStart(co.path, commonPath);
co.subresourceOperation = co.path.length() > 1;
}
objs.put("commonPath", "/".equals(commonPath) ? StringUtils.EMPTY : commonPath);
}
return objs;
}
@@ -251,7 +270,7 @@ public abstract class AbstractJavaJAXRSServerCodegen extends AbstractJavaCodegen
if (computed.length() > 0) {
computed = sanitizeName(computed);
}
return super.toApiName(computed);
return super.toApiName(computed);
}
@Override
@@ -273,6 +292,19 @@ public abstract class AbstractJavaJAXRSServerCodegen extends AbstractJavaCodegen
return result;
}
private static String getCommonPath(String path1, String path2) {
final String[] parts1 = StringUtils.split(path1, "/");
final String[] parts2 = StringUtils.split(path2, "/");
StringBuilder builder = new StringBuilder();
for (int i = 0; i < Math.min(parts1.length, parts2.length); i++) {
if (!parts1[i].equals(parts2[i])) {
break;
}
builder.append("/").append(parts1[i]);
}
return builder.toString();
}
private String implFileFolder(String output) {
return outputFolder + "/" + output + "/" + apiPackage().replace('.', '/');
}
@@ -281,5 +313,8 @@ public abstract class AbstractJavaJAXRSServerCodegen extends AbstractJavaCodegen
this.useBeanValidation = useBeanValidation;
}
@VisibleForTesting
public void setUseTags(boolean useTags) {
this.useTags = useTags;
}
}

View File

@@ -771,7 +771,9 @@ public abstract class AbstractKotlinCodegen extends DefaultCodegen implements Co
@Override
protected boolean needToImport(String type) {
// provides extra protection against improperly trying to import language primitives and java types
boolean imports = !type.startsWith("kotlin.") && !type.startsWith("java.") && !defaultIncludes.contains(type) && !languageSpecificPrimitives.contains(type);
boolean imports = !type.startsWith("kotlin.") && !type.startsWith("java.") &&
!defaultIncludes.contains(type) && !languageSpecificPrimitives.contains(type) &&
!type.contains(".");
return imports;
}

View File

@@ -86,6 +86,10 @@ abstract public class AbstractRubyCodegen extends DefaultCodegen implements Code
typeMapping.put("ByteArray", "String");
typeMapping.put("UUID", "String");
typeMapping.put("URI", "String");
instantiationTypes.put("map", "Hash");
instantiationTypes.put("array", "Array");
instantiationTypes.put("set", "Set");
}
@Override
@@ -118,6 +122,22 @@ abstract public class AbstractRubyCodegen extends DefaultCodegen implements Code
return super.getTypeDeclaration(schema);
}
@Override
public String toInstantiationType(Schema schema) {
if (ModelUtils.isMapSchema(schema)) {
return instantiationTypes.get("map");
} else if (ModelUtils.isArraySchema(schema)) {
String parentType;
if (ModelUtils.isSet(schema)) {
parentType = "set";
} else {
parentType = "array";
}
return instantiationTypes.get(parentType);
}
return super.toInstantiationType(schema);
}
@Override
public String toDefaultValue(Schema p) {
if (ModelUtils.isIntegerSchema(p) || ModelUtils.isNumberSchema(p) || ModelUtils.isBooleanSchema(p)) {

View File

@@ -690,13 +690,13 @@ public abstract class AbstractTypeScriptClientCodegen extends DefaultCodegen imp
case original:
return name;
case camelCase:
return camelize(name, true);
return camelize(underscore(name), true);
case PascalCase:
return camelize(name);
return camelize(underscore(name));
case snake_case:
return underscore(name);
case UPPERCASE:
return name.toUpperCase(Locale.ROOT);
return underscore(name).toUpperCase(Locale.ROOT);
default:
throw new IllegalArgumentException("Unsupported enum property naming: '" + name);
}

View File

@@ -97,10 +97,10 @@ public class AdaCodegen extends AbstractAdaCodegen implements CodegenConfig {
String srcPrefix = "src" + File.separator;
String modelPrefix = srcPrefix + "model" + File.separator + toFilename(modelPackage);
String clientPrefix = srcPrefix + "client" + File.separator + toFilename(modelPackage);
supportingFiles.add(new SupportingFile("model-spec.mustache", null, modelPrefix + "-models.ads"));
supportingFiles.add(new SupportingFile("model-body.mustache", null, modelPrefix + "-models.adb"));
supportingFiles.add(new SupportingFile("client-spec.mustache", null, clientPrefix + "-clients.ads"));
supportingFiles.add(new SupportingFile("client-body.mustache", null, clientPrefix + "-clients.adb"));
supportingFiles.add(new SupportingFile("model-spec.mustache", "", modelPrefix + "-models.ads"));
supportingFiles.add(new SupportingFile("model-body.mustache", "", modelPrefix + "-models.adb"));
supportingFiles.add(new SupportingFile("client-spec.mustache", "", clientPrefix + "-clients.ads"));
supportingFiles.add(new SupportingFile("client-body.mustache", "", clientPrefix + "-clients.adb"));
if (additionalProperties.containsKey(CodegenConstants.PROJECT_NAME)) {
projectName = (String) additionalProperties.get(CodegenConstants.PROJECT_NAME);
@@ -125,20 +125,20 @@ public class AdaCodegen extends AbstractAdaCodegen implements CodegenConfig {
additionalProperties.put("isServer", false);
additionalProperties.put(CodegenConstants.PROJECT_NAME, projectName);
String names[] = this.modelPackage.split("\\.");
String[] names = this.modelPackage.split("\\.");
String pkgName = names[0];
additionalProperties.put("packageLevel1", pkgName);
supportingFiles.add(new SupportingFile("package-spec-level1.mustache", null,
supportingFiles.add(new SupportingFile("package-spec-level1.mustache", "",
"src" + File.separator + toFilename(names[0]) + ".ads"));
if (names.length > 1) {
String fileName = toFilename(names[0]) + "-" + toFilename(names[1]) + ".ads";
pkgName = names[0] + "." + names[1];
additionalProperties.put("packageLevel2", pkgName);
supportingFiles.add(new SupportingFile("package-spec-level2.mustache", null,
supportingFiles.add(new SupportingFile("package-spec-level2.mustache", "",
"src" + File.separator + fileName));
}
pkgName = this.modelPackage;
supportingFiles.add(new SupportingFile("client.mustache", null,
supportingFiles.add(new SupportingFile("client.mustache", "",
"src" + File.separator + toFilename(pkgName) + "-client.adb"));
additionalProperties.put("packageName", toFilename(pkgName));

View File

@@ -92,12 +92,12 @@ public class AdaServerCodegen extends AbstractAdaCodegen implements CodegenConfi
String serverPrefix = srcPrefix + "server" + File.separator + toFilename(modelPackage);
String modelPrefix = srcPrefix + "model" + File.separator + toFilename(modelPackage);
String implPrefix = srcPrefix + toFilename(modelPackage);
supportingFiles.add(new SupportingFile("model-spec.mustache", null, modelPrefix + "-models.ads"));
supportingFiles.add(new SupportingFile("model-body.mustache", null, modelPrefix + "-models.adb"));
supportingFiles.add(new SupportingFile("server-skeleton-spec.mustache", null, serverPrefix + "-skeletons.ads"));
supportingFiles.add(new SupportingFile("server-skeleton-body.mustache", null, serverPrefix + "-skeletons.adb"));
supportingFiles.add(new SupportingFile("server-spec.mustache", null, implPrefix + "-servers.ads"));
supportingFiles.add(new SupportingFile("server-body.mustache", null, implPrefix + "-servers.adb"));
supportingFiles.add(new SupportingFile("model-spec.mustache", "", modelPrefix + "-models.ads"));
supportingFiles.add(new SupportingFile("model-body.mustache", "", modelPrefix + "-models.adb"));
supportingFiles.add(new SupportingFile("server-skeleton-spec.mustache", "", serverPrefix + "-skeletons.ads"));
supportingFiles.add(new SupportingFile("server-skeleton-body.mustache", "", serverPrefix + "-skeletons.adb"));
supportingFiles.add(new SupportingFile("server-spec.mustache", "", implPrefix + "-servers.ads"));
supportingFiles.add(new SupportingFile("server-body.mustache", "", implPrefix + "-servers.adb"));
supportingFiles.add(new SupportingFile("openapi.mustache", "web" + File.separator + "swagger", "openapi.json"));
@@ -128,17 +128,17 @@ public class AdaServerCodegen extends AbstractAdaCodegen implements CodegenConfi
String names[] = this.modelPackage.split("\\.");
String pkgName = names[0];
additionalProperties.put("packageLevel1", pkgName);
supportingFiles.add(new SupportingFile("package-spec-level1.mustache", null,
supportingFiles.add(new SupportingFile("package-spec-level1.mustache", "",
"src" + File.separator + toFilename(names[0]) + ".ads"));
if (names.length > 1) {
String fileName = toFilename(names[0]) + "-" + toFilename(names[1]) + ".ads";
pkgName = names[0] + "." + names[1];
additionalProperties.put("packageLevel2", pkgName);
supportingFiles.add(new SupportingFile("package-spec-level2.mustache", null,
supportingFiles.add(new SupportingFile("package-spec-level2.mustache", "",
"src" + File.separator + fileName));
}
pkgName = this.modelPackage;
supportingFiles.add(new SupportingFile("server.mustache", null,
supportingFiles.add(new SupportingFile("server.mustache", "",
"src" + File.separator + toFilename(pkgName) + "-server.adb"));
additionalProperties.put("packageName", toFilename(pkgName));

View File

@@ -23,6 +23,7 @@ import io.swagger.v3.oas.models.media.Schema;
import org.openapitools.codegen.*;
import org.openapitools.codegen.meta.features.*;
import org.openapitools.codegen.utils.ModelUtils;
import org.openapitools.codegen.utils.ProcessUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -610,6 +611,9 @@ public class CSharpNetCoreClientCodegen extends AbstractCSharpCodegen {
supportingFiles.add(new SupportingFile("OpenAPIDateConverter.mustache", clientPackageDir, "OpenAPIDateConverter.cs"));
supportingFiles.add(new SupportingFile("ClientUtils.mustache", clientPackageDir, "ClientUtils.cs"));
supportingFiles.add(new SupportingFile("HttpMethod.mustache", clientPackageDir, "HttpMethod.cs"));
if (ProcessUtils.hasHttpSignatureMethods(openAPI)) {
supportingFiles.add(new SupportingFile("HTTPSigningConfiguration.mustache", clientPackageDir, "HTTPSigningConfiguration.cs"));
}
if (supportsAsync) {
supportingFiles.add(new SupportingFile("IAsynchronousClient.mustache", clientPackageDir, "IAsynchronousClient.cs"));
}

View File

@@ -176,7 +176,6 @@ public class FsharpGiraffeServerCodegen extends AbstractFSharpCodegen {
@Override
public void processOpts() {
super.processOpts();
boolean isLibrary = false;
if (additionalProperties.containsKey(CodegenConstants.OPTIONAL_PROJECT_GUID)) {
setPackageGuid((String) additionalProperties.get(CodegenConstants.OPTIONAL_PROJECT_GUID));
@@ -191,10 +190,6 @@ public class FsharpGiraffeServerCodegen extends AbstractFSharpCodegen {
additionalProperties.put(PROJECT_SDK, projectSdk);
// TODO - should we be supporting a Giraffe class library?
if (isLibrary)
LOGGER.warn("Library flag not currently supported.");
String authFolder = sourceFolder + File.separator + "auth";
String implFolder = sourceFolder + File.separator + "impl";
String helperFolder = sourceFolder + File.separator + "helpers";

View File

@@ -40,7 +40,6 @@ public class GoClientCodegen extends AbstractGoCodegen {
protected String packageVersion = "1.0.0";
protected String apiDocPath = "docs/";
protected String modelDocPath = "docs/";
public static final String WITH_GO_CODEGEN_COMMENT = "withGoCodegenComment";
public static final String WITH_XML = "withXml";
public static final String STRUCT_PREFIX = "structPrefix";
public static final String WITH_AWSV4_SIGNATURE = "withAWSV4Signature";
@@ -88,6 +87,7 @@ public class GoClientCodegen extends AbstractGoCodegen {
usesOptionals = false;
apiTemplateFiles.put("api.mustache", ".go");
modelTemplateFiles.put("model.mustache", ".go");
modelDocTemplateFiles.put("model_doc.mustache", ".md");
apiDocTemplateFiles.put("api_doc.mustache", ".md");
@@ -95,7 +95,6 @@ public class GoClientCodegen extends AbstractGoCodegen {
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 in GitHub 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(CodegenConstants.ENUM_CLASS_PREFIX, CodegenConstants.ENUM_CLASS_PREFIX_DESC));
cliOptions.add(CliOption.newBoolean(STRUCT_PREFIX, "whether to prefix struct with the class name. e.g. DeletePetOpts => PetApiDeletePetOpts"));
@@ -190,11 +189,6 @@ public class GoClientCodegen extends AbstractGoCodegen {
modelPackage = packageName;
apiPackage = packageName;
if (additionalProperties.containsKey(WITH_GO_CODEGEN_COMMENT)) {
setWithGoCodegenComment(Boolean.parseBoolean(additionalProperties.get(WITH_GO_CODEGEN_COMMENT).toString()));
additionalProperties.put(WITH_GO_CODEGEN_COMMENT, withGoCodegenComment);
}
if (additionalProperties.containsKey(WITH_AWSV4_SIGNATURE)) {
setWithAWSV4Signature(Boolean.parseBoolean(additionalProperties.get(WITH_AWSV4_SIGNATURE).toString()));
additionalProperties.put(WITH_AWSV4_SIGNATURE, withAWSV4Signature);

View File

@@ -136,8 +136,6 @@ public class GoServerCodegen extends AbstractGoCodegen {
@Override
public void processOpts() {
super.processOpts();
/*
* Additional Properties. These values can be passed to the templates and
* are available in models, apis, and supporting files
@@ -201,6 +199,8 @@ public class GoServerCodegen extends AbstractGoCodegen {
supportingFiles.add(new SupportingFile("go.mod.mustache", "", "go.mod"));
supportingFiles.add(new SupportingFile("routers.mustache", sourceFolder, "routers.go"));
supportingFiles.add(new SupportingFile("logger.mustache", sourceFolder, "logger.go"));
supportingFiles.add(new SupportingFile("impl.mustache",sourceFolder, "impl.go"));
supportingFiles.add(new SupportingFile("helpers.mustache", sourceFolder, "helpers.go"));
supportingFiles.add(new SupportingFile("api.mustache", sourceFolder, "api.go"));
supportingFiles.add(new SupportingFile("README.mustache", "", "README.md")
.doNotOverwrite());

View File

@@ -60,7 +60,8 @@ public class GroovyClientCodegen extends AbstractJavaCodegen {
languageSpecificPrimitives.add("File");
languageSpecificPrimitives.add("Map");
sourceFolder = projectFolder + File.separator +"groovy";
// this must not be OS-specific
sourceFolder = projectFolder + "/groovy";
outputFolder = "generated-code/groovy";
modelTemplateFiles.put("model.mustache", ".groovy");
apiTemplateFiles.put("api.mustache", ".groovy");

View File

@@ -1274,9 +1274,11 @@ public class HaskellHttpClientCodegen extends DefaultCodegen implements CodegenC
if (dataType == null && cm.isArrayModel) { // isAlias + arrayModelType missing "datatype"
dataType = "[" + cm.arrayModelType + "]";
}
cm.vendorExtensions.put(VENDOR_EXTENSION_X_DATA_TYPE, dataType);
if (dataType.equals("Maybe A.Value")) {
cm.vendorExtensions.put(VENDOR_EXTENSION_X_IS_MAYBE_VALUE, true);
if (dataType != null) {
cm.vendorExtensions.put(VENDOR_EXTENSION_X_DATA_TYPE, dataType);
if (dataType.equals("Maybe A.Value")) {
cm.vendorExtensions.put(VENDOR_EXTENSION_X_IS_MAYBE_VALUE, true);
}
}
}
for (CodegenProperty var : cm.vars) {

View File

@@ -282,7 +282,7 @@ public class JavaCXFExtServerCodegen extends JavaCXFServerCodegen implements CXF
return f;
});
private static final long MILLIS_PER_DAY = 24 * 60 * 60 * 1000;
private static final long MILLIS_PER_DAY = 24 * 60 * 60 * 1000L;
private static final long MIN_DATE;
@@ -551,10 +551,13 @@ public class JavaCXFExtServerCodegen extends JavaCXFServerCodegen implements CXF
short inclusiveMax = (short) (var == null || !var.exclusiveMaximum ? 1 : 0);
byte randomByte = (byte) (min + exclusiveMin + ((max + inclusiveMax - min - exclusiveMin) * Math.random()));
if (loadTestDataFromFile)
var.addTestData(randomByte);
else
if (loadTestDataFromFile) {
if (var != null) {
var.addTestData(randomByte);
}
} else {
buffer.append(String.format(Locale.getDefault(), "(byte)%0#2x", randomByte));
}
}
}
@@ -568,10 +571,13 @@ public class JavaCXFExtServerCodegen extends JavaCXFServerCodegen implements CXF
char inclusiveMax = (char) (var == null || !var.exclusiveMaximum ? 1 : 0);
char randomChar = (char) (min + exclusiveMin + ((max + inclusiveMax - min - exclusiveMin) * Math.random()));
if (loadTestDataFromFile)
var.addTestData(randomChar);
else
if (loadTestDataFromFile) {
if (var != null) {
var.addTestData(randomChar);
}
} else {
buffer.append(String.format(Locale.getDefault(), "'%c'", randomChar));
}
}
}
@@ -607,24 +613,26 @@ public class JavaCXFExtServerCodegen extends JavaCXFServerCodegen implements CXF
BigDecimal exclusiveMinLong = new BigDecimal(var != null && var.exclusiveMinimum ? 1 : 0);
BigDecimal inclusiveMaxLong = new BigDecimal(var == null || !var.exclusiveMaximum ? 1 : 0);
long randomDateLong = minLong.add(exclusiveMinLong).add(maxLong.add(inclusiveMaxLong).subtract(minLong)
.subtract(exclusiveMinLong).multiply(new BigDecimal(Math.random()))).longValue();
.subtract(exclusiveMinLong).multiply(BigDecimal.valueOf(Math.random()))).longValue();
// If it's just a date without a time, round downwards to the nearest day.
if ("date".equals(var.dataFormat))
if (var != null && "date".equals(var.dataFormat))
randomDateLong = (randomDateLong % MILLIS_PER_DAY) * MILLIS_PER_DAY;
// NOTE: By default Jackson serializes Date as long milliseconds since epoch date, but that conflicts with
// the OpenAPI 2.0/3.0 specs, which mandates the ISO-8601 full-date or date-time formats. Accordingly, date
// and date-time fields are annotated with @JsonFormat to specify the appropriate ISO format.
if (loadTestDataFromFile) {
Date randomDate = new Date(randomDateLong);
switch (var.dataFormat) {
case "date":
var.addTestData(ISO8601_DATE_FORMAT.get().format(randomDate));
break;
case "date-time":
var.addTestData(ISO8601_DATETIME_FORMAT.get().format(randomDate));
break;
if (var != null) {
Date randomDate = new Date(randomDateLong);
switch (var.dataFormat) {
case "date":
var.addTestData(ISO8601_DATE_FORMAT.get().format(randomDate));
break;
case "date-time":
var.addTestData(ISO8601_DATETIME_FORMAT.get().format(randomDate));
break;
}
}
} else {
buffer.append("new Date(").append(randomDateLong).append(')');
@@ -635,19 +643,20 @@ public class JavaCXFExtServerCodegen extends JavaCXFServerCodegen implements CXF
private void appendRandomDouble(StringBuilder buffer, CodegenOperation op, CodegenVariable var) {
if (!appendRandomEnum(buffer, op, var)) {
// NOTE: use BigDecimal to hold double values, to avoid numeric overflow.
BigDecimal min = new BigDecimal(
var == null || var.minimum == null ? Long.MIN_VALUE : Double.parseDouble(var.minimum));
BigDecimal max = new BigDecimal(
var == null || var.maximum == null ? Long.MAX_VALUE : Double.parseDouble(var.maximum));
BigDecimal min = BigDecimal.valueOf(var == null || var.minimum == null ? Long.MIN_VALUE : Double.parseDouble(var.minimum));
BigDecimal max = BigDecimal.valueOf(var == null || var.maximum == null ? Long.MAX_VALUE : Double.parseDouble(var.maximum));
BigDecimal exclusiveMin = new BigDecimal(var != null && var.exclusiveMinimum ? 1 : 0);
BigDecimal inclusiveMax = new BigDecimal(var == null || !var.exclusiveMaximum ? 1 : 0);
BigDecimal randomBigDecimal = min.add(exclusiveMin).add(max.add(inclusiveMax).subtract(min)
.subtract(exclusiveMin).multiply(new BigDecimal(String.valueOf(Math.random()))));
if (loadTestDataFromFile)
var.addTestData(randomBigDecimal);
else
if (loadTestDataFromFile) {
if (var != null) {
var.addTestData(randomBigDecimal);
}
} else {
buffer.append(randomBigDecimal.toString()).append('D');
}
}
}
@@ -704,10 +713,13 @@ public class JavaCXFExtServerCodegen extends JavaCXFServerCodegen implements CXF
float randomFloat = (float) (min + exclusiveMin
+ ((max + inclusiveMax - min - exclusiveMin) * Math.random()));
if (loadTestDataFromFile)
var.addTestData(randomFloat);
else
if (loadTestDataFromFile) {
if (var != null) {
var.addTestData(randomFloat);
}
} else {
buffer.append(String.format(Locale.getDefault(), "%g", randomFloat)).append('F');
}
}
}
@@ -720,10 +732,13 @@ public class JavaCXFExtServerCodegen extends JavaCXFServerCodegen implements CXF
long inclusiveMax = var == null || !var.exclusiveMaximum ? 1 : 0;
int randomInt = (int) (min + exclusiveMin + ((max + inclusiveMax - min - exclusiveMin) * Math.random()));
if (loadTestDataFromFile)
var.addTestData(randomInt);
else
if (loadTestDataFromFile) {
if (var != null) {
var.addTestData(randomInt);
}
} else {
buffer.append(randomInt);
}
}
}
@@ -737,13 +752,16 @@ public class JavaCXFExtServerCodegen extends JavaCXFServerCodegen implements CXF
BigDecimal exclusiveMin = new BigDecimal(var != null && var.exclusiveMinimum ? 1 : 0);
BigDecimal inclusiveMax = new BigDecimal(var == null || !var.exclusiveMaximum ? 1 : 0);
long randomLong = min.add(exclusiveMin).add(
max.add(inclusiveMax).subtract(min).subtract(exclusiveMin).multiply(new BigDecimal(Math.random())))
max.add(inclusiveMax).subtract(min).subtract(exclusiveMin).multiply(BigDecimal.valueOf(Math.random())))
.longValue();
if (loadTestDataFromFile)
var.addTestData(randomLong);
else
if (loadTestDataFromFile) {
if (var != null) {
var.addTestData(randomLong);
}
} else {
buffer.append(randomLong).append('L');
}
}
}
@@ -757,10 +775,13 @@ public class JavaCXFExtServerCodegen extends JavaCXFServerCodegen implements CXF
short randomShort = (short) (min + exclusiveMin
+ ((max + inclusiveMax - min - exclusiveMin) * Math.random()));
if (loadTestDataFromFile)
var.addTestData(randomShort);
else
if (loadTestDataFromFile) {
if (var != null) {
var.addTestData(randomShort);
}
} else {
buffer.append(String.format(Locale.getDefault(), "(short)%d", randomShort));
}
}
}
@@ -769,7 +790,9 @@ public class JavaCXFExtServerCodegen extends JavaCXFServerCodegen implements CXF
String randomString = generateRandomString(var);
if (loadTestDataFromFile) {
var.addTestData(randomString);
if (var != null) {
var.addTestData(randomString);
}
} else {
buffer.append('"').append(randomString).append('"');
}
@@ -1368,12 +1391,22 @@ public class JavaCXFExtServerCodegen extends JavaCXFServerCodegen implements CXF
}
if (this.generateSpringApplication) {
if (supportMultipleSpringServices) {
SupportingFile supportingFile = null;
for (SupportingFile sf : supportingFiles) {
if ("server/ApplicationContext.xml.mustache".equals(sf.templateFile)) {
sf.destinationFilename = "ApplicationContext-" + invokerPackage + ".xml";
if ("server/ApplicationContext.xml.mustache".equals(sf.getTemplateFile())) {
supportingFile = sf;
break;
}
}
if (supportingFile != null) {
supportingFiles.remove(supportingFile);
SupportingFile updated = new SupportingFile(
supportingFile.getTemplateFile(),
supportingFile.getFolder(),
"ApplicationContext-" + invokerPackage + ".xml"
);
supportingFiles.add(updated);
}
}
}
}

View File

@@ -72,6 +72,7 @@ public class JavaCXFServerCodegen extends AbstractJavaJAXRSServerCodegen
super();
supportsInheritance = true;
useTags = true;
artifactId = "openapi-cxf-server";
@@ -79,6 +80,7 @@ public class JavaCXFServerCodegen extends AbstractJavaJAXRSServerCodegen
// clioOptions default redifinition need to be updated
updateOption(CodegenConstants.ARTIFACT_ID, this.getArtifactId());
updateOption(USE_TAGS, String.valueOf(true));
apiTemplateFiles.put("apiServiceImpl.mustache", ".java");
@@ -234,12 +236,6 @@ public class JavaCXFServerCodegen extends AbstractJavaJAXRSServerCodegen
return "jaxrs-cxf";
}
@Override
public void addOperationToGroup(String tag, String resourcePath, Operation operation, CodegenOperation co, Map<String, List<CodegenOperation>> operations) {
super.addOperationToGroup(tag, resourcePath, operation, co, operations);
co.subresourceOperation = !co.path.isEmpty();
}
@Override
public void postProcessModelProperty(CodegenModel model, CodegenProperty property) {
super.postProcessModelProperty(model, property);

View File

@@ -481,7 +481,7 @@ public class JavaClientCodegen extends AbstractJavaCodegen
Iterator<SupportingFile> iter = supportingFiles.iterator();
while (iter.hasNext()) {
SupportingFile sf = iter.next();
if (sf.templateFile.startsWith("auth/")) {
if (sf.getTemplateFile().startsWith("auth/")) {
iter.remove();
}
}
@@ -818,11 +818,11 @@ public class JavaClientCodegen extends AbstractJavaCodegen
}
if (addImports) {
Map<String, String> imports2Classnames = new HashMap<String, String>() {{
put("JsonNullable", "org.openapitools.jackson.nullable.JsonNullable");
put("NoSuchElementException", "java.util.NoSuchElementException");
put("JsonIgnore", "com.fasterxml.jackson.annotation.JsonIgnore");
}};
Map<String, String> imports2Classnames = new HashMap<>();
imports2Classnames.put("JsonNullable", "org.openapitools.jackson.nullable.JsonNullable");
imports2Classnames.put("NoSuchElementException", "java.util.NoSuchElementException");
imports2Classnames.put("JsonIgnore", "com.fasterxml.jackson.annotation.JsonIgnore");
for (Map.Entry<String, String> entry : imports2Classnames.entrySet()) {
cm.imports.add(entry.getKey());
Map<String, String> importsItem = new HashMap<String, String>();
@@ -976,9 +976,9 @@ public class JavaClientCodegen extends AbstractJavaCodegen
@Override
public void addImportsToOneOfInterface(List<Map<String, String>> imports) {
for (String i : Arrays.asList("JsonSubTypes", "JsonTypeInfo")) {
Map<String, String> oneImport = new HashMap<String, String>() {{
put("import", importMapping.get(i));
}};
Map<String, String> oneImport = new HashMap<>();
oneImport.put("import", importMapping.get(i));
if (!imports.contains(oneImport)) {
imports.add(oneImport);
}

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