Compare commits

..

106 Commits

Author SHA1 Message Date
William Cheng
bfcc692689 comment out ts jquery test 2023-03-18 19:59:45 +08:00
William Cheng
d1f4f40fc8 Merge branch 'fix_validation_of_list_of_enums' of https://github.com/t0mk/openapi-generator into t0mk-fix_validation_of_list_of_enums2 2023-03-18 17:37:52 +08:00
William Cheng
e1719f2b7b [JavaSpring] migrate config files to use 3.0 spec (#14981)
* update spring config file to use 3.0 spec

* migrate spring config file to use 3.0 spec

* update github workflow to cover more samples
2023-03-17 16:02:27 +08:00
devhl-labs
02b6248510 moved null checks (#14980) 2023-03-17 15:12:27 +08:00
William Cheng
3d4f7b3ce0 [java] fix optional array property's default value (#14961)
* fix optional array property default value

* fix default values

* more fixes

* update default value for jersey2, 3, okhttp-gson

* update default value

* fix java okhttp-gson

* fix jersey2, 3
2023-03-17 11:58:49 +08:00
William Cheng
d0f7bd18ba [spring] fix default value for nullable containers (#14959)
* fix default value, update spec to 3.0

* add tests for container default value

* update java camel samples

* remove samples/openapi3/server/petstore/springboot-beanvalidation-no-nullable

* remove ./bin/configs/spring-boot-beanvalidation-no-nullable-oas3.yaml

* remove samples/openapi3/server/petstore/springboot-useoptional

* remove samples/openapi3/server/petstore/springboot-reactive

* update github workflow

* fix default in add, put operation
2023-03-17 10:16:17 +08:00
Tomas Karasek
e39d2cea9f [python-nextgen] re-generate exapmles for #14809 2023-03-16 13:40:06 +01:00
Tomas Karasek
aed041ac67 [python-nextgen] check enum arrady values better 2023-03-16 13:39:17 +01:00
Riccardo Cardin
e626b43e27 Added a property to the Spring generator to avoid the use of the ResponseEntity type (#11537)
* Added the useResponseEntity additional parameter for Spring generator

* Changed the mustache templates using the new useResponseEntity property

* Added the new property to the documentation

* Merging with remote master

* #11537 Added missing configuration for the delegate pattern case

* #11537 Added autogenerated @ResponseStatus on Spring methods

* #11537 Fixed borsch comments

* #11537 Added the default 200 HTTP Status for empty response HTTP code

* [Java][Spring] useResponseEntity sample + remove blank line

* [Java][Spring] useResponseEntity sample + remove blank line

* [Java][Spring] useResponseEntity sample + remove blank line

---------

Co-authored-by: Oleh Kurpiak <oleh.kurpiak@gmail.com>
2023-03-16 14:00:10 +02:00
dependabot[bot]
217d052bf7 Bump actions/setup-go from 3 to 4 (#14972)
Bumps [actions/setup-go](https://github.com/actions/setup-go) from 3 to 4.
- [Release notes](https://github.com/actions/setup-go/releases)
- [Commits](https://github.com/actions/setup-go/compare/v3...v4)

---
updated-dependencies:
- dependency-name: actions/setup-go
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2023-03-16 16:49:57 +08:00
devhl-labs
9787388f77 removed TryGet from deserialization methods (#14974) 2023-03-16 16:49:21 +08:00
devhl-labs
b6ccf078ef fixed nrt bug (#14973) 2023-03-16 08:59:12 +08:00
Peter Lamby
5c4529259f [BUG][typescript-fetch] wrong response for simple types (#14659)
See #9364
See #2870
2023-03-15 09:47:34 +01:00
William Cheng
5eb2819744 update go doc 2023-03-15 15:11:35 +08:00
Jason D'Amour
1268b5135d Enable bearer security schema for Go client (#14957) 2023-03-15 14:46:05 +08:00
devhl-labs
388147f822 suffixed variables with LocalVar to avoid conflicts (#14958) 2023-03-15 10:58:09 +08:00
martin-mfg
f1d05fc7f8 Allow Java apache-httpclient users to supply additional HTTP headers per call, updated (#14929)
* Allow Java apache-httpclient users to supply additional HTTP headers per API call

* fix 'unexpected return value' problem

* make "fullJavaUtil" work

* Revert 'make "fullJavaUtil" work'

This reverts commit 60c8846.

---------

Co-authored-by: Jigar Joshi <jigarjm@gmail.com>
2023-03-14 20:20:31 +02:00
igokoro
b172f622b9 Do not use default locale in kotlin generated code (#14668)
Using default locale for non-user visible text transformations is not safe
and can result in bugs, in particular with Turkish locale.

More details in
https://mattryall.net/blog/the-infamous-turkish-locale-bug

Closes #14667
2023-03-14 16:47:15 +00:00
Christian Mösl
85ff3de157 [java][webclient/resttemplate] fix dependencies for gradle with jakarta (#14925) 2023-03-14 17:57:08 +02:00
William Cheng
3826d712ad show error only in travis build to reduce log size 2023-03-14 17:24:13 +08:00
Oleh Kurpiak
bda2501455 [Java][Spring] option whether to generate required args constructor (#14941) (fix #14934) 2023-03-14 10:39:58 +02:00
Cameron Mackenzie
3d12510e1f Update README Angular compatible version (#14947)
Update version to 2.x-15.x in README to match latest version in docs: https://openapi-generator.tech/docs/generators/typescript-angular
2023-03-14 16:28:03 +08:00
William Cheng
644bccfd92 Reduce log level to avoid Travis CI build failure (#14946)
* reduce log level to avoid travis build failure

* add new file
2023-03-14 12:40:37 +08:00
devhl-labs
dc1386c134 better deserialization (#14945) 2023-03-14 11:40:40 +08:00
William Cheng
8b1e80d360 Merge branch 'master' of https://github.com/OpenAPITools/openapi-generator 2023-03-14 11:36:24 +08:00
William Cheng
de35cbd010 update samples 2023-03-14 11:36:17 +08:00
Guillaume Turri
9fd989e297 [PHP-Symfony] Fixes #14930 (#14933)
* [PHP-Symfony] fixes validation of date-time parameter

This fixes parts of #14930.

Without this patch a parameter declared as date-time
is validated against Symfony's "DateTime" constraint,
which always fails. Because this constraint expects
a string with format "Y-m-d H:i:s".
It fails because the generated code performs the check
after the deserialization, so the variable checked is not
a string anymore.

Besides this, even if we performed that validation on the
string, that would not work well because OpenApi
specification expects date-time to conform to RFC 3339
and that "Y-m-d H:i:s" would reject RFC 3339 compliant dates.

With this change we ensure that the string provided by the
web user could be parsed by PHP to DateTime, which solves both issues.

(Note however that it means that it now accepts more formats than just
RFC 3339 compliant ones for those parameters (it would accept all formats
accepted by PHP DateTime). That being said it's compliant with the guideline
""be conservative in what you send, be liberal in what you accept")

* [PHP-Symfony] Fix handling of null date-time parameter

This fixes one of the issue described on #14930, namely that
the deserializeString method of the generated class JsmSerializer returns null
for other types of string, but not for date-time. Instead it returns a DateTime
which represents "now" (because that what `new DateTime(null)` does).

Consequently when an API declares a date-time parameter as non-required and
when that endpoint is called without that parameters, then the user code
would end up having "now" instead of "null" for this parameter.
2023-03-14 11:17:34 +08:00
martin-mfg
f5d31c5214 Log Warn Messages for ineffective Schema Validations, updated (#14759)
* Implement WARN messages for ineffective schema validation constraints

* Implement tests String, Number, Object schema validations

* Implement HashSet to store Validations for different types

* Revert Validation Helper functions; Add Test cases for Any and Boolean

* Implement Unit Test for Array with inffective schema validations

* Reformat Code; Optimize Imports

* Add assertions to ineffective validation tests

* Add Test case for Null Schema Validations

* Adjust log level and message

* Merge commit ... into issue-6491

---------

Co-authored-by: Chidu Nadig <chidu.nadig@gmail.com>
2023-03-14 11:16:18 +08:00
Yannick Wiesner
ecd28b2090 JAX-RS Spec: Stop generating @NotNull Validation for required & optional properties (#12575)
* Stop generating @NotNull Validation for required & optional properties

* correct linebreak and add tests

* add samples in a separate folder
2023-03-14 00:39:31 +08:00
Eskild Diderichsen
e53b6fa7fa Setup GitHub Codespaces (#13533)
* Setup GitHub Codespaces

* updated devcontainer to new format
2023-03-14 00:35:44 +08:00
Mathias Dierickx
e52a9fd961 Add missing ConfigureAwaits for csharp-netcore generator (#13664) 2023-03-14 00:29:03 +08:00
William Cheng
dbc6c82446 minor fix to isPassword (#14942) 2023-03-13 23:37:40 +08:00
Romain Bioteau
59be28cc8a feat(password): add isPassword codegen property (#13982)
Expose `isPassword` codegen property. This property can be used in the
mustache templates to handle specific generation use case. _e.g._:
* hiding the string value of password fields in generated toString()
methods
* use more specific types like `char[]` instead of `String` in
[Java](https://stackoverflow.com/a/8881376)

Closes https://github.com/OpenAPITools/openapi-generator/issues/9124
2023-03-13 23:23:48 +08:00
Sascha Peilicke
df58ee3829 [Kotlin-Spring]: Dont't make readOnly properties nullable (#14509)
Resolves #14280
2023-03-13 23:14:02 +08:00
KlausH09
245851116f [Kotlin-Spring] add skip-default-interface option (#14662) 2023-03-13 22:51:49 +08:00
Nick Ufer
23cf8368e8 [Rust] fix: removes replacement which makes x-tag-name incompatible with spec (#14746) 2023-03-13 22:40:16 +08:00
Jonas Reichert
f45523dd1a [swift5] fix modelNamePrefix and -suffix for reserved types (#14768)
* only add suffix or prefix if type is not a primitive or from dependency

* add tests

* add sample

* add second API with prefix and suffix

* add primitives

* add missing pom

* add missing shell script

* fix cycle dependency

* generate samples
2023-03-13 09:42:24 +00:00
Robin Karlsson
564939a4a8 [java][jersey] Remove double brace initialization and some more jersey cleanup (#14783)
* Remove double brace initialization

* Use diamond operator

* Less clutter in generated api classes

* Optimize isJsonMime

* Revert change in escapeString

Skip toString() on string parameters.

* Fix edge-cases

A ServerVariable without enumValues and/or operationServers
with any ServerVariables would lead to invalid code.
2023-03-13 16:42:37 +08:00
William Cheng
9a53625fcc update erlang proper samples 2023-03-13 16:07:14 +08:00
William Cheng
6d71db3d6d update samples 2023-03-13 15:46:31 +08:00
David Weinstein
43697d2cfb [erlang-client] Fix Path (#14821) 2023-03-13 15:40:43 +08:00
devhl-labs
e9fed506b3 used the date format (#14936) 2023-03-13 15:25:29 +08:00
devhl-labs
8785acea7c added samples for unsigned (#14938) 2023-03-13 15:24:45 +08:00
William Cheng
0f2156191f add tests to jaxrs-cxf-cdi generator (#14937) 2023-03-12 23:43:39 +08:00
Antoine Reilles
72871cf930 [cxf-cdi] use InputStream for binary body (#14439)
Use a  single InputStream instead of "File".
This allows the generated code to build in case of a definition like:
      requestBody:
        content:
          text/plain:
            schema:
              type: string
              format: binary
This fixes #9372
2023-03-12 23:24:30 +08:00
William Cheng
790b0be964 update option description (#14932) 2023-03-12 16:47:32 +08:00
William Cheng
0c41a7c1b4 Minor bug fix in openapi normalizer (#14924)
* minor bug fix in openapi normalizer

* add test

* better code format

* fix hasCommonAttributesDefined
2023-03-12 15:28:16 +08:00
devhl-labs
3a940c93cc [csharp-netcore][aspnetcore] Added examples (#14927)
* added examples

* added examples to aspnet
2023-03-12 15:07:54 +08:00
devhl-labs
2b7007b653 [csharp-netcore] Moved formats to separate file (#14894)
* add unsigned integer/long support to c# netcore client

* moved formats to separate file

* moved formats to cli options

* moved formats to cli options

* reverted unintended changes

* reverted unintended changes

---------

Co-authored-by: William Cheng <wing328hk@gmail.com>
2023-03-12 15:05:35 +08:00
William Cheng
140d941da2 [csharp-netcore] Add unsigned integer/long support (#14885)
* add unsigned integer/long support to c# netcore client

* undo change in test spec, samples

* new test spec

* update doc
2023-03-10 15:18:41 +08:00
William Cheng
c4b404dc2e Decommission csharp-dotnet2 client generator (#14911)
* decommission csharp-dotnet2 client generator

* update doc
2023-03-10 14:30:32 +08:00
William Cheng
cda42b9e7b update doc 2023-03-10 14:29:23 +08:00
Brahim Hadriche
f3960b2116 [v2] (RFC) Csharp netcore generator supports UnityWebRequest library (#14870)
* Base impl

* Improve Unity support

* update samples

* Sync bool property

* Update samples

* Set support file property

* Address comments

* Fix test asmdef

* Fixes for WebGL support

* Add note about Unity version

* Add Unity Sample

---------

Co-authored-by: William Cheng <wing328hk@gmail.com>
2023-03-10 14:17:50 +08:00
William Cheng
f9efb7b2fb [OpenAPI Normalizer] update SIMPLIFY_ONEOF_ANYOF to convert enum of null to nullable (#14898)
* reorganize openapi normalizer tests

* add the logic to simply oneof anyof rule instead

* minor fix
2023-03-09 11:10:30 +08:00
William Cheng
77dd4990a4 update C# client dep, update samples (#14908) 2023-03-09 11:05:59 +08:00
Andre Vegas
d56a55a06b Fixing missing openApiNullable config for java apache-httpclient generator (#14828)
* 14827 - fixing missing openApiNullable config for java apache-httpclient generator

* 14827 - run PR steps updating examples & docs

* 14827 - fixing test data
2023-03-09 00:05:47 +08:00
Jorge Rodríguez Martín
9705617f93 [Java][Resttemplate] Normalize the RestTemplate ApiClient (#14845)
* Normalize resttemplate

* Update samples
2023-03-08 23:57:05 +08:00
Volker Suschke
c81ff5801d [Kotlin-Spring] Remove wildcard imports from mustache templates [#14652] (#14899)
* [Kotlin-Spring] Remove wildcard imports from mustache templates [#14652]

* [Kotlin-Spring] Update sample files [#14652]
2023-03-07 16:23:46 +00:00
William Cheng
4ed3cd9233 add new openapi-normalizer rule: ADD_UNSIGNED_TO_INTEGER_WITH_INVALID_MAX_VALUE (#14891) 2023-03-07 21:46:11 +08:00
William Cheng
e38ea578f8 Better support of inline allOf/anyOf/oneOf schemas (#14887)
* better support of inilne allof schemas

* add test file

* better handling of anyof, oneof inline schemas

* update samples

* add tests for nested anyof

* better code format
2023-03-07 15:53:53 +08:00
William Cheng
70faa6b15c better support of allOf with 1 sub-schema (#14882) 2023-03-07 00:35:34 +08:00
William Cheng
d497c3d087 [python-nextgen] Better docstring/documentation (#14880)
* better docstring/documentation in python nextgen client

* update instruction in test files
2023-03-06 21:22:43 +08:00
William Cheng
8ede021ec5 remove api import from model tests in csharp-netcore client (#14889) 2023-03-06 16:29:40 +08:00
devhl-labs
2a9fb7b6e7 removed double encoding (#14883) 2023-03-05 10:09:57 +08:00
William Cheng
46fb49ecd0 [python-nextgen] Add pyproject.toml (#14861)
* add pyproject.toml in python-nextgen client generator

* minor fix
2023-03-04 14:14:43 +08:00
William Cheng
39e27a804d [python-nextgen] better enum naming (#14869)
* better handling of enum naming in python nextgen

* remove unused import

* update samples

* update samples

* map dot
2023-03-03 17:54:10 +08:00
Dan Čermák
e535066a85 [python-nextgen] Add @overload for api methods to handle async requests (#14851) 2023-03-03 15:51:59 +08:00
William Cheng
c50e449cf5 Disable unit tests to prevent build from failing (#14872)
* disable ts tests

* disable ts test

* fix template tests

* add sleep

* Revert "add sleep"

This reverts commit bdb14a3677.

* disable template tests
2023-03-03 15:18:12 +08:00
Terence Honles
057a56a827 fix(typescript-angular): only import services if providing them (#14864)
* fix(typescript-angular): only import services if providing them

* update samples
2023-03-02 15:17:31 +01:00
Terence Honles
c2f244ccfa fix(typescript-angular): fix model filename including modelNamePrefix (#14859)
This change removes the modelNamePrefix from the API import filename
to be consistent with the processing in the rest of the class.
2023-03-02 14:49:14 +01:00
Oleh Kurpiak
440861270e [Core] Close Stream<Path> on spec merger (#14862) 2023-03-02 15:07:46 +02:00
Oleh Kurpiak
ca3e8be1bc [Java][Spring] version parameter (#14847) 2023-03-02 13:29:01 +02:00
William Cheng
60e2d605c4 [python-nextgen] fix enum default value (#14846)
* fix enum value

* add test for default value

* update samples, better code format
2023-03-02 17:36:38 +08:00
William Cheng
27a4355c6c add dmtech logo to website (#14853) 2023-03-02 10:53:42 +08:00
sbilz
7de302c43e add dmTECH GmbH as company using openApiGenerator (#14850) 2023-03-02 10:26:37 +08:00
Kuzma
c8fab3f40a [Typescript] Use for of instead of for in at ObjectSerializer (#14849)
* [Typescript] Use for of instead of for in

* fix for

* regenerate samples
2023-03-01 22:16:01 +01:00
Joe Spandrusyszyn
2458743257 [Typescript-Axios] Add options to TypescriptAxios reserved words (#14650)
* Add options to TypescriptAxios reserved words

* Update generated docs

---------

Co-authored-by: Joseph Spandrusyszyn <joseph.spandrusyszyn@bstock.com>
2023-03-01 15:48:19 +01:00
jmejane
350fb82bed [K6] Enhancement: Make operationId accessible inside requests (#14787)
* feat(k6): Make operationId accessible inside requests

* feat(k6): Update sample script

* feat(k6): re-add space deleted by formater
2023-03-01 22:46:12 +08:00
Adam Stoffel
43493a94fe [typescript] Fix Invalid path separator for imports on Windows (#14754)
Fix for #14753
2023-03-01 15:41:18 +01:00
Antoine Lucas
e1ab25c915 Add constructor with required parameter for Spring (#14822) (fix #9789)
* Add constructor with required parameter for spring

Fix #9789

* [Java][Spring] constructor with required args

---------

Co-authored-by: Oleh Kurpiak <oleh.kurpiak@gmail.com>
2023-03-01 15:09:47 +02:00
William Cheng
c70a41210e python-nextgen: fix tests 2023-03-01 17:17:08 +08:00
William Cheng
6d48d73421 python-nextgen switch union order (#14762) 2023-03-01 15:30:18 +08:00
William Cheng
e82ae6bacd [python-nextgen] Add datetime, date format support (#14799)
* add datetime, date format support in python nextgen

* encode query parameters

* update default datetime format

* change default datetime format
2023-03-01 15:29:47 +08:00
William Cheng
854f8dbc6d [CI] try to fix bitrise deprecation warning #14834 (#14836)
* [CI] try to fix bitrise deprecation warning

* [CI] try to fix bitrise deprecation warning

* skip tests

* simply run tests

---------

Co-authored-by: Bruno Coelho <4brunu@gmail.com>
2023-03-01 11:01:46 +08:00
Sylvain Joubert
a9e4eaf582 [C++][Pistache] Add some missing {{declspec}} on classes and functions (#14808) 2023-02-28 18:19:43 +08:00
William Cheng
a4b5b85067 Update jackson nullable version to newer version v0.2.6 (#14823)
* update jackson nullable to newer version

* update samples

* update samples

* update samples
2023-02-27 18:38:31 +08:00
Michel Wohlert
07f1d2d51c Encode request parameters to enable whitespace characters (#14797) 2023-02-27 09:25:28 +08:00
Rémi Kalbe
099f138dd5 [RUST] Upgrade reqwest-middleware (#14819)
* [RUST] Upgrade reqwest-middleware

Bump reqwest-middleware from 0.1.6 to 0.2.0

* Bump sample
2023-02-27 09:05:37 +08:00
William Cheng
b5d4fa9d27 fix unique items in python nextgen client (#14816) 2023-02-26 10:21:26 +08:00
Emma
1f2d6b8848 [python-nextgen] support dict query params (#14727)
* [python-nextgen] convert dictionary query params to string

* [python-nextgen] regenerated samples

* [python-nextgen] added some test cases for parameters_to_url_query

* [python-nextgen] use json.dumps instead of str(v)

* [python-nextgen] update api_client tests
2023-02-25 22:25:52 +08:00
Dennis Melzer
92b96635bd Fix bean validation for Collection and add unit test (#14736)
* Fix bean validation for Collection + uni test

* Fix

* Adapt examples

* Fix comments

* Merge master

* Remove Bean validation for Maps

* Remove @Valid from jakarta

* Fix example

* Fix comments

* Fix springboot-3 example
2023-02-25 22:06:31 +08:00
David Weinstein
3aa7ec6a39 Get API configuration from application environment for erlang-client (#14752)
* Get config from classname api

* Use the packageName

* Add samples
2023-02-25 22:05:14 +08:00
sbilz
f4e53db8cf Java Jersey glassfish fix renewing OAuth-Accesstoken #14734 (#14735) 2023-02-25 22:01:33 +08:00
catostrophe
5c9999b7cf Stop using org.springframework.util.Base64Utils in Java generators (#14813)
This utility class has been marked as deprecated for future removal since Spring 6.0.5. All Java generators, except WebClient and RestTemplate, are already using Base64 directly.
2023-02-25 21:56:18 +08:00
William Cheng
8b2de37414 [openapi-normalizer] add a new rule to set tags for all operations (#14794)
* add doc for KEEP_ONLY_FIRST_TAG_IN_OPERATION

* add new rule SET_TAGS_FOR_ALL_OPERATIONS

* better null check

* improve doc
2023-02-24 15:26:34 +08:00
William Cheng
d400d7fb15 Better handling of x-nullable in codegen property (#14800)
* add failed tests

* add logic to handle x-nullable in property

* update samples

* update test
2023-02-24 15:24:34 +08:00
William Cheng
b527f3b816 Setup Github works for Erlang projects (#14788)
* add github work for erlang projects

* trigger build

* use setup-bean instead

* add rebar3 version

* update otp version

* fix otp version

* fix otp version

* use 22.2

* fix

* fix

* fix ubuntu version

* use 22.2

* comment out erlang server test
2023-02-22 15:03:21 +08:00
William Cheng
cab9872d6d Add from_dict in model anyOf in python-nextgen (#14781)
* add from_dict to model_anyof template in python-nextgen, fixes #14767

* add space before from_dict in model.anyof in python-nextgen

* update samples, add tests

---------

Co-authored-by: Tomas Karasek <tom.to.the.k@gmail.com>
2023-02-22 10:56:05 +08:00
Cameron Koegel
18ef6ff96a [Ruby] fix return_binary_data with attr_accessor (#14772)
* [Ruby] fix `return_binary_data` with `attr_accessor`

* regenerate samples
2023-02-22 00:51:21 +08:00
Sergey Prytkov
94733b8bdf ktor-client fix array generation (#14778) 2023-02-21 10:58:11 +00:00
William Cheng
e09196261a Add rule to simplify oneOf/anyOf (#14777)
* add rule to simplify oneof/anyof

* update doc

* test nullable
2023-02-21 17:39:43 +08:00
William Cheng
c9958e12b8 Add rule to simplify boolean enum (#14764)
* add rule to simplify boolean enum

* update doc
2023-02-21 14:06:24 +08:00
William Cheng
b215f67b2e fix gradle properties with the correct snapshot version 2023-02-20 16:44:23 +08:00
Naoki Ikeguchi
9290c1a75e [rust-server] Fix clippy warnings (#13907)
* fix(rust-server): clippy::blacklisted_name -> clippy::disallowed_names

* fix(rust-server): Remove unnecessary deref

* fix(rust-server): Allow clippy::single_match

* fix(rust-server): Use clone instead of to_owned on Cow

* fix(rust-server): Remove needless borrows

* chore(rust-server): Update sample outputs
2023-02-20 13:46:01 +08:00
William Cheng
94d6faffe3 revert spring boot back to 2.5.14 (#14755) 2023-02-20 12:35:47 +08:00
William Cheng
c50a775e0c prepare 6.5.0 release (#14749) 2023-02-19 20:36:23 +08:00
4030 changed files with 87596 additions and 75131 deletions

View File

@@ -0,0 +1,47 @@
{
"name": "OpenAPIGenerator",
"image": "mcr.microsoft.com/devcontainers/base:debian",
"features": {
"ghcr.io/devcontainers/features/java:1": {
"version": "11",
"installMaven": true
},
"ghcr.io/devcontainers/features/node:1": {
"version": "lts"
},
"ghcr.io/snebjorn/devcontainer-feature/chromium:latest": {}
},
// Configure tool-specific properties.
"customizations": {
// Configure properties specific to VS Code.
"vscode": {
// Set *default* container specific settings.json values on container create.
"settings": {
"java.configuration.runtimes": [
{
"name": "JavaSE-11",
"path": "/usr/local/sdkman/candidates/java/11.0.16.1-ms",
"sources": "/usr/local/sdkman/candidates/java/11.0.16.1-ms/lib/src.zip",
"javadoc": "https://docs.oracle.com/en/java/javase/11/docs/api",
"default": true
}
]
},
// Add the IDs of extensions you want installed when the container is created.
"extensions": [
"vscjava.vscode-java-pack",
"attilabuti.mustache-syntax-vscode",
"formulahendry.code-runner",
"visualstudioexptteam.vscodeintellicode",
"42crunch.vscode-openapi",
"mermade.openapi-lint"
]
}
},
// Use 'forwardPorts' to make a list of ports inside the container available locally.
// "forwardPorts": [],
// Use 'postCreateCommand' to run commands after the container is created.
// "postCreateCommand": "mvn clean package -DskipTests",
// Comment out to connect as root instead. More info: https://aka.ms/vscode-remote/containers/non-root.
"remoteUser": "vscode"
}

35
.github/workflows/samples-erlang.yaml vendored Normal file
View File

@@ -0,0 +1,35 @@
name: Samples Erlang
on:
push:
paths:
# comment out due to errors
# ===> Compiling src/openapi_pet_handler.erl failed
# src/openapi_pet_handler.erl:278: function is_authorized/2 already defined
#- samples/server/petstore/erlang-server/**
- samples/client/petstore/erlang-client/**
- samples/client/petstore/erlang-proper/**
pull_request:
paths:
#- samples/server/petstore/erlang-server/**
- samples/client/petstore/erlang-client/**
- samples/client/petstore/erlang-proper/**
jobs:
build:
name: Build Erlang projects
runs-on: ubuntu-20.04
strategy:
fail-fast: false
matrix:
sample:
#- samples/server/petstore/erlang-server/
- samples/client/petstore/erlang-client/
- samples/client/petstore/erlang-proper/
steps:
- uses: actions/checkout@v3
- uses: erlef/setup-beam@v1
with:
otp-version: '22.2'
rebar3-version: '3.14.3'
- run: rebar3 compile
working-directory: ${{ matrix.sample }}

View File

@@ -22,7 +22,7 @@ jobs:
- samples/server/petstore/go-api-server/
steps:
- uses: actions/checkout@v3
- uses: actions/setup-go@v3
- uses: actions/setup-go@v4
with:
go-version: '>=1.17.0'
- run: go version

View File

@@ -34,6 +34,9 @@ jobs:
path: |
~/.m2
key: ${{ runner.os }}-${{ github.job }}-${{ env.cache-name }}-${{ hashFiles('**/pom.xml') }}
- name: Build
- name: Build with Maven
working-directory: ${{ matrix.sample }}
run: mvn clean package
- name: Build with Gradle
working-directory: ${{ matrix.sample }}
run: gradle clean build

View File

@@ -22,26 +22,30 @@ jobs:
- samples/openapi3/client/petstore/spring-cloud
- samples/client/petstore/spring-cloud-date-time
- samples/openapi3/client/petstore/spring-cloud-date-time
- samples/client/petstore/spring-stubs
- samples/openapi3/client/petstore/spring-stubs
- samples/openapi3/client/petstore/spring-stubs-skip-default-interface
- samples/openapi3/client/petstore/spring-cloud-async
- samples/openapi3/client/petstore/spring-cloud-spring-pageable
# servers
- samples/server/petstore/springboot
- samples/openapi3/server/petstore/springboot
- samples/server/petstore/springboot-beanvalidation
- samples/server/petstore/springboot-useoptional
- samples/openapi3/server/petstore/springboot-useoptional
- samples/server/petstore/springboot-reactive
- samples/openapi3/server/petstore/springboot-reactive
- samples/server/petstore/springboot-implicitHeaders
- samples/openapi3/server/petstore/springboot-implicitHeaders
- samples/server/petstore/springboot-delegate
- samples/server/petstore/springboot-delegate-no-response-entity
- samples/openapi3/server/petstore/springboot-delegate
- samples/server/petstore/spring-boot-nullable-set
- samples/server/petstore/spring-boot-defaultInterface-unhandledException
- samples/openapi3/server/petstore/spring-boot-oneof
- samples/server/petstore/springboot-virtualan
- samples/server/petstore/springboot-implicitHeaders-annotationLibrary
- samples/server/petstore/springboot-spring-pageable-delegatePattern-without-j8
- samples/server/petstore/springboot-spring-pageable-delegatePattern
- samples/server/petstore/springboot-spring-pageable-without-j8
- samples/server/petstore/springboot-spring-pageable
steps:
- uses: actions/checkout@v3
- uses: actions/setup-java@v3

View File

@@ -150,14 +150,15 @@ script:
- docker buildx version
# run integration tests defined in maven pom.xml
# WARN: Travis will timeout after 10 minutes of no stdout/stderr activity, which is problematic with mvn --quiet.
- mvn -e --no-snapshot-updates --quiet --batch-mode --show-version clean install -Dorg.slf4j.simpleLogger.defaultLogLevel=error
# show "error" only to reduce the log size
- mvn -e --no-snapshot-updates --quiet --batch-mode --show-version clean install -Dorg.slf4j.simpleLogger.defaultLogLevel=error 2>&1 | grep -i error
#- mvn -e --no-snapshot-updates --quiet --batch-mode --show-version verify -Psamples -Dorg.slf4j.simpleLogger.defaultLogLevel=error
after_success:
# push to maven repo
- if [ $SONATYPE_USERNAME ] && [ "$TRAVIS_PULL_REQUEST" == "false" ]; then
if [ "$TRAVIS_BRANCH" = "master" ] && [ -z $TRAVIS_TAG ]; then
echo "Publishing from branch $TRAVIS_BRANCH";
mvn clean deploy -DskipTests=true -B -U -P release --settings CI/settings.xml;
mvn clean deploy -DskipTests=true -B -U -P release --settings CI/settings.xml -Dorg.slf4j.simpleLogger.defaultLogLevel=error;
echo "Finished mvn clean deploy for $TRAVIS_BRANCH";
pushd .;
cd modules/openapi-generator-gradle-plugin;
@@ -166,7 +167,7 @@ after_success:
popd;
elif [ -z $TRAVIS_TAG ] && [[ "$TRAVIS_BRANCH" =~ ^[0-9]+\.[0-9]+\.x$ ]]; then
echo "Publishing from branch $TRAVIS_BRANCH";
mvn clean deploy --settings CI/settings.xml;
mvn clean deploy --settings CI/settings.xml -Dorg.slf4j.simpleLogger.defaultLogLevel=error;
echo "Finished mvn clean deploy for $TRAVIS_BRANCH";
pushd .;
cd modules/openapi-generator-gradle-plugin;

View File

@@ -78,7 +78,7 @@ OpenAPI Generator allows generation of API client libraries (SDK generation), se
| | Languages/Frameworks |
| -------------------------------- |-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| **API clients** | **ActionScript**, **Ada**, **Apex**, **Bash**, **C**, **C#** (.net 2.0, 3.5 or later, .NET Standard 1.3 - 2.1, .NET Core 3.1, .NET 5.0. Libraries: RestSharp, GenericHost, HttpClient), **C++** (Arduino, cpp-restsdk, Qt5, Tizen, Unreal Engine 4), **Clojure**, **Crystal**, **Dart**, **Elixir**, **Elm**, **Eiffel**, **Erlang**, **Go**, **Groovy**, **Haskell** (http-client, Servant), **Java** (Apache HttpClient 4.x, Apache HttpClient 5.x, Jersey1.x, Jersey2.x, OkHttp, Retrofit1.x, Retrofit2.x, Feign, RestTemplate, RESTEasy, Vertx, Google API Client Library for Java, Rest-assured, Spring 5 Web Client, MicroProfile Rest Client, Helidon), **Jetbrains HTTP Client**, **Julia**, **k6**, **Kotlin**, **Lua**, **Nim**, **Node.js/JavaScript** (ES5, ES6, AngularJS with Google Closure Compiler annotations, Flow types, Apollo GraphQL DataStore), **Objective-C**, **OCaml**, **Perl**, **PHP**, **PowerShell**, **Python**, **R**, **Ruby**, **Rust** (hyper, reqwest, rust-server), **Scala** (akka, http4s, scalaz, sttp, swagger-async-httpclient), **Swift** (2.x, 3.x, 4.x, 5.x), **Typescript** (AngularJS, Angular (2.x - 13.x), Aurelia, Axios, Fetch, Inversify, jQuery, Nestjs, Node, redux-query, Rxjs) |
| **API clients** | **ActionScript**, **Ada**, **Apex**, **Bash**, **C**, **C#** (.net 2.0, 3.5 or later, .NET Standard 1.3 - 2.1, .NET Core 3.1, .NET 5.0. Libraries: RestSharp, GenericHost, HttpClient), **C++** (Arduino, cpp-restsdk, Qt5, Tizen, Unreal Engine 4), **Clojure**, **Crystal**, **Dart**, **Elixir**, **Elm**, **Eiffel**, **Erlang**, **Go**, **Groovy**, **Haskell** (http-client, Servant), **Java** (Apache HttpClient 4.x, Apache HttpClient 5.x, Jersey1.x, Jersey2.x, OkHttp, Retrofit1.x, Retrofit2.x, Feign, RestTemplate, RESTEasy, Vertx, Google API Client Library for Java, Rest-assured, Spring 5 Web Client, MicroProfile Rest Client, Helidon), **Jetbrains HTTP Client**, **Julia**, **k6**, **Kotlin**, **Lua**, **Nim**, **Node.js/JavaScript** (ES5, ES6, AngularJS with Google Closure Compiler annotations, Flow types, Apollo GraphQL DataStore), **Objective-C**, **OCaml**, **Perl**, **PHP**, **PowerShell**, **Python**, **R**, **Ruby**, **Rust** (hyper, reqwest, rust-server), **Scala** (akka, http4s, scalaz, sttp, swagger-async-httpclient), **Swift** (2.x, 3.x, 4.x, 5.x), **Typescript** (AngularJS, Angular (2.x - 15.x), Aurelia, Axios, Fetch, Inversify, jQuery, Nestjs, Node, redux-query, Rxjs) |
| **Server stubs** | **Ada**, **C#** (ASP.NET Core, Azure Functions), **C++** (Pistache, Restbed, Qt5 QHTTPEngine), **Erlang**, **F#** (Giraffe), **Go** (net/http, Gin, Echo), **Haskell** (Servant, Yesod), **Java** (MSF4J, Spring, Undertow, JAX-RS: CDI, CXF, Inflector, Jersey, RestEasy, Play Framework, [PKMST](https://github.com/ProKarma-Inc/pkmst-getting-started-examples), [Vert.x](https://vertx.io/), [Apache Camel](https://camel.apache.org/), [Helidon](https://helidon.io/)), **Julia**, **Kotlin** (Spring Boot, Ktor, Vertx), **PHP** (Laravel, Lumen, [Mezzio (fka Zend Expressive)](https://github.com/mezzio/mezzio), Slim, Silex, [Symfony](https://symfony.com/)), **Python** (FastAPI, Flask), **NodeJS**, **Ruby** (Sinatra, Rails5), **Rust** ([rust-server](https://openapi-generator.tech/docs/generators/rust-server/)), **Scala** (Akka, [Finch](https://github.com/finagle/finch), [Lagom](https://github.com/lagom/lagom), [Play](https://www.playframework.com/), Scalatra) |
| **API documentation generators** | **HTML**, **Confluence Wiki**, **Asciidoc**, **Markdown**, **PlantUML** |
| **Configuration files** | [**Apache2**](https://httpd.apache.org/) |
@@ -613,6 +613,7 @@ Here are some companies/projects (alphabetical order) using OpenAPI Generator in
- [DB Systel](https://www.dbsystel.de)
- [Deeporute.ai](https://www.deeproute.ai/)
- [Devsupply](https://www.devsupply.com/)
- [dmTECH GmbH](https://www.dmTECH.de)
- [DocSpring](https://docspring.com/)
- [dwango](https://dwango.co.jp/)
- [Edge Impulse](https://www.edgeimpulse.com/)

View File

@@ -0,0 +1,6 @@
# for .net Unity
generatorName: csharp-netcore
outputDir: samples/client/petstore/csharp-netcore/OpenAPIClient-unityWebRequest
inputSpec: modules/openapi-generator/src/test/resources/3_0/csharp/petstore-with-fake-endpoints-models-for-testing-with-http-signature.yaml
templateDir: modules/openapi-generator/src/main/resources/csharp-netcore
library: unityWebRequest

View File

@@ -1,6 +1,6 @@
generatorName: jaxrs-cxf-cdi
outputDir: samples/server/petstore/jaxrs-cxf-cdi
inputSpec: modules/openapi-generator/src/test/resources/2_0/petstore.yaml
inputSpec: modules/openapi-generator/src/test/resources/3_0/jaxrs/petstore.yaml
templateDir: modules/openapi-generator/src/main/resources/JavaJaxRS/cxf-cdi
additionalProperties:
hideGenerationTimestamp: "true"

View File

@@ -0,0 +1,10 @@
generatorName: jaxrs-spec
outputDir: samples/server/petstore/jaxrs-spec-required-and-readonly-property
inputSpec: modules/openapi-generator/src/test/resources/3_0/required-and-readonly-property.yaml
templateDir: modules/openapi-generator/src/main/resources/JavaJaxRS/spec
additionalProperties:
artifactId: jaxrs-spec-petstore-server
serializableModel: "true"
hideGenerationTimestamp: "true"
implicitHeadersRegex: (api_key|enum_header_string)
generateBuilders: "true"

View File

@@ -1,13 +0,0 @@
generatorName: spring
outputDir: samples/openapi3/server/petstore/springboot-beanvalidation-no-nullable
library: spring-boot
inputSpec: modules/openapi-generator/src/test/resources/2_0/petstore-with-fake-endpoints-models-for-testing.yaml
templateDir: modules/openapi-generator/src/main/resources/JavaSpring
additionalProperties:
groupId: org.openapitools.openapi3
documentationProvider: springdoc
java8: "false"
useBeanValidation: true
artifactId: spring-boot-beanvalidation-no-nullable
hideGenerationTimestamp: "true"
openApiNullable: "false"

View File

@@ -1,9 +1,10 @@
generatorName: spring
outputDir: samples/server/petstore/springboot-beanvalidation-no-nullable
library: spring-boot
inputSpec: modules/openapi-generator/src/test/resources/2_0/petstore-with-fake-endpoints-models-for-testing.yaml
inputSpec: modules/openapi-generator/src/test/resources/3_0/spring/petstore-with-fake-endpoints-models-for-testing.yaml
templateDir: modules/openapi-generator/src/main/resources/JavaSpring
additionalProperties:
groupId: org.openapitools.openapi3
documentationProvider: springfox
java8: "false"
useBeanValidation: true

View File

@@ -1,7 +1,7 @@
generatorName: spring
outputDir: samples/server/petstore/springboot-beanvalidation
library: spring-boot
inputSpec: modules/openapi-generator/src/test/resources/2_0/petstore-with-fake-endpoints-models-for-testing.yaml
inputSpec: modules/openapi-generator/src/test/resources/3_0/spring/petstore-with-fake-endpoints-models-for-testing.yaml
templateDir: modules/openapi-generator/src/main/resources/JavaSpring
additionalProperties:
documentationProvider: springfox

View File

@@ -1,6 +1,6 @@
generatorName: spring
outputDir: samples/server/petstore/spring-boot-defaultInterface-unhandledException
inputSpec: modules/openapi-generator/src/test/resources/2_0/petstore-with-fake-endpoints-models-for-testing.yaml
inputSpec: modules/openapi-generator/src/test/resources/3_0/spring/petstore-with-fake-endpoints-models-for-testing.yaml
templateDir: modules/openapi-generator/src/main/resources/JavaSpring
additionalProperties:
artifactId: spring-boot-defaultInterface-unhandledException

View File

@@ -1,6 +1,6 @@
generatorName: spring
outputDir: samples/server/petstore/springboot-delegate-j8
inputSpec: modules/openapi-generator/src/test/resources/2_0/petstore-with-fake-endpoints-models-for-testing.yaml
inputSpec: modules/openapi-generator/src/test/resources/3_0/spring/petstore-with-fake-endpoints-models-for-testing.yaml
templateDir: modules/openapi-generator/src/main/resources/JavaSpring
additionalProperties:
documentationProvider: springfox

View File

@@ -0,0 +1,11 @@
generatorName: spring
outputDir: samples/server/petstore/springboot-delegate-no-response-entity
inputSpec: modules/openapi-generator/src/test/resources/3_0/petstore.yaml
templateDir: modules/openapi-generator/src/main/resources/JavaSpring
additionalProperties:
documentationProvider: springfox
artifactId: springboot-delegate-no-response-entity
hideGenerationTimestamp: "true"
java8: true
delegatePattern: "true"
useResponseEntity: "false"

View File

@@ -1,6 +1,6 @@
generatorName: spring
outputDir: samples/openapi3/server/petstore/springboot-delegate
inputSpec: modules/openapi-generator/src/test/resources/2_0/petstore-with-fake-endpoints-models-for-testing.yaml
inputSpec: modules/openapi-generator/src/test/resources/3_0/spring/petstore-with-fake-endpoints-models-for-testing.yaml
templateDir: modules/openapi-generator/src/main/resources/JavaSpring
additionalProperties:
groupId: org.openapitools.openapi3

View File

@@ -1,6 +1,6 @@
generatorName: spring
outputDir: samples/server/petstore/springboot-delegate
inputSpec: modules/openapi-generator/src/test/resources/2_0/petstore-with-fake-endpoints-models-for-testing.yaml
inputSpec: modules/openapi-generator/src/test/resources/3_0/spring/petstore-with-fake-endpoints-models-for-testing.yaml
templateDir: modules/openapi-generator/src/main/resources/JavaSpring
additionalProperties:
documentationProvider: springfox

View File

@@ -1,6 +1,6 @@
generatorName: spring
outputDir: samples/openapi3/server/petstore/springboot-implicitHeaders
inputSpec: modules/openapi-generator/src/test/resources/2_0/petstore-with-fake-endpoints-models-for-testing.yaml
inputSpec: modules/openapi-generator/src/test/resources/3_0/spring/petstore-with-fake-endpoints-models-for-testing.yaml
templateDir: modules/openapi-generator/src/main/resources/JavaSpring
additionalProperties:
groupId: org.openapitools.openapi3

View File

@@ -1,6 +1,6 @@
generatorName: spring
outputDir: samples/server/petstore/springboot-implicitHeaders
inputSpec: modules/openapi-generator/src/test/resources/2_0/petstore-with-fake-endpoints-models-for-testing.yaml
inputSpec: modules/openapi-generator/src/test/resources/3_0/spring/petstore-with-fake-endpoints-models-for-testing.yaml
templateDir: modules/openapi-generator/src/main/resources/JavaSpring
additionalProperties:
artifactId: springboot-implicitHeaders

View File

@@ -1,11 +0,0 @@
generatorName: spring
outputDir: samples/openapi3/server/petstore/springboot-reactive
inputSpec: modules/openapi-generator/src/test/resources/2_0/petstore-with-fake-endpoints-models-for-testing.yaml
templateDir: modules/openapi-generator/src/main/resources/JavaSpring
additionalProperties:
groupId: org.openapitools.openapi3
documentationProvider: springdoc
artifactId: springboot-reactive
reactive: "true"
hideGenerationTimestamp: "true"
delegatePattern: "true"

View File

@@ -1,8 +1,9 @@
generatorName: spring
outputDir: samples/server/petstore/springboot-reactive
inputSpec: modules/openapi-generator/src/test/resources/2_0/petstore-with-fake-endpoints-models-for-testing.yaml
inputSpec: modules/openapi-generator/src/test/resources/3_0/spring/petstore-with-fake-endpoints-models-for-testing.yaml
templateDir: modules/openapi-generator/src/main/resources/JavaSpring
additionalProperties:
groupId: org.openapitools.openapi3
artifactId: springboot-reactive
documentationProvider: springfox
reactive: "true"

View File

@@ -1,10 +0,0 @@
generatorName: spring
outputDir: samples/openapi3/server/petstore/springboot-useoptional
inputSpec: modules/openapi-generator/src/test/resources/2_0/petstore-with-fake-endpoints-models-for-testing.yaml
templateDir: modules/openapi-generator/src/main/resources/JavaSpring
additionalProperties:
groupId: org.openapitools.openapi3
documentationProvider: springdoc
useOptional: true
artifactId: spring-boot-useoptional
hideGenerationTimestamp: "true"

View File

@@ -1,8 +1,9 @@
generatorName: spring
outputDir: samples/server/petstore/springboot-useoptional
inputSpec: modules/openapi-generator/src/test/resources/2_0/petstore-with-fake-endpoints-models-for-testing.yaml
inputSpec: modules/openapi-generator/src/test/resources/3_0/spring/petstore-with-fake-endpoints-models-for-testing.yaml
templateDir: modules/openapi-generator/src/main/resources/JavaSpring
additionalProperties:
groupId: org.openapitools.openapi3
documentationProvider: springfox
useOptional: true
artifactId: spring-boot-useoptional

View File

@@ -1,7 +1,7 @@
generatorName: spring
outputDir: samples/server/petstore/springboot-virtualan
library: spring-boot
inputSpec: modules/openapi-generator/src/test/resources/2_0/petstore-with-fake-endpoints-models-for-testing.yaml
inputSpec: modules/openapi-generator/src/test/resources/3_0/spring/petstore-with-fake-endpoints-models-for-testing.yaml
templateDir: modules/openapi-generator/src/main/resources/JavaSpring
additionalProperties:
documentationProvider: springdoc

View File

@@ -1,6 +1,6 @@
generatorName: spring
outputDir: samples/server/petstore/springboot
inputSpec: modules/openapi-generator/src/test/resources/2_0/petstore-with-fake-endpoints-models-for-testing.yaml
inputSpec: modules/openapi-generator/src/test/resources/3_0/spring/petstore-with-fake-endpoints-models-for-testing.yaml
templateDir: modules/openapi-generator/src/main/resources/JavaSpring
additionalProperties:
documentationProvider: springfox

View File

@@ -1,7 +1,7 @@
generatorName: spring
outputDir: samples/openapi3/client/petstore/spring-cloud-async
library: spring-cloud
inputSpec: modules/openapi-generator/src/test/resources/2_0/petstore.yaml
inputSpec: modules/openapi-generator/src/test/resources/3_0/petstore.yaml
templateDir: modules/openapi-generator/src/main/resources/JavaSpring
additionalProperties:
groupId: org.openapitools.openapi3

View File

@@ -1,11 +0,0 @@
generatorName: spring
outputDir: samples/client/petstore/spring-cloud-async
library: spring-cloud
inputSpec: modules/openapi-generator/src/test/resources/2_0/petstore.yaml
templateDir: modules/openapi-generator/src/main/resources/JavaSpring
additionalProperties:
documentationProvider: springfox
async: "true"
java8: "true"
artifactId: petstore-spring-cloud
hideGenerationTimestamp: "true"

View File

@@ -1,7 +1,7 @@
generatorName: spring
library: spring-cloud
outputDir: samples/openapi3/client/petstore/spring-cloud-oas3-fakeapi
inputSpec: modules/openapi-generator/src/test/resources/2_0/petstore-with-fake-endpoints-models-for-testing.yaml
inputSpec: modules/openapi-generator/src/test/resources/3_0/spring/petstore-with-fake-endpoints-models-for-testing.yaml
templateDir: modules/openapi-generator/src/main/resources/JavaSpring
additionalProperties:
groupId: org.openapitools.openapi3
@@ -10,3 +10,4 @@ additionalProperties:
interfaceOnly: "true"
singleContentTypes: "true"
hideGenerationTimestamp: "true"
generatedConstructorWithRequiredArgs: "false"

View File

@@ -1,7 +1,7 @@
generatorName: spring
outputDir: samples/openapi3/client/petstore/spring-cloud-spring-pageable
library: spring-cloud
inputSpec: modules/openapi-generator/src/test/resources/2_0/petstore-with-spring-pageable.yaml
inputSpec: modules/openapi-generator/src/test/resources/3_0/spring/petstore-with-spring-pageable.yaml
templateDir: modules/openapi-generator/src/main/resources/JavaSpring
additionalProperties:
groupId: org.openapitools.openapi3

View File

@@ -1,9 +0,0 @@
generatorName: spring
outputDir: samples/client/petstore/spring-cloud-spring-pageable
library: spring-cloud
inputSpec: modules/openapi-generator/src/test/resources/2_0/petstore-with-spring-pageable.yaml
templateDir: modules/openapi-generator/src/main/resources/JavaSpring
additionalProperties:
documentationProvider: springfox
artifactId: spring-cloud-spring-pageable
hideGenerationTimestamp: 'true'

View File

@@ -1,7 +1,7 @@
generatorName: spring
library: spring-http-interface
outputDir: samples/client/petstore/spring-http-interface-reactive
inputSpec: modules/openapi-generator/src/test/resources/2_0/petstore-with-fake-endpoints-models-for-testing.yaml
inputSpec: modules/openapi-generator/src/test/resources/3_0/spring/petstore-with-fake-endpoints-models-for-testing.yaml
templateDir: modules/openapi-generator/src/main/resources/JavaSpring
additionalProperties:
artifactId: spring-http-interface-reactive

View File

@@ -1,10 +1,11 @@
generatorName: spring
library: spring-http-interface
outputDir: samples/client/petstore/spring-http-interface
inputSpec: modules/openapi-generator/src/test/resources/2_0/petstore-with-fake-endpoints-models-for-testing.yaml
inputSpec: modules/openapi-generator/src/test/resources/3_0/spring/petstore-with-fake-endpoints-models-for-testing.yaml
templateDir: modules/openapi-generator/src/main/resources/JavaSpring
additionalProperties:
artifactId: spring-http-interface
snapshotVersion: "true"
hideGenerationTimestamp: "true"
modelNameSuffix: 'Dto'
generatedConstructorWithRequiredArgs: "false"

View File

@@ -1,6 +1,6 @@
generatorName: spring
outputDir: samples/openapi3/client/petstore/spring-stubs
inputSpec: modules/openapi-generator/src/test/resources/2_0/petstore.yaml
inputSpec: modules/openapi-generator/src/test/resources/3_0/petstore.yaml
templateDir: modules/openapi-generator/src/main/resources/JavaSpring
additionalProperties:
groupId: org.openapitools.openapi3

View File

@@ -1,6 +1,6 @@
generatorName: spring
outputDir: samples/openapi3/client/petstore/spring-stubs-skip-default-interface
inputSpec: modules/openapi-generator/src/test/resources/2_0/petstore.yaml
inputSpec: modules/openapi-generator/src/test/resources/3_0/petstore.yaml
templateDir: modules/openapi-generator/src/main/resources/JavaSpring
additionalProperties:
groupId: org.openapitools.openapi3

View File

@@ -1,10 +0,0 @@
generatorName: spring
outputDir: samples/server/petstore/spring-stubs
inputSpec: modules/openapi-generator/src/test/resources/2_0/petstore.yaml
templateDir: modules/openapi-generator/src/main/resources/JavaSpring
additionalProperties:
documentationProvider: springfox
artifactId: spring-stubs
interfaceOnly: "true"
singleContentTypes: "true"
hideGenerationTimestamp: "true"

View File

@@ -1,7 +1,7 @@
generatorName: spring
outputDir: samples/server/petstore/springboot-spring-pageable-delegatePattern-without-j8
library: spring-boot
inputSpec: modules/openapi-generator/src/test/resources/2_0/petstore-with-fake-endpoints-models-for-testing-with-spring-pageable.yaml
inputSpec: modules/openapi-generator/src/test/resources/3_0/spring/petstore-with-fake-endpoints-models-for-testing-with-spring-pageable.yaml
templateDir: modules/openapi-generator/src/main/resources/JavaSpring
delegatePattern: true
java8: false

View File

@@ -1,10 +1,11 @@
generatorName: spring
outputDir: samples/server/petstore/springboot-spring-pageable-delegatePattern
library: spring-boot
inputSpec: modules/openapi-generator/src/test/resources/2_0/petstore-with-fake-endpoints-models-for-testing-with-spring-pageable.yaml
inputSpec: modules/openapi-generator/src/test/resources/3_0/spring/petstore-with-fake-endpoints-models-for-testing-with-spring-pageable.yaml
templateDir: modules/openapi-generator/src/main/resources/JavaSpring
delegatePattern: true
additionalProperties:
documentationProvider: springfox
artifactId: springboot-spring-pageable-delegatePattern
hideGenerationTimestamp: 'true'
implicitHeadersRegex: ^Version.*

View File

@@ -1,7 +1,7 @@
generatorName: spring
outputDir: samples/server/petstore/springboot-spring-pageable-without-j8
library: spring-boot
inputSpec: modules/openapi-generator/src/test/resources/2_0/petstore-with-fake-endpoints-models-for-testing-with-spring-pageable.yaml
inputSpec: modules/openapi-generator/src/test/resources/3_0/spring/petstore-with-fake-endpoints-models-for-testing-with-spring-pageable.yaml
templateDir: modules/openapi-generator/src/main/resources/JavaSpring
java8: false
additionalProperties:

View File

@@ -1,9 +1,10 @@
generatorName: spring
outputDir: samples/server/petstore/springboot-spring-pageable
library: spring-boot
inputSpec: modules/openapi-generator/src/test/resources/2_0/petstore-with-fake-endpoints-models-for-testing-with-spring-pageable.yaml
inputSpec: modules/openapi-generator/src/test/resources/3_0/spring/petstore-with-fake-endpoints-models-for-testing-with-spring-pageable.yaml
templateDir: modules/openapi-generator/src/main/resources/JavaSpring
additionalProperties:
documentationProvider: springfox
artifactId: springboot-spring-pageable
hideGenerationTimestamp: 'true'
implicitHeadersRegex: ^Version.*

View File

@@ -0,0 +1,10 @@
generatorName: swift5
outputDir: samples/client/petstore/swift5/anycodable
inputSpec: modules/openapi-generator/src/test/resources/3_0/any_codable.yaml
modelNamePrefix: Prefix
modelNameSuffix: Suffix
additionalProperties:
podAuthors: ""
podSummary: PetstoreClient
projectName: PetstoreClient
podHomepage: https://github.com/openapitools/openapi-generator

View File

@@ -1,6 +0,0 @@
generatorName: csharp-dotnet2
outputDir: samples/client/petstore/csharp-dotnet2/OpenAPIClientTest/Lib/OpenAPIClient
inputSpec: modules/openapi-generator/src/test/resources/2_0/petstore.yaml
templateDir: modules/openapi-generator/src/main/resources/csharp-dotnet2
additionalProperties:
hideGenerationTimestamp: "true"

View File

@@ -10,10 +10,7 @@ trigger_map:
workflows:
primary:
steps:
- git-clone@6.2.1: {}
- brew-install@0.12.1:
inputs:
- packages: maven
- git-clone@8.0.0: {}
- script@1.2.0:
title: Install Cocoapods
inputs:
@@ -21,15 +18,6 @@ workflows:
#!/usr/bin/env bash
sudo gem install cocoapods
- script@1.2.0:
inputs:
- content: |
#!/usr/bin/env bash
set -e
mvn --no-snapshot-updates package -Dorg.slf4j.simpleLogger.defaultLogLevel=error
title: Build openapi-generator
- script@1.2.0:
title: Run Swift5 tests
inputs:
@@ -42,4 +30,4 @@ workflows:
meta:
bitrise.io:
stack: osx-xcode-14.1.x
stack: osx-xcode-14.2.x

View File

@@ -477,3 +477,38 @@ Example:
```
java -jar modules/openapi-generator-cli/target/openapi-generator-cli.jar generate -g java -i modules/openapi-generator/src/test/resources/3_0/simplifyAnyOfStringAndEnumString_test.yaml -o /tmp/java-okhttp/ --openapi-normalizer SIMPLIFY_ANYOF_STRING_AND_ENUM_STRING=true
```
- `SIMPLIFY_BOOLEAN_ENUM`: when set to `true`, convert boolean enum to just enum.
Example:
```
java -jar modules/openapi-generator-cli/target/openapi-generator-cli.jar generate -g java -i modules/openapi-generator/src/test/resources/3_0/simplifyBooleanEnum_test.yaml -o /tmp/java-okhttp/ --openapi-normalizer SIMPLIFY_BOOLEAN_ENUM=true
```
- `SIMPLIFY_ONEOF_ANYOF`: when set to `true`, simplify oneOf/anyOf by 1) removing null (sub-schema) or enum of null (sub-schema) and setting nullable to true instead, and 2) simplifying oneOf/anyOf with a single sub-schema to just the sub-schema itself.
Example:
```
java -jar modules/openapi-generator-cli/target/openapi-generator-cli.jar generate -g java -i modules/openapi-generator/src/test/resources/3_0/simplifyOneOfAnyOf_test.yaml -o /tmp/java-okhttp/ --openapi-normalizer SIMPLIFY_ONEOF_ANYOF=true
```
- `KEEP_ONLY_FIRST_TAG_IN_OPERATION`: when set to `true`, only keep the first tag in operation if there are more than one tag defined.
Example:
```
java -jar modules/openapi-generator-cli/target/openapi-generator-cli.jar generate -g java -i modules/openapi-generator/src/test/resources/3_0/enableKeepOnlyFirstTagInOperation_test.yaml -o /tmp/java-okhttp/ --openapi-normalizer KEEP_ONLY_FIRST_TAG_IN_OPERATION=true
```
- `SET_TAGS_FOR_ALL_OPERATIONS`: when set to a string value, tags in all operatinos will reset to the string value provided.
Example:
```
java -jar modules/openapi-generator-cli/target/openapi-generator-cli.jar generate -g java -i modules/openapi-generator/src/test/resources/3_0/enableKeepOnlyFirstTagInOperation_test.yaml -o /tmp/java-okhttp/ --openapi-normalizer SET_TAGS_FOR_ALL_OPERATIONS=true
```
- `ADD_UNSIGNED_TO_INTEGER_WITH_INVALID_MAX_VALUE`: when set to true, auto fix integer with maximum value 4294967295 (2^32-1) or long with 18446744073709551615 (2^64-1) by adding x-unsigned to the schema
Example:
```
java -jar modules/openapi-generator-cli/target/openapi-generator-cli.jar generate -g java -i modules/openapi-generator/src/test/resources/3_0/addUnsignedToIntegerWithInvalidMaxValue_test.yaml -o /tmp/java-okhttp/ --openapi-normalizer ADD_UNSIGNED_TO_INTEGER_WITH_INVALID_MAX_VALUE=true
```

View File

@@ -19,7 +19,6 @@ The following generators are available:
* [cpp-ue4 (beta)](generators/cpp-ue4.md)
* [crystal (beta)](generators/crystal.md)
* [csharp](generators/csharp.md)
* [csharp-dotnet2 (deprecated)](generators/csharp-dotnet2.md)
* [csharp-netcore](generators/csharp-netcore.md)
* [dart](generators/dart.md)
* [dart-dio](generators/dart-dio.md)

View File

@@ -105,6 +105,10 @@ These options may be applied as additional-properties (cli) or configOptions (pl
<li>long</li>
<li>long?</li>
<li>string</li>
<li>uint</li>
<li>uint?</li>
<li>ulong</li>
<li>ulong?</li>
</ul>
## RESERVED WORDS

View File

@@ -1,293 +0,0 @@
---
title: Documentation for the csharp-dotnet2 Generator
---
## METADATA
| Property | Value | Notes |
| -------- | ----- | ----- |
| generator name | csharp-dotnet2 | pass this to the generate command after -g |
| generator stability | DEPRECATED | |
| generator type | CLIENT | |
| generator language | C# | |
| generator default templating engine | mustache | |
| helpTxt | Generates a C# .Net 2.0 client library (beta). | |
## CONFIG OPTIONS
These options may be applied as additional-properties (cli) or configOptions (plugins). Refer to [configuration docs](https://openapi-generator.tech/docs/configuration) for more details.
| Option | Description | Values | Default |
| ------ | ----------- | ------ | ------- |
|clientPackage|C# client package name (convention: Camel.Case).| |Org.OpenAPITools.Client|
|packageName|C# package name (convention: Camel.Case).| |Org.OpenAPITools|
|packageVersion|C# package version.| |1.0.0|
## IMPORT MAPPING
| Type/Alias | Imports |
| ---------- | ------- |
## INSTANTIATION TYPES
| Type/Alias | Instantiated By |
| ---------- | --------------- |
|array|List|
|list|List|
|map|Dictionary|
## LANGUAGE PRIMITIVES
<ul class="column-ul">
<li>Boolean</li>
<li>Collection</li>
<li>DateTime</li>
<li>DateTime?</li>
<li>DateTimeOffset</li>
<li>DateTimeOffset?</li>
<li>Decimal</li>
<li>Dictionary</li>
<li>Double</li>
<li>Float</li>
<li>Guid</li>
<li>Guid?</li>
<li>ICollection</li>
<li>Int32</li>
<li>Int64</li>
<li>List</li>
<li>Object</li>
<li>String</li>
<li>System.IO.Stream</li>
<li>bool</li>
<li>bool?</li>
<li>byte[]</li>
<li>decimal</li>
<li>decimal?</li>
<li>double</li>
<li>double?</li>
<li>float</li>
<li>float?</li>
<li>int</li>
<li>int?</li>
<li>long</li>
<li>long?</li>
<li>string</li>
</ul>
## RESERVED WORDS
<ul class="column-ul">
<li>Client</li>
<li>Configuration</li>
<li>Version</li>
<li>abstract</li>
<li>as</li>
<li>base</li>
<li>bool</li>
<li>break</li>
<li>byte</li>
<li>case</li>
<li>catch</li>
<li>char</li>
<li>checked</li>
<li>class</li>
<li>client</li>
<li>const</li>
<li>continue</li>
<li>decimal</li>
<li>default</li>
<li>delegate</li>
<li>do</li>
<li>double</li>
<li>else</li>
<li>enum</li>
<li>event</li>
<li>explicit</li>
<li>extern</li>
<li>false</li>
<li>finally</li>
<li>fixed</li>
<li>float</li>
<li>for</li>
<li>foreach</li>
<li>goto</li>
<li>if</li>
<li>implicit</li>
<li>in</li>
<li>int</li>
<li>interface</li>
<li>internal</li>
<li>is</li>
<li>localVarFileParams</li>
<li>localVarFormParams</li>
<li>localVarHeaderParams</li>
<li>localVarHttpContentType</li>
<li>localVarHttpContentTypes</li>
<li>localVarHttpHeaderAccept</li>
<li>localVarHttpHeaderAccepts</li>
<li>localVarPath</li>
<li>localVarPathParams</li>
<li>localVarPostBody</li>
<li>localVarQueryParams</li>
<li>localVarResponse</li>
<li>localVarStatusCode</li>
<li>lock</li>
<li>long</li>
<li>namespace</li>
<li>new</li>
<li>null</li>
<li>object</li>
<li>operator</li>
<li>out</li>
<li>override</li>
<li>parameter</li>
<li>params</li>
<li>private</li>
<li>protected</li>
<li>public</li>
<li>readonly</li>
<li>ref</li>
<li>return</li>
<li>sbyte</li>
<li>sealed</li>
<li>short</li>
<li>sizeof</li>
<li>stackalloc</li>
<li>static</li>
<li>string</li>
<li>struct</li>
<li>switch</li>
<li>this</li>
<li>throw</li>
<li>true</li>
<li>try</li>
<li>typeof</li>
<li>uint</li>
<li>ulong</li>
<li>unchecked</li>
<li>unsafe</li>
<li>ushort</li>
<li>using</li>
<li>virtual</li>
<li>void</li>
<li>volatile</li>
<li>while</li>
</ul>
## FEATURE SET
### Client Modification Feature
| Name | Supported | Defined By |
| ---- | --------- | ---------- |
|BasePath|✗|ToolingExtension
|Authorizations|✗|ToolingExtension
|UserAgent|✗|ToolingExtension
|MockServer|✗|ToolingExtension
### Data Type Feature
| Name | Supported | Defined By |
| ---- | --------- | ---------- |
|Custom|✗|OAS2,OAS3
|Int32|✓|OAS2,OAS3
|Int64|✓|OAS2,OAS3
|Float|✓|OAS2,OAS3
|Double|✓|OAS2,OAS3
|Decimal|✓|ToolingExtension
|String|✓|OAS2,OAS3
|Byte|✓|OAS2,OAS3
|Binary|✓|OAS2,OAS3
|Boolean|✓|OAS2,OAS3
|Date|✓|OAS2,OAS3
|DateTime|✓|OAS2,OAS3
|Password|✓|OAS2,OAS3
|File|✓|OAS2
|Uuid|✗|
|Array|✓|OAS2,OAS3
|Null|✗|OAS3
|AnyType|✗|OAS2,OAS3
|Object|✓|OAS2,OAS3
|Maps|✓|ToolingExtension
|CollectionFormat|✓|OAS2
|CollectionFormatMulti|✓|OAS2
|Enum|✓|OAS2,OAS3
|ArrayOfEnum|✓|ToolingExtension
|ArrayOfModel|✓|ToolingExtension
|ArrayOfCollectionOfPrimitives|✓|ToolingExtension
|ArrayOfCollectionOfModel|✓|ToolingExtension
|ArrayOfCollectionOfEnum|✓|ToolingExtension
|MapOfEnum|✓|ToolingExtension
|MapOfModel|✓|ToolingExtension
|MapOfCollectionOfPrimitives|✓|ToolingExtension
|MapOfCollectionOfModel|✓|ToolingExtension
|MapOfCollectionOfEnum|✓|ToolingExtension
### Documentation Feature
| Name | Supported | Defined By |
| ---- | --------- | ---------- |
|Readme|✓|ToolingExtension
|Model|✓|ToolingExtension
|Api|✓|ToolingExtension
### Global Feature
| Name | Supported | Defined By |
| ---- | --------- | ---------- |
|Host|✓|OAS2,OAS3
|BasePath|✓|OAS2,OAS3
|Info|✓|OAS2,OAS3
|Schemes|✗|OAS2,OAS3
|PartialSchemes|✓|OAS2,OAS3
|Consumes|✓|OAS2
|Produces|✓|OAS2
|ExternalDocumentation|✓|OAS2,OAS3
|Examples|✓|OAS2,OAS3
|XMLStructureDefinitions|✗|OAS2,OAS3
|MultiServer|✗|OAS3
|ParameterizedServer|✗|OAS3
|ParameterStyling|✗|OAS3
|Callbacks|✓|OAS3
|LinkObjects|✗|OAS3
### Parameter Feature
| Name | Supported | Defined By |
| ---- | --------- | ---------- |
|Path|✓|OAS2,OAS3
|Query|✓|OAS2,OAS3
|Header|✓|OAS2,OAS3
|Body|✓|OAS2
|FormUnencoded|✓|OAS2
|FormMultipart|✓|OAS2
|Cookie|✓|OAS3
### Schema Support Feature
| Name | Supported | Defined By |
| ---- | --------- | ---------- |
|Simple|✓|OAS2,OAS3
|Composite|✓|OAS2,OAS3
|Polymorphism|✓|OAS2,OAS3
|Union|✗|OAS3
|allOf|✗|OAS2,OAS3
|anyOf|✗|OAS3
|oneOf|✗|OAS3
|not|✗|OAS3
### Security Feature
| Name | Supported | Defined By |
| ---- | --------- | ---------- |
|BasicAuth|✓|OAS2,OAS3
|ApiKey|✓|OAS2,OAS3
|OpenIDConnect|✗|OAS3
|BearerToken|✓|OAS3
|OAuth2_Implicit|✓|OAS2,OAS3
|OAuth2_Password|✓|OAS2,OAS3
|OAuth2_ClientCredentials|✓|OAS2,OAS3
|OAuth2_AuthorizationCode|✓|OAS2,OAS3
### Wire Format Feature
| Name | Supported | Defined By |
| ---- | --------- | ---------- |
|JSON|✓|OAS2,OAS3
|XML|✓|OAS2,OAS3
|PROTOBUF|✗|ToolingExtension
|Custom|✗|OAS2,OAS3

View File

@@ -98,6 +98,10 @@ These options may be applied as additional-properties (cli) or configOptions (pl
<li>long</li>
<li>long?</li>
<li>string</li>
<li>uint</li>
<li>uint?</li>
<li>ulong</li>
<li>ulong?</li>
</ul>
## RESERVED WORDS

View File

@@ -22,10 +22,12 @@ These options may be applied as additional-properties (cli) or configOptions (pl
|apiName|Must be a valid C# class name. Only used in Generic Host library. Default: Api| |Api|
|caseInsensitiveResponseHeaders|Make API response's headers case-insensitive| |false|
|conditionalSerialization|Serialize only those properties which are initialized by user, accepted values are true or false, default value is false.| |false|
|dateFormat|The default Date format (only `generichost` library supports this option).| |yyyy'-'MM'-'dd|
|dateTimeFormat|The default DateTime format (only `generichost` library supports this option).| |yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffffK|
|disallowAdditionalPropertiesIfNotPresent|If false, the 'additionalProperties' implementation (set to true by default) is compliant with the OAS and JSON schema specifications. If true (default), keep the old (incorrect) behaviour that 'additionalProperties' is set to false by default.|<dl><dt>**false**</dt><dd>The 'additionalProperties' implementation is compliant with the OAS and JSON schema specifications.</dd><dt>**true**</dt><dd>Keep the old (incorrect) behaviour that 'additionalProperties' is set to false by default.</dd></dl>|true|
|hideGenerationTimestamp|Hides the generation timestamp when files are generated.| |true|
|interfacePrefix|Prefix interfaces with a community standard or widely accepted prefix.| |I|
|library|HTTP library template (sub-template) to use|<dl><dt>**generichost**</dt><dd>HttpClient with Generic Host dependency injection (https://docs.microsoft.com/en-us/dotnet/core/extensions/generic-host) (Experimental. Subject to breaking changes without notice.)</dd><dt>**httpclient**</dt><dd>HttpClient (https://docs.microsoft.com/en-us/dotnet/api/system.net.http.httpclient) (Experimental. Subject to breaking changes without notice.)</dd><dt>**restsharp**</dt><dd>RestSharp (https://github.com/restsharp/RestSharp)</dd></dl>|restsharp|
|library|HTTP library template (sub-template) to use|<dl><dt>**generichost**</dt><dd>HttpClient with Generic Host dependency injection (https://docs.microsoft.com/en-us/dotnet/core/extensions/generic-host) (Experimental. Subject to breaking changes without notice.)</dd><dt>**httpclient**</dt><dd>HttpClient (https://docs.microsoft.com/en-us/dotnet/api/system.net.http.httpclient) (Experimental. Subject to breaking changes without notice.)</dd><dt>**unityWebRequest**</dt><dd>UnityWebRequest (...) (Experimental. Subject to breaking changes without notice.)</dd><dt>**restsharp**</dt><dd>RestSharp (https://github.com/restsharp/RestSharp)</dd></dl>|restsharp|
|licenseId|The identifier of the license| |null|
|modelPropertyNaming|Naming convention for the property: 'camelCase', 'PascalCase', 'snake_case' and 'original', which keeps the original name| |PascalCase|
|netCoreProjectFile|Use the new format (.NET Core) for .NET project files (.csproj).| |false|
@@ -99,6 +101,10 @@ These options may be applied as additional-properties (cli) or configOptions (pl
<li>long</li>
<li>long?</li>
<li>string</li>
<li>uint</li>
<li>uint?</li>
<li>ulong</li>
<li>ulong?</li>
</ul>
## RESERVED WORDS

View File

@@ -93,6 +93,10 @@ These options may be applied as additional-properties (cli) or configOptions (pl
<li>long</li>
<li>long?</li>
<li>string</li>
<li>uint</li>
<li>uint?</li>
<li>ulong</li>
<li>ulong?</li>
</ul>
## RESERVED WORDS

View File

@@ -218,7 +218,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl
|BasicAuth|✓|OAS2,OAS3
|ApiKey|✓|OAS2,OAS3
|OpenIDConnect|✗|OAS3
|BearerToken||OAS3
|BearerToken||OAS3
|OAuth2_Implicit|✓|OAS2,OAS3
|OAuth2_Password|✗|OAS2,OAS3
|OAuth2_ClientCredentials|✗|OAS2,OAS3

View File

@@ -56,6 +56,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl
|ensureUniqueParams|Whether to ensure parameter names are unique in an operation (rename parameters that are not).| |true|
|enumUnknownDefaultCase|If the server adds new enum cases, that are unknown by an old spec/client, the client will fail to parse the network response.With this option enabled, each enum will have a new case, 'unknown_default_open_api', so that when the server sends an enum case that is not known by the client/spec, they can safely fallback to this case.|<dl><dt>**false**</dt><dd>No changes to the enum's are made, this is the default option.</dd><dt>**true**</dt><dd>With this option enabled, each enum will have a new case, 'unknown_default_open_api', so that when the enum case sent by the server is not known by the client/spec, can safely be decoded to this case.</dd></dl>|false|
|fullJavaUtil|whether to use fully qualified name for classes under java.util. This option only works for Java API client| |false|
|generatedConstructorWithRequiredArgs|Whether to generate constructors with required args for models| |true|
|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|
@@ -96,6 +97,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl
|useFeignClientUrl|Whether to generate Feign client with url parameter.| |true|
|useJakartaEe|whether to use Jakarta EE namespace instead of javax| |false|
|useOptional|Use Optional container for optional parameters| |false|
|useResponseEntity|Use the `ResponseEntity` type to wrap return values of generated API methods. If disabled, method are annotated using a `@ResponseStatus` annotation, which has the status of the first response declared in the Api definition| |true|
|useSpringBoot3|Generate code and provide dependencies for use with Spring Boot 3.x. (Use jakarta instead of javax in imports). Enabling this option will also enable `useJakartaEe`.| |false|
|useSpringController|Annotate the generated API as a Spring Controller| |false|
|useSwaggerUI|Open the OpenApi specification in swagger-ui. Will also import and configure needed dependencies| |true|
@@ -116,6 +118,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl
|x-class-extra-annotation|List of custom annotations to be added to model|MODEL|null
|x-field-extra-annotation|List of custom annotations to be added to property|FIELD|null
|x-spring-paginated|Add org.springframework.data.domain.Pageable to controller method. Can be used to handle page & size query parameters|OPERATION|false
|x-version-param|Marker property that tells that this parameter would be used for endpoint versioning. Applicable for headers & query params. true/false|OPERATION_PARAMETER|null
## IMPORT MAPPING

View File

@@ -44,6 +44,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl
|serverPort|configuration the port in which the sever is to run on| |8080|
|serviceImplementation|generate stub service implementations that extends service interfaces. If this is set to true service interfaces will also be generated| |false|
|serviceInterface|generate service interfaces to go alongside controllers. In most cases this option would be used to update an existing project, so not to override implementations. Useful to help facilitate the generation gap pattern| |false|
|skipDefaultInterface|Whether to skip generation of default implementations for interfaces| |false|
|sortModelPropertiesByRequiredFlag|Sort model properties to place required parameters before optional parameters.| |null|
|sortParamsByRequiredFlag|Sort method arguments to place required parameters before optional parameters.| |null|
|sourceFolder|source folder for generated code| |src/main/kotlin|

View File

@@ -20,6 +20,8 @@ These options may be applied as additional-properties (cli) or configOptions (pl
| Option | Description | Values | Default |
| ------ | ----------- | ------ | ------- |
|allowStringInDateTimeParameters|Allow string as input to datetime/date parameters for backward compartibility.| |false|
|dateFormat|date format for query parameters| |%Y-%m-%d|
|datetimeFormat|datetime format for query parameters| |%Y-%m-%dT%H:%M:%S%z|
|disallowAdditionalPropertiesIfNotPresent|If false, the 'additionalProperties' implementation (set to true by default) is compliant with the OAS and JSON schema specifications. If true (default), keep the old (incorrect) behaviour that 'additionalProperties' is set to false by default.|<dl><dt>**false**</dt><dd>The 'additionalProperties' implementation is compliant with the OAS and JSON schema specifications.</dd><dt>**true**</dt><dd>Keep the old (incorrect) behaviour that 'additionalProperties' is set to false by default.</dd></dl>|true|
|floatStrictType|Use strict type for float, i.e. StrictFloat or confloat(strict=true, ...)| |true|
|generateSourceCodeOnly|Specifies that only a library source code is to be generated.| |false|

View File

@@ -49,6 +49,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl
|ensureUniqueParams|Whether to ensure parameter names are unique in an operation (rename parameters that are not).| |true|
|enumUnknownDefaultCase|If the server adds new enum cases, that are unknown by an old spec/client, the client will fail to parse the network response.With this option enabled, each enum will have a new case, 'unknown_default_open_api', so that when the server sends an enum case that is not known by the client/spec, they can safely fallback to this case.|<dl><dt>**false**</dt><dd>No changes to the enum's are made, this is the default option.</dd><dt>**true**</dt><dd>With this option enabled, each enum will have a new case, 'unknown_default_open_api', so that when the enum case sent by the server is not known by the client/spec, can safely be decoded to this case.</dd></dl>|false|
|fullJavaUtil|whether to use fully qualified name for classes under java.util. This option only works for Java API client| |false|
|generatedConstructorWithRequiredArgs|Whether to generate constructors with required args for models| |true|
|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|
@@ -89,6 +90,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl
|useFeignClientUrl|Whether to generate Feign client with url parameter.| |true|
|useJakartaEe|whether to use Jakarta EE namespace instead of javax| |false|
|useOptional|Use Optional container for optional parameters| |false|
|useResponseEntity|Use the `ResponseEntity` type to wrap return values of generated API methods. If disabled, method are annotated using a `@ResponseStatus` annotation, which has the status of the first response declared in the Api definition| |true|
|useSpringBoot3|Generate code and provide dependencies for use with Spring Boot 3.x. (Use jakarta instead of javax in imports). Enabling this option will also enable `useJakartaEe`.| |false|
|useSpringController|Annotate the generated API as a Spring Controller| |false|
|useSwaggerUI|Open the OpenApi specification in swagger-ui. Will also import and configure needed dependencies| |true|
@@ -109,6 +111,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl
|x-class-extra-annotation|List of custom annotations to be added to model|MODEL|null
|x-field-extra-annotation|List of custom annotations to be added to property|FIELD|null
|x-spring-paginated|Add org.springframework.data.domain.Pageable to controller method. Can be used to handle page & size query parameters|OPERATION|false
|x-version-param|Marker property that tells that this parameter would be used for endpoint versioning. Applicable for headers & query params. true/false|OPERATION_PARAMETER|null
## IMPORT MAPPING

View File

@@ -74,6 +74,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl
<ul class="column-ul">
<li>Any</li>
<li>AnyCodable</li>
<li>AnyObject</li>
<li>Bool</li>
<li>Character</li>

View File

@@ -125,6 +125,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl
<li>native</li>
<li>new</li>
<li>null</li>
<li>options</li>
<li>package</li>
<li>private</li>
<li>protected</li>

View File

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

View File

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

View File

@@ -1,5 +1,5 @@
# RELEASE_VERSION
openApiGeneratorVersion=6.4.0
openApiGeneratorVersion=6.5.0-SNAPSHOT
# /RELEASE_VERSION
# BEGIN placeholders

View File

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

View File

@@ -1,3 +1,3 @@
# RELEASE_VERSION
openApiGeneratorVersion=6.4.0
openApiGeneratorVersion=6.5.0-SNAPSHOT
# /RELEASE_VERSION

View File

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

View File

@@ -15,7 +15,7 @@
<groupId>org.openapitools</groupId>
<artifactId>openapi-generator-maven-plugin</artifactId>
<!-- RELEASE_VERSION -->
<version>6.4.0</version>
<version>6.5.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>6.4.0</version>
<version>6.5.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>6.4.0</version>
<version>6.5.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>6.4.0</version>
<version>6.5.0-SNAPSHOT</version>
<!-- /RELEASE_VERSION -->
<executions>
<execution>

View File

@@ -20,7 +20,7 @@
<groupId>org.openapitools</groupId>
<artifactId>openapi-generator-maven-plugin</artifactId>
<!-- RELEASE_VERSION -->
<version>6.4.0</version>
<version>6.5.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>6.4.0</version>
<version>6.5.0-SNAPSHOT</version>
<!-- /RELEASE_VERSION -->
<relativePath>../..</relativePath>
</parent>

View File

@@ -4,7 +4,7 @@
<groupId>org.openapitools</groupId>
<artifactId>openapi-generator-project</artifactId>
<!-- RELEASE_VERSION -->
<version>6.4.0</version>
<version>6.5.0-SNAPSHOT</version>
<!-- /RELEASE_VERSION -->
<relativePath>../..</relativePath>
</parent>
@@ -12,7 +12,7 @@
<packaging>jar</packaging>
<name>openapi-generator-online</name>
<properties>
<spring-boot.version>2.7.5</spring-boot.version>
<spring-boot.version>2.5.14</spring-boot.version>
<springfox-version>3.0.0</springfox-version>
<sonar.exclusions>**/org/openapitools/codegen/online/**/*</sonar.exclusions>
</properties>

View File

@@ -4,7 +4,7 @@
<groupId>org.openapitools</groupId>
<artifactId>openapi-generator-project</artifactId>
<!-- RELEASE_VERSION -->
<version>6.4.0</version>
<version>6.5.0-SNAPSHOT</version>
<!-- /RELEASE_VERSION -->
<relativePath>../..</relativePath>
</parent>
@@ -272,6 +272,12 @@
<artifactId>commons-io</artifactId>
<version>${commons-io.version}</version>
</dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>1.2.11</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-ext</artifactId>

View File

@@ -75,6 +75,7 @@ public class CodegenModel implements IJsonSchemaValidationProperties {
public List<CodegenProperty> readOnlyVars = new ArrayList<>(); // a list of read-only properties
public List<CodegenProperty> readWriteVars = new ArrayList<>(); // a list of properties for read, write
public List<CodegenProperty> parentVars = new ArrayList<>();
public List<CodegenProperty> parentRequiredVars = new ArrayList<>();
public List<CodegenProperty> nonNullableVars = new ArrayList<>(); // a list of non-nullable properties
public Map<String, Object> allowableValues;

View File

@@ -27,6 +27,7 @@ public class CodegenOperation {
public boolean hasAuthMethods, hasConsumes, hasProduces, hasParams, hasOptionalParams, hasRequiredParams,
returnTypeIsPrimitive, returnSimpleType, subresourceOperation, isMap,
isArray, isMultipart,
hasVersionHeaders = false, hasVersionQueryParams = false,
isResponseBinary = false, isResponseFile = false, isResponseOptional = false, hasReference = false, defaultReturnType = false,
isRestfulIndex, isRestfulShow, isRestfulCreate, isRestfulUpdate, isRestfulDestroy,
isRestful, isDeprecated, isCallbackRequest, uniqueItems, hasDefaultResponse = false,

View File

@@ -35,7 +35,7 @@ public class CodegenParameter implements IJsonSchemaValidationProperties {
public String example; // example value (x-example)
public String jsonSchema;
public boolean isString, isNumeric, isInteger, isLong, isNumber, isFloat, isDouble, isDecimal, isByteArray, isBinary,
isBoolean, isDate, isDateTime, isUuid, isUri, isEmail, isFreeFormObject, isAnyType, isShort, isUnboundedInteger;
isBoolean, isDate, isDateTime, isUuid, isUri, isEmail, isPassword, isFreeFormObject, isAnyType, isShort, isUnboundedInteger;
public boolean isArray, isMap;
public boolean isFile;
public boolean isEnum;
@@ -229,6 +229,7 @@ public class CodegenParameter implements IJsonSchemaValidationProperties {
output.isUuid = this.isUuid;
output.isUri = this.isUri;
output.isEmail = this.isEmail;
output.isPassword = this.isPassword;
output.isFreeFormObject = this.isFreeFormObject;
output.isAnyType = this.isAnyType;
output.isArray = this.isArray;
@@ -244,7 +245,7 @@ public class CodegenParameter implements IJsonSchemaValidationProperties {
@Override
public int hashCode() {
return Objects.hash(isFormParam, isQueryParam, isPathParam, isHeaderParam, isCookieParam, isBodyParam, isContainer, isCollectionFormatMulti, isPrimitiveType, isModel, isExplode, baseName, paramName, dataType, datatypeWithEnum, dataFormat, collectionFormat, description, unescapedDescription, baseType, defaultValue, enumDefaultValue, enumName, style, isDeepObject, isAllowEmptyValue, example, jsonSchema, isString, isNumeric, isInteger, isLong, isNumber, isFloat, isDouble, isDecimal, isByteArray, isBinary, isBoolean, isDate, isDateTime, isUuid, isUri, isEmail, isFreeFormObject, isAnyType, isArray, isMap, isFile, isEnum, _enum, allowableValues, items, mostInnerItems, additionalProperties, vars, requiredVars, vendorExtensions, hasValidation, getMaxProperties(), getMinProperties(), isNullable, isDeprecated, required, getMaximum(), getExclusiveMaximum(), getMinimum(), getExclusiveMinimum(), getMaxLength(), getMinLength(), getPattern(), getMaxItems(), getMinItems(), getUniqueItems(), contentType, multipleOf, isNull, additionalPropertiesIsAnyType, hasVars, hasRequired, isShort, isUnboundedInteger, hasDiscriminatorWithNonEmptyMapping, composedSchemas, hasMultipleTypes, schema, content, requiredVarsMap, ref, uniqueItemsBoolean, schemaIsFromAdditionalProperties);
return Objects.hash(isFormParam, isQueryParam, isPathParam, isHeaderParam, isCookieParam, isBodyParam, isContainer, isCollectionFormatMulti, isPrimitiveType, isModel, isExplode, baseName, paramName, dataType, datatypeWithEnum, dataFormat, collectionFormat, description, unescapedDescription, baseType, defaultValue, enumDefaultValue, enumName, style, isDeepObject, isAllowEmptyValue, example, jsonSchema, isString, isNumeric, isInteger, isLong, isNumber, isFloat, isDouble, isDecimal, isByteArray, isBinary, isBoolean, isDate, isDateTime, isUuid, isUri, isEmail, isPassword, isFreeFormObject, isAnyType, isArray, isMap, isFile, isEnum, _enum, allowableValues, items, mostInnerItems, additionalProperties, vars, requiredVars, vendorExtensions, hasValidation, getMaxProperties(), getMinProperties(), isNullable, isDeprecated, required, getMaximum(), getExclusiveMaximum(), getMinimum(), getExclusiveMinimum(), getMaxLength(), getMinLength(), getPattern(), getMaxItems(), getMinItems(), getUniqueItems(), contentType, multipleOf, isNull, additionalPropertiesIsAnyType, hasVars, hasRequired, isShort, isUnboundedInteger, hasDiscriminatorWithNonEmptyMapping, composedSchemas, hasMultipleTypes, schema, content, requiredVarsMap, ref, uniqueItemsBoolean, schemaIsFromAdditionalProperties);
}
@Override
@@ -281,6 +282,7 @@ public class CodegenParameter implements IJsonSchemaValidationProperties {
isUuid == that.isUuid &&
isUri == that.isUri &&
isEmail == that.isEmail &&
isPassword == that.isPassword &&
isFreeFormObject == that.isFreeFormObject &&
isAnyType == that.isAnyType &&
isArray == that.isArray &&
@@ -394,6 +396,7 @@ public class CodegenParameter implements IJsonSchemaValidationProperties {
sb.append(", isUuid=").append(isUuid);
sb.append(", isUri=").append(isUri);
sb.append(", isEmail=").append(isEmail);
sb.append(", isPassword=").append(isPassword);
sb.append(", isFreeFormObject=").append(isFreeFormObject);
sb.append(", isAnyType=").append(isAnyType);
sb.append(", isArray=").append(isArray);

View File

@@ -134,6 +134,7 @@ public class CodegenProperty implements Cloneable, IJsonSchemaValidationProperti
public boolean isUuid;
public boolean isUri;
public boolean isEmail;
public boolean isPassword;
public boolean isNull;
/**
* The type is a free-form object, i.e. it is a map of string to values with no declared properties.
@@ -1051,6 +1052,7 @@ public class CodegenProperty implements Cloneable, IJsonSchemaValidationProperti
sb.append(", isUuid=").append(isUuid);
sb.append(", isUri=").append(isUri);
sb.append(", isEmail=").append(isEmail);
sb.append(", isPassword=").append(isPassword);
sb.append(", isFreeFormObject=").append(isFreeFormObject);
sb.append(", isArray=").append(isArray);
sb.append(", isMap=").append(isMap);
@@ -1142,6 +1144,7 @@ public class CodegenProperty implements Cloneable, IJsonSchemaValidationProperti
isUuid == that.isUuid &&
isUri == that.isUri &&
isEmail == that.isEmail &&
isPassword == that.isPassword &&
isFreeFormObject == that.isFreeFormObject &&
isArray == that.isArray &&
isMap == that.isMap &&
@@ -1231,7 +1234,7 @@ public class CodegenProperty implements Cloneable, IJsonSchemaValidationProperti
exclusiveMinimum, exclusiveMaximum, required, deprecated,
hasMoreNonReadOnly, isPrimitiveType, isModel, isContainer, isString, isNumeric,
isInteger, isLong, isNumber, isFloat, isDouble, isDecimal, isByteArray, isBinary, isFile,
isBoolean, isDate, isDateTime, isUuid, isUri, isEmail, isFreeFormObject,
isBoolean, isDate, isDateTime, isUuid, isUri, isEmail, isPassword, isFreeFormObject,
isArray, isMap, isEnum, isInnerEnum, isEnumRef, isAnyType, isReadOnly, isWriteOnly, isNullable, isShort,
isUnboundedInteger, isSelfReference, isCircularReference, isDiscriminator, isNew, _enum,
allowableValues, items, mostInnerItems, additionalProperties, vars, requiredVars,

View File

@@ -50,6 +50,7 @@ public class CodegenResponse implements IJsonSchemaValidationProperties {
public boolean isDateTime;
public boolean isUuid;
public boolean isEmail;
public boolean isPassword;
public boolean isModel;
public boolean isFreeFormObject;
public boolean isAnyType;
@@ -98,7 +99,7 @@ public class CodegenResponse implements IJsonSchemaValidationProperties {
public int hashCode() {
return Objects.hash(headers, code, message, examples, dataType, baseType, containerType, hasHeaders,
isString, isNumeric, isInteger, isLong, isNumber, isFloat, isDouble, isDecimal, isByteArray, isBoolean, isDate,
isDateTime, isUuid, isEmail, isModel, isFreeFormObject, isAnyType, isDefault, simpleType, primitiveType,
isDateTime, isUuid, isEmail, isPassword, isModel, isFreeFormObject, isAnyType, isDefault, simpleType, primitiveType,
isMap, isArray, isBinary, isFile, schema, jsonSchema, vendorExtensions, items, additionalProperties,
vars, requiredVars, isNull, hasValidation, isShort, isUnboundedInteger,
getMaxProperties(), getMinProperties(), uniqueItems, getMaxItems(), getMinItems(), getMaxLength(),
@@ -130,6 +131,7 @@ public class CodegenResponse implements IJsonSchemaValidationProperties {
isDateTime == that.isDateTime &&
isUuid == that.isUuid &&
isEmail == that.isEmail &&
isPassword == that.isPassword &&
isModel == that.isModel &&
isFreeFormObject == that.isFreeFormObject &&
isAnyType == that.isAnyType &&
@@ -568,6 +570,7 @@ public class CodegenResponse implements IJsonSchemaValidationProperties {
sb.append(", isDateTime=").append(isDateTime);
sb.append(", isUuid=").append(isUuid);
sb.append(", isEmail=").append(isEmail);
sb.append(", isPassword=").append(isPassword);
sb.append(", isModel=").append(isModel);
sb.append(", isFreeFormObject=").append(isFreeFormObject);
sb.append(", isAnyType=").append(isAnyType);

View File

@@ -25,11 +25,27 @@ import com.google.common.collect.ImmutableMap;
import com.samskivert.mustache.Mustache;
import com.samskivert.mustache.Mustache.Compiler;
import com.samskivert.mustache.Mustache.Lambda;
import io.swagger.v3.core.util.Json;
import io.swagger.v3.oas.models.OpenAPI;
import io.swagger.v3.oas.models.Operation;
import io.swagger.v3.oas.models.PathItem;
import io.swagger.v3.oas.models.callbacks.Callback;
import io.swagger.v3.oas.models.examples.Example;
import io.swagger.v3.oas.models.headers.Header;
import io.swagger.v3.oas.models.media.*;
import io.swagger.v3.oas.models.parameters.*;
import io.swagger.v3.oas.models.responses.ApiResponse;
import io.swagger.v3.oas.models.responses.ApiResponses;
import io.swagger.v3.oas.models.security.OAuthFlow;
import io.swagger.v3.oas.models.security.OAuthFlows;
import io.swagger.v3.oas.models.security.SecurityScheme;
import io.swagger.v3.oas.models.servers.Server;
import io.swagger.v3.oas.models.servers.ServerVariable;
import io.swagger.v3.parser.util.SchemaTypeUtil;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.text.StringEscapeUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.tuple.Pair;
import org.apache.commons.text.StringEscapeUtils;
import org.openapitools.codegen.CodegenDiscriminator.MappedModel;
import org.openapitools.codegen.api.TemplatingEngineAdapter;
import org.openapitools.codegen.config.GlobalSettings;
@@ -634,7 +650,7 @@ public class DefaultCodegen implements CodegenConfig {
parent.hasChildren = true;
Schema parentSchema = this.openAPI.getComponents().getSchemas().get(parent.name);
if (parentSchema == null) {
throw new NullPointerException(parent.name+" in "+this.openAPI.getComponents().getSchemas());
throw new NullPointerException(parent.name + " in " + this.openAPI.getComponents().getSchemas());
}
if (parentSchema.getDiscriminator() == null) {
parent = allModels.get(parent.getParent());
@@ -1728,9 +1744,11 @@ public class DefaultCodegen implements CodegenConfig {
typeMapping.put("DateTime", "Date");
typeMapping.put("long", "Long");
typeMapping.put("short", "Short");
typeMapping.put("integer", "Integer");
typeMapping.put("UnsignedInteger", "Integer");
typeMapping.put("UnsignedLong", "Long");
typeMapping.put("char", "String");
typeMapping.put("object", "Object");
typeMapping.put("integer", "Integer");
// FIXME: java specific type should be in Java Based Abstract Impl's
typeMapping.put("ByteArray", "byte[]");
typeMapping.put("binary", "File");
@@ -2062,7 +2080,7 @@ public class DefaultCodegen implements CodegenConfig {
if (encoding != null) {
boolean styleGiven = true;
Encoding.StyleEnum style = encoding.getStyle();
if(style == null || style == Encoding.StyleEnum.FORM) {
if (style == null || style == Encoding.StyleEnum.FORM) {
// (Unfortunately, swagger-parser-v3 will always provide 'form'
// when style is not specified, so we can't detect that)
style = Encoding.StyleEnum.FORM;
@@ -2070,12 +2088,12 @@ public class DefaultCodegen implements CodegenConfig {
}
boolean explodeGiven = true;
Boolean explode = encoding.getExplode();
if(explode == null) {
if (explode == null) {
explode = style == Encoding.StyleEnum.FORM; // Default to True when form, False otherwise
explodeGiven = false;
}
if(!styleGiven && !explodeGiven) {
if (!styleGiven && !explodeGiven) {
// Ignore contentType if style or explode are specified.
codegenParameter.contentType = encoding.getContentType();
}
@@ -2083,7 +2101,7 @@ public class DefaultCodegen implements CodegenConfig {
codegenParameter.style = style.toString();
codegenParameter.isDeepObject = Encoding.StyleEnum.DEEP_OBJECT == style;
if(codegenParameter.isContainer) {
if (codegenParameter.isContainer) {
codegenParameter.isExplode = explode;
String collectionFormat = getCollectionFormat(codegenParameter);
codegenParameter.collectionFormat = StringUtils.isEmpty(collectionFormat) ? "csv" : collectionFormat;
@@ -2394,8 +2412,14 @@ public class DefaultCodegen implements CodegenConfig {
return "number";
}
} else if (ModelUtils.isIntegerSchema(schema)) {
if (ModelUtils.isLongSchema(schema)) {
if (ModelUtils.isUnsignedLongSchema(schema)) {
return "UnsignedLong";
} else if (ModelUtils.isUnsignedIntegerSchema(schema)) {
return "UnsignedInteger";
} else if (ModelUtils.isLongSchema(schema)) {
return "long";
} else if (ModelUtils.isShortSchema(schema)) {// int32
return "integer";
} else {
return schema.getType(); // integer
}
@@ -3024,7 +3048,6 @@ public class DefaultCodegen implements CodegenConfig {
// referenced models here, component that refs another component which is a model
// if a component references a schema which is not a generated model, the refed schema will be loaded into
// schema by unaliasSchema and one of the above code paths will be taken
;
}
if (schema.get$ref() != null) {
m.setRef(schema.get$ref());
@@ -3672,6 +3695,8 @@ public class DefaultCodegen implements CodegenConfig {
property.isUri = true;
} else if (ModelUtils.isEmailSchema(p)) {
property.isEmail = true;
} else if (ModelUtils.isPasswordSchema(p)) {
property.isPassword = true;
} else if (ModelUtils.isDateSchema(p)) { // date format
property.setIsString(false); // for backward compatibility with 2.x
property.isDate = true;
@@ -3764,6 +3789,18 @@ public class DefaultCodegen implements CodegenConfig {
return cpc;
}
Schema original = null;
// check if it's allOf (only 1 sub schema) with default/nullable/etc set in the top level
if (ModelUtils.isAllOf(p) && p.getAllOf().size() == 1 && ModelUtils.hasCommonAttributesDefined(p) ) {
if (p.getAllOf().get(0) instanceof Schema) {
original = p;
p = (Schema) p.getAllOf().get(0);
} else {
LOGGER.error("Unknown type in allOf schema. Please report the issue via openapi-generator's Github issue tracker.");
}
}
CodegenProperty property = CodegenModelFactory.newInstance(CodegenModelType.PROPERTY);
if (p.equals(trueSchema)) {
property.setIsBooleanSchemaTrue(true);
@@ -3877,8 +3914,12 @@ public class DefaultCodegen implements CodegenConfig {
}
}
// set isNullable using nullable or x-nullable in the schema
if (referencedSchema.getNullable() != null) {
property.isNullable = referencedSchema.getNullable();
} else if (referencedSchema.getExtensions() != null &&
referencedSchema.getExtensions().containsKey("x-nullable")) {
property.isNullable = (Boolean) referencedSchema.getExtensions().get("x-nullable");
}
property.dataType = getTypeDeclaration(p);
@@ -3916,7 +3957,7 @@ public class DefaultCodegen implements CodegenConfig {
}
property.baseType = getSchemaType(p);
if (p.getXml() != null) {
property.isXmlWrapped = p.getXml().getWrapped() == null ? false : p.getXml().getWrapped();
property.isXmlWrapped = p.getXml().getWrapped() != null && p.getXml().getWrapped();
property.xmlPrefix = p.getXml().getPrefix();
property.xmlNamespace = p.getXml().getNamespace();
property.xmlName = p.getXml().getName();
@@ -3953,6 +3994,25 @@ public class DefaultCodegen implements CodegenConfig {
property.isModel = (ModelUtils.isComposedSchema(referencedSchema) || ModelUtils.isObjectSchema(referencedSchema)) && ModelUtils.isModel(referencedSchema);
}
// restore original schema with default value, nullable, readonly etc
if (original != null) {
p = original;
// evaluate common attributes defined in the top level
if (p.getNullable() != null) {
property.isNullable = p.getNullable();
} else if (p.getExtensions() != null && p.getExtensions().containsKey("x-nullable")) {
property.isNullable = (Boolean) p.getExtensions().get("x-nullable");
}
if (p.getReadOnly() != null) {
property.isReadOnly = p.getReadOnly();
}
if (p.getWriteOnly() != null) {
property.isWriteOnly = p.getWriteOnly();
}
}
// set the default value
property.defaultValue = toDefaultValue(property, p);
property.defaultValueWithParam = toDefaultValueWithParam(name, p);
@@ -4695,6 +4755,8 @@ public class DefaultCodegen implements CodegenConfig {
} else if (ModelUtils.isStringSchema(responseSchema)) {
if (ModelUtils.isEmailSchema(responseSchema)) {
r.isEmail = true;
} else if (ModelUtils.isPasswordSchema(responseSchema)) {
r.isPassword = true;
} else if (ModelUtils.isUUIDSchema(responseSchema)) {
r.isUuid = true;
} else if (ModelUtils.isByteArraySchema(responseSchema)) {
@@ -5005,7 +5067,7 @@ public class DefaultCodegen implements CodegenConfig {
// the default value is false
// https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.2.md#user-content-parameterexplode
codegenParameter.isExplode = parameter.getExplode() == null ? false : parameter.getExplode();
codegenParameter.isExplode = parameter.getExplode() != null && parameter.getExplode();
// TODO revise collectionFormat, default collection format in OAS 3 appears to multi at least for query parameters
// https://swagger.io/docs/specification/serialization/
@@ -5034,7 +5096,6 @@ public class DefaultCodegen implements CodegenConfig {
if (ModelUtils.isShortSchema(parameterSchema)) { // int32/short format
codegenParameter.isShort = true;
} else { // unbounded integer
;
}
}
} else if (ModelUtils.isTypeObjectSchema(parameterSchema)) {
@@ -5046,7 +5107,6 @@ public class DefaultCodegen implements CodegenConfig {
}
addVarsRequiredVarsAdditionalProps(parameterSchema, codegenParameter);
} else if (ModelUtils.isNullType(parameterSchema)) {
;
} else if (ModelUtils.isAnyType(parameterSchema)) {
// any schema with no type set, composed schemas often do this
if (ModelUtils.isMapSchema(parameterSchema)) { // for map parameter
@@ -5074,7 +5134,6 @@ public class DefaultCodegen implements CodegenConfig {
}
} else {
// referenced schemas
;
}
CodegenProperty codegenProperty = fromProperty(parameter.getName(), parameterSchema, false);
@@ -6243,6 +6302,8 @@ public class DefaultCodegen implements CodegenConfig {
}
if (Boolean.TRUE.equals(property.isEmail) && Boolean.TRUE.equals(property.isString)) {
parameter.isEmail = true;
} else if (Boolean.TRUE.equals(property.isPassword) && Boolean.TRUE.equals(property.isString)) {
parameter.isPassword = true;
} else if (Boolean.TRUE.equals(property.isUuid) && Boolean.TRUE.equals(property.isString)) {
parameter.isUuid = true;
} else if (Boolean.TRUE.equals(property.isByteArray)) {
@@ -6758,6 +6819,8 @@ public class DefaultCodegen implements CodegenConfig {
} else if (ModelUtils.isStringSchema(ps)) {
if (ModelUtils.isEmailSchema(ps)) {
codegenParameter.isEmail = true;
} else if (ModelUtils.isPasswordSchema(ps)) {
codegenParameter.isPassword = true;
} else if (ModelUtils.isUUIDSchema(ps)) {
codegenParameter.isUuid = true;
} else if (ModelUtils.isByteArraySchema(ps)) {
@@ -6802,7 +6865,6 @@ public class DefaultCodegen implements CodegenConfig {
if (ModelUtils.isShortSchema(ps)) { // int32/short format
codegenParameter.isShort = true;
} else { // unbounded integer
;
}
}
} else if (ModelUtils.isTypeObjectSchema(ps)) {
@@ -6810,10 +6872,8 @@ public class DefaultCodegen implements CodegenConfig {
codegenParameter.isFreeFormObject = true;
}
} else if (ModelUtils.isNullType(ps)) {
;
} else if (ModelUtils.isAnyType(ps)) {
// any schema with no type set, composed schemas often do this
;
} else if (ModelUtils.isArraySchema(ps)) {
Schema inner = getSchemaItems((ArraySchema) ps);
CodegenProperty arrayInnerProperty = fromProperty("inner", inner, false);
@@ -6854,7 +6914,6 @@ public class DefaultCodegen implements CodegenConfig {
}
} else {
// referenced schemas
;
}
if (Boolean.TRUE.equals(codegenProperty.isModel)) {
@@ -7758,9 +7817,9 @@ public class DefaultCodegen implements CodegenConfig {
return exceptions;
}
private String name;
private String removeCharRegEx;
private List<String> exceptions;
private final String name;
private final String removeCharRegEx;
private final List<String> exceptions;
@Override
public boolean equals(Object o) {
@@ -7932,7 +7991,7 @@ public class DefaultCodegen implements CodegenConfig {
}
private CodegenComposedSchemas getComposedSchemas(Schema schema) {
if (!(schema instanceof ComposedSchema) && schema.getNot()==null) {
if (!(schema instanceof ComposedSchema) && schema.getNot() == null) {
return null;
}
Schema notSchema = schema.getNot();

View File

@@ -820,6 +820,11 @@ public class DefaultGenerator implements Generator {
bundle.put("hasServers", true);
}
boolean hasOperationServers = allOperations != null && allOperations.stream()
.flatMap(om -> om.getOperations().getOperation().stream())
.anyMatch(o -> o.servers != null && !o.servers.isEmpty());
bundle.put("hasOperationServers", hasOperationServers);
if (openAPI.getExternalDocs() != null) {
bundle.put("externalDocs", openAPI.getExternalDocs());
}

View File

@@ -247,6 +247,8 @@ public interface IJsonSchemaValidationProperties {
;
} else if (ModelUtils.isEmailSchema(p)) {
;
} else if (ModelUtils.isPasswordSchema(p)) {
;
} else if (ModelUtils.isDateSchema(p)) {
;
} else if (ModelUtils.isDateTimeSchema(p)) {

View File

@@ -224,7 +224,7 @@ public class InlineModelResolver {
}
if (m.getAllOf() != null && !m.getAllOf().isEmpty()) {
// check to ensure at least of the allOf item is model
// check to ensure at least one of the allOf item is model
for (Schema inner : m.getAllOf()) {
if (isModelNeeded(ModelUtils.getReferencedSchema(openAPI, inner), visitedSchemas)) {
return true;
@@ -385,6 +385,7 @@ public class InlineModelResolver {
}
}
m.setAnyOf(newAnyOf);
}
if (m.getOneOf() != null) {
List<Schema> newOneOf = new ArrayList<Schema>();
@@ -541,15 +542,15 @@ public class InlineModelResolver {
* allOf:
* - $ref: '#/components/schemas/Animal'
* - type: object
* properties:
* name:
* type: string
* age:
* type: string
* properties:
* name:
* type: string
* age:
* type: string
* - type: object
* properties:
* breed:
* type: string
* properties:
* breed:
* type: string
*
* @param key a unique name ofr the composed schema.
* @param children the list of nested schemas within a composed schema (allOf, anyOf, oneOf).
@@ -577,6 +578,8 @@ public class InlineModelResolver {
// instead of inline.
String innerModelName = resolveModelName(component.getTitle(), key);
Schema innerModel = modelFromProperty(openAPI, component, innerModelName);
// Recurse to create $refs for inner models
gatherInlineModels(innerModel, innerModelName);
String existing = matchGenerated(innerModel);
if (existing == null) {
innerModelName = addSchemas(innerModelName, innerModel);
@@ -604,13 +607,17 @@ public class InlineModelResolver {
List<String> modelNames = new ArrayList<String>(models.keySet());
for (String modelName : modelNames) {
Schema model = models.get(modelName);
if (ModelUtils.isComposedSchema(model)) {
if (ModelUtils.isAnyOf(model)) { // contains anyOf only
gatherInlineModels(model, modelName);
} else if (ModelUtils.isOneOf(model)) { // contains oneOf only
gatherInlineModels(model, modelName);
} else if (ModelUtils.isComposedSchema(model)) {
ComposedSchema m = (ComposedSchema) model;
// inline child schemas
flattenComposedChildren(modelName + "_allOf", m.getAllOf());
flattenComposedChildren(modelName + "_anyOf", m.getAnyOf());
flattenComposedChildren(modelName + "_oneOf", m.getOneOf());
} else if (model instanceof Schema) {
} else {
gatherInlineModels(model, modelName);
}
}

View File

@@ -39,7 +39,7 @@ public class OpenAPINormalizer {
final Logger LOGGER = LoggerFactory.getLogger(OpenAPINormalizer.class);
// ============= a list of rules =============
// when set to true, all rules are enabled
// when set to true, all rules (true or false) are enabled
final String ALL = "ALL";
boolean enableAll;
@@ -63,6 +63,25 @@ public class OpenAPINormalizer {
final String SIMPLIFY_ANYOF_STRING_AND_ENUM_STRING = "SIMPLIFY_ANYOF_STRING_AND_ENUM_STRING";
boolean simplifyAnyOfStringAndEnumString;
// when set to true, oneOf/anyOf schema with only one sub-schema is simplified to just the sub-schema
// and if sub-schema contains "null", remove it and set nullable to true instead
// and if sub-schema contains enum of "null", remove it and set nullable to true instead
final String SIMPLIFY_ONEOF_ANYOF = "SIMPLIFY_ONEOF_ANYOF";
boolean simplifyOneOfAnyOf;
// when set to true, boolean enum will be converted to just boolean
final String SIMPLIFY_BOOLEAN_ENUM = "SIMPLIFY_BOOLEAN_ENUM";
boolean simplifyBooleanEnum;
// when set to a string value, tags in all operations will be reset to the string value provided
final String SET_TAGS_FOR_ALL_OPERATIONS = "SET_TAGS_FOR_ALL_OPERATIONS";
String setTagsForAllOperations;
// when set to true, auto fix integer with maximum value 4294967295 (2^32-1) or long with 18446744073709551615 (2^64-1)
// by adding x-unsigned to the schema
final String ADD_UNSIGNED_TO_INTEGER_WITH_INVALID_MAX_VALUE = "ADD_UNSIGNED_TO_INTEGER_WITH_INVALID_MAX_VALUE";
boolean addUnsignedToIntegerWithInvalidMaxValue;
// ============= end of rules =============
/**
@@ -106,6 +125,22 @@ public class OpenAPINormalizer {
if (enableAll || "true".equalsIgnoreCase(rules.get(SIMPLIFY_ANYOF_STRING_AND_ENUM_STRING))) {
simplifyAnyOfStringAndEnumString = true;
}
if (enableAll || "true".equalsIgnoreCase(rules.get(SIMPLIFY_ONEOF_ANYOF))) {
simplifyOneOfAnyOf = true;
}
if (enableAll || "true".equalsIgnoreCase(rules.get(SIMPLIFY_BOOLEAN_ENUM))) {
simplifyBooleanEnum = true;
}
if (StringUtils.isNotEmpty(rules.get(SET_TAGS_FOR_ALL_OPERATIONS))) {
setTagsForAllOperations = rules.get(SET_TAGS_FOR_ALL_OPERATIONS);
}
if (enableAll || "true".equalsIgnoreCase(rules.get(ADD_UNSIGNED_TO_INTEGER_WITH_INVALID_MAX_VALUE))) {
addUnsignedToIntegerWithInvalidMaxValue = true;
}
}
/**
@@ -169,6 +204,8 @@ public class OpenAPINormalizer {
*/
private void normalizeOperation(Operation operation) {
processKeepOnlyFirstTagInOperation(operation);
processSetTagsForAllOperations(operation);
}
/**
@@ -301,11 +338,17 @@ public class OpenAPINormalizer {
visitedSchemas.add(schema);
}
if (schema instanceof ArraySchema) {
if (schema instanceof ArraySchema) { // array
normalizeSchema(schema.getItems(), visitedSchemas);
} else if (schema.getAdditionalProperties() instanceof Schema) { // map
normalizeSchema((Schema) schema.getAdditionalProperties(), visitedSchemas);
} else if (ModelUtils.isComposedSchema(schema)) {
} else if (ModelUtils.isOneOf(schema)) { // oneOf
return normalizeOneOf(schema, visitedSchemas);
} else if (ModelUtils.isAnyOf(schema)) { // anyOf
return normalizeAnyOf(schema, visitedSchemas);
} else if (ModelUtils.isAllOf(schema)) { // allOf
return normalizeAllOf(schema, visitedSchemas);
} else if (ModelUtils.isComposedSchema(schema)) { // composed schema
ComposedSchema cs = (ComposedSchema) schema;
if (ModelUtils.isComplexComposedSchema(cs)) {
@@ -333,10 +376,12 @@ public class OpenAPINormalizer {
}
return cs;
} else if (schema.getNot() != null) {// not schema
normalizeSchema(schema.getNot(), visitedSchemas);
} else if (schema.getProperties() != null && !schema.getProperties().isEmpty()) {
normalizeProperties(schema.getProperties(), visitedSchemas);
} else if (schema instanceof BooleanSchema) {
normalizeBooleanSchema(schema, visitedSchemas);
} else if (schema instanceof IntegerSchema) {
normalizeIntegerSchema(schema, visitedSchemas);
} else if (schema instanceof Schema) {
normalizeSchemaWithOnlyProperties(schema, visitedSchemas);
} else {
@@ -346,6 +391,14 @@ public class OpenAPINormalizer {
return schema;
}
private void normalizeBooleanSchema(Schema schema, Set<Schema> visitedSchemas) {
processSimplifyBooleanEnum(schema);
}
private void normalizeIntegerSchema(Schema schema, Set<Schema> visitedSchemas) {
processAddUnsignedToIntegerWithInvalidMaxValue(schema);
}
private void normalizeSchemaWithOnlyProperties(Schema schema, Set<Schema> visitedSchemas) {
// normalize non-composed schema (e.g. schema with only properties)
}
@@ -376,33 +429,46 @@ public class OpenAPINormalizer {
private Schema normalizeOneOf(Schema schema, Set<Schema> visitedSchemas) {
for (Object item : schema.getOneOf()) {
if (item == null) {
continue;
}
if (!(item instanceof Schema)) {
throw new RuntimeException("Error! allOf schema is not of the type Schema: " + item);
throw new RuntimeException("Error! oneOf schema is not of the type Schema: " + item);
}
// normalize oenOf sub schemas one by one
normalizeSchema((Schema) item, visitedSchemas);
}
// process rules here
schema = processSimplifyOneOf(schema);
return schema;
}
private Schema normalizeAnyOf(Schema schema, Set<Schema> visitedSchemas) {
for (Object item : schema.getAnyOf()) {
if (item == null) {
continue;
}
if (!(item instanceof Schema)) {
throw new RuntimeException("Error! allOf schema is not of the type Schema: " + item);
throw new RuntimeException("Error! anyOf schema is not of the type Schema: " + item);
}
// normalize anyOf sub schemas one by one
normalizeSchema((Schema) item, visitedSchemas);
}
// process rules here
schema = processSimplifyAnyOf(schema);
// last rule to process as the schema may become String schema (not "anyOf") after the completion
return processSimplifyAnyOfStringAndEnumString(schema);
}
private Schema normalizeComplexComposedSchema(Schema schema, Set<Schema> visitedSchemas) {
// loop through properties, if any
if (schema.getProperties() != null && !schema.getProperties().isEmpty()) {
normalizeProperties(schema.getProperties(), visitedSchemas);
}
processRemoveAnyOfOneOfAndKeepPropertiesOnly(schema);
@@ -469,6 +535,20 @@ public class OpenAPINormalizer {
}
}
/**
* Set the tag name for all operations
*
* @param operation Operation
*/
private void processSetTagsForAllOperations(Operation operation) {
if (StringUtils.isEmpty(setTagsForAllOperations)) {
return;
}
operation.setTags(null);
operation.addTagsItem(setTagsForAllOperations);
}
/**
* If the schema contains anyOf/oneOf and properties, remove oneOf/anyOf as these serve as rules to
* ensure inter-dependency between properties. It's a workaround as such validation is not supported at the moment.
@@ -476,7 +556,6 @@ public class OpenAPINormalizer {
* @param schema Schema
*/
private void processRemoveAnyOfOneOfAndKeepPropertiesOnly(Schema schema) {
if (!removeAnyOfOneOfAndKeepPropertiesOnly && !enableAll) {
return;
}
@@ -493,7 +572,7 @@ public class OpenAPINormalizer {
/**
* If the schema is anyOf and the sub-schemas are either string or enum of string,
* then simply it to just string as many generators do not yet support anyOf.
* then simplify it to just string as many generators do not yet support anyOf.
*
* @param schema Schema
* @return Schema
@@ -503,7 +582,12 @@ public class OpenAPINormalizer {
return schema;
}
Schema s0 = null, s1 = null;
if (schema.getAnyOf() == null) {
// ComposedSchema, Schema with `type: null`
return schema;
}
Schema result = null, s0 = null, s1 = null;
if (schema.getAnyOf().size() == 2) {
s0 = ModelUtils.unaliasSchema(openAPI, (Schema) schema.getAnyOf().get(0));
s1 = ModelUtils.unaliasSchema(openAPI, (Schema) schema.getAnyOf().get(1));
@@ -517,15 +601,162 @@ public class OpenAPINormalizer {
// find the string schema (not enum)
if (s0 instanceof StringSchema && s1 instanceof StringSchema) {
if (((StringSchema) s0).getEnum() != null) { // s0 is enum, s1 is string
return (StringSchema) s1;
result = (StringSchema) s1;
} else if (((StringSchema) s1).getEnum() != null) { // s1 is enum, s0 is string
return (StringSchema) s0;
result = (StringSchema) s0;
} else { // both are string
return schema;
result = schema;
}
} else {
result = schema;
}
// set nullable
if (schema.getNullable() != null) {
result.setNullable(schema.getNullable());
}
// set default
if (schema.getDefault() != null) {
result.setDefault(schema.getDefault());
}
return result;
}
/**
* If the schema is oneOf and the sub-schemas is null, set `nullable: true` instead.
* If there's only one sub-schema, simply return the sub-schema directly.
*
* @param schema Schema
* @return Schema
*/
private Schema processSimplifyOneOf(Schema schema) {
if (!simplifyOneOfAnyOf && !enableAll) {
return schema;
}
if (schema.getOneOf() != null && !schema.getOneOf().isEmpty()) {
for (int i = 0; i < schema.getOneOf().size(); i++) {
// convert null sub-schema to `nullable: true`
if (schema.getOneOf().get(i) == null || ((Schema) schema.getOneOf().get(i)).getType() == null) {
schema.getOneOf().remove(i);
schema.setNullable(true);
continue;
}
// convert enum of null only to `nullable:true`
Schema oneOfElement = ModelUtils.getReferencedSchema(openAPI, (Schema) schema.getOneOf().get(i));
if (oneOfElement.getEnum() != null && oneOfElement.getEnum().size() == 1) {
if ("null".equals(String.valueOf(oneOfElement.getEnum().get(0)))) {
schema.setNullable(true);
schema.getOneOf().remove(i);
continue;
}
}
}
// if only one element left, simplify to just the element (schema)
if (schema.getOneOf().size() == 1) {
if (schema.getNullable()) { // retain nullable setting
((Schema) schema.getOneOf().get(0)).setNullable(true);
}
return (Schema) schema.getOneOf().get(0);
}
}
return schema;
}
/**
* If the schema is anyOf and the sub-schemas is null, set `nullable: true` instead.
* If there's only one sub-schema, simply return the sub-schema directly.
*
* @param schema Schema
* @return Schema
*/
private Schema processSimplifyAnyOf(Schema schema) {
if (!simplifyOneOfAnyOf && !enableAll) {
return schema;
}
if (schema.getAnyOf() != null && !schema.getAnyOf().isEmpty()) {
for (int i = 0; i < schema.getAnyOf().size(); i++) {
// convert null sub-schema to `nullable: true`
if (schema.getAnyOf().get(i) == null || ((Schema) schema.getAnyOf().get(i)).getType() == null) {
schema.getAnyOf().remove(i);
schema.setNullable(true);
continue;
}
// convert enum of null only to `nullable:true`
Schema anyOfElement = ModelUtils.getReferencedSchema(openAPI, (Schema) schema.getAnyOf().get(i));
if (anyOfElement.getEnum() != null && anyOfElement.getEnum().size() == 1) {
if ("null".equals(String.valueOf(anyOfElement.getEnum().get(0)))) {
schema.setNullable(true);
schema.getAnyOf().remove(i);
continue;
}
}
}
// if only one element left, simplify to just the element (schema)
if (schema.getAnyOf().size() == 1) {
if (schema.getNullable()) { // retain nullable setting
((Schema) schema.getAnyOf().get(0)).setNullable(true);
}
return (Schema) schema.getAnyOf().get(0);
}
}
return schema;
}
/**
* If the schema is boolean and its enum is defined,
* then simply it to just boolean.
*
* @param schema Schema
* @return Schema
*/
private void processSimplifyBooleanEnum(Schema schema) {
if (!simplifyBooleanEnum && !enableAll) {
return;
}
if (schema instanceof BooleanSchema) {
BooleanSchema bs = (BooleanSchema) schema;
if (bs.getEnum() != null && !bs.getEnum().isEmpty()) { // enum defined
bs.setEnum(null);
}
}
}
/**
* If the schema is integer and the max value is invalid (out of bound)
* then add x-unsigned to use unsigned integer/long instead.
*
* @param schema Schema
* @return Schema
*/
private void processAddUnsignedToIntegerWithInvalidMaxValue(Schema schema) {
if (!addUnsignedToIntegerWithInvalidMaxValue && !enableAll) {
return;
}
if (schema instanceof IntegerSchema) {
if (ModelUtils.isLongSchema(schema)) {
if ("18446744073709551615".equals(String.valueOf(schema.getMaximum())) &&
"0".equals(String.valueOf(schema.getMinimum()))) {
schema.addExtension("x-unsigned", true);
}
} else {
if ("4294967295".equals(String.valueOf(schema.getMaximum())) &&
"0".equals(String.valueOf(schema.getMinimum()))) {
schema.addExtension("x-unsigned", true);
}
}
}
}
// ===================== end of rules =====================

View File

@@ -15,6 +15,7 @@ public enum VendorExtension {
X_CONTENT_TYPE("x-content-type", ExtensionLevel.OPERATION, "Specify custom value for 'Content-Type' header for operation", null),
X_CLASS_EXTRA_ANNOTATION("x-class-extra-annotation", ExtensionLevel.MODEL, "List of custom annotations to be added to model", null),
X_FIELD_EXTRA_ANNOTATION("x-field-extra-annotation", ExtensionLevel.FIELD, "List of custom annotations to be added to property", null),
X_VERSION_PARAM("x-version-param", ExtensionLevel.OPERATION_PARAMETER, "Marker property that tells that this parameter would be used for endpoint versioning. Applicable for headers & query params. true/false", null),
;
private final String name;
@@ -52,7 +53,8 @@ public enum VendorExtension {
public enum ExtensionLevel {
FIELD,
MODEL,
OPERATION
OPERATION,
OPERATION_PARAMETER
}
}

View File

@@ -14,6 +14,7 @@ import java.util.Locale;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -120,8 +121,8 @@ public class MergedSpecBuilder {
private List<String> getAllSpecFilesInDirectory() {
Path rootDirectory = new File(inputSpecRootDirectory).toPath();
try {
return Files.walk(rootDirectory)
try (Stream<Path> pathStream = Files.walk(rootDirectory)) {
return pathStream
.filter(path -> !Files.isDirectory(path))
.map(path -> rootDirectory.relativize(path).toString())
.collect(Collectors.toList());

View File

@@ -70,6 +70,10 @@ public abstract class AbstractCSharpCodegen extends DefaultCodegen implements Co
protected String packageCompany = "OpenAPI";
protected String packageCopyright = "No Copyright";
protected String packageAuthors = "OpenAPI";
public static final String DATE_FORMAT = "dateFormat";
protected String dateFormat = "yyyy'-'MM'-'dd";
public static final String DATETIME_FORMAT = "dateTimeFormat";
protected String dateTimeFormat = "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffffK";
protected String interfacePrefix = "I";
protected String enumNameSuffix = "Enum";
@@ -160,8 +164,12 @@ public abstract class AbstractCSharpCodegen extends DefaultCodegen implements Co
"decimal",
"int?",
"int",
"uint",
"uint?",
"long?",
"long",
"ulong",
"ulong?",
"float?",
"float",
"byte[]",
@@ -197,8 +205,10 @@ public abstract class AbstractCSharpCodegen extends DefaultCodegen implements Co
typeMapping.put("ByteArray", "byte[]");
typeMapping.put("boolean", "bool?");
typeMapping.put("integer", "int?");
typeMapping.put("float", "float?");
typeMapping.put("UnsignedInteger", "uint?");
typeMapping.put("UnsignedLong", "ulong?");
typeMapping.put("long", "long?");
typeMapping.put("float", "float?");
typeMapping.put("double", "double?");
typeMapping.put("number", "decimal?");
typeMapping.put("BigDecimal", "decimal?");
@@ -215,11 +225,12 @@ public abstract class AbstractCSharpCodegen extends DefaultCodegen implements Co
// nullable type
nullableType = new HashSet<>(
Arrays.asList("decimal", "bool", "int", "float", "long", "double", "DateTime", "DateTimeOffset", "Guid")
Arrays.asList("decimal", "bool", "int", "uint", "long", "ulong", "float", "double",
"DateTime", "DateTimeOffset", "Guid")
);
// value Types
valueTypes = new HashSet<>(
Arrays.asList("decimal", "bool", "int", "float", "long", "double")
Arrays.asList("decimal", "bool", "int", "uint", "long", "ulong", "float", "double")
);
this.setSortParamsByRequiredFlag(true);
@@ -326,6 +337,20 @@ public abstract class AbstractCSharpCodegen extends DefaultCodegen implements Co
additionalProperties.put(CodegenConstants.PACKAGE_PRODUCTNAME, packageProductName);
}
// {{dateFormat}}
if (additionalProperties.containsKey(DATE_FORMAT)) {
setDateFormat((String) additionalProperties.get(DATE_FORMAT));
} else {
additionalProperties.put(DATE_FORMAT, this.dateFormat);
}
// {{dateTimeFormat}}
if (additionalProperties.containsKey(DATETIME_FORMAT)) {
setDateTimeFormat((String) additionalProperties.get(DATETIME_FORMAT));
} else {
additionalProperties.put(DATETIME_FORMAT, this.dateTimeFormat);
}
// {{packageDescription}}
if (additionalProperties.containsKey(CodegenConstants.PACKAGE_DESCRIPTION)) {
setPackageDescription((String) additionalProperties.get(CodegenConstants.PACKAGE_DESCRIPTION));
@@ -535,6 +560,11 @@ public abstract class AbstractCSharpCodegen extends DefaultCodegen implements Co
property.datatypeWithEnum = property.datatypeWithEnum.replace("Dictionary>", property.items.datatypeWithEnum + ">");
property.dataType = property.datatypeWithEnum;
}
// HOTFIX: https://github.com/OpenAPITools/openapi-generator/issues/14944
if (property.datatypeWithEnum.equals("decimal")) {
property.isDecimal = true;
}
}
/** Mitigates https://github.com/OpenAPITools/openapi-generator/issues/13709 */
@@ -1262,6 +1292,14 @@ public abstract class AbstractCSharpCodegen extends DefaultCodegen implements Co
this.packageProductName = packageProductName;
}
public void setDateFormat(String dateFormat) {
this.dateFormat = dateFormat;
}
public void setDateTimeFormat(String dateTimeFormat) {
this.dateTimeFormat = dateTimeFormat;
}
public void setPackageDescription(String packageDescription) {
this.packageDescription = packageDescription;
}
@@ -1334,7 +1372,9 @@ public abstract class AbstractCSharpCodegen extends DefaultCodegen implements Co
// Per: https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/enum
// The approved types for an enum are byte, sbyte, short, ushort, int, uint, long, or ulong.
// but we're not supporting unsigned integral types or shorts.
if (datatype.startsWith("int") || datatype.startsWith("long") || datatype.startsWith("byte")) {
if (datatype.startsWith("int") || datatype.startsWith("uint") ||
datatype.startsWith("long") || datatype.startsWith("ulong") ||
datatype.startsWith("byte")) {
return value;
}

View File

@@ -1051,7 +1051,8 @@ public abstract class AbstractJavaCodegen extends DefaultCodegen implements Code
schema = ModelUtils.getReferencedSchema(this.openAPI, schema);
if (ModelUtils.isArraySchema(schema)) {
if (schema.getDefault() == null) {
if (cp.isNullable || containerDefaultToNull) { // nullable or containerDefaultToNull set to true
// nullable, optional or containerDefaultToNull set to true
if (cp.isNullable || !cp.required || containerDefaultToNull) {
return null;
} else {
if (ModelUtils.isSet(schema)) {

View File

@@ -125,7 +125,6 @@ public abstract class AbstractPythonCodegen extends DefaultCodegen implements Co
}
/**
* Return the default value of the property
*
@@ -285,7 +284,7 @@ public abstract class AbstractPythonCodegen extends DefaultCodegen implements Co
}
private String toExampleValueRecursive(Schema schema, List<Schema> includedSchemas, int indentation) {
boolean cycleFound = includedSchemas.stream().filter(s->schema.equals(s)).count() > 1;
boolean cycleFound = includedSchemas.stream().filter(s -> schema.equals(s)).count() > 1;
if (cycleFound) {
return "";
}
@@ -716,5 +715,7 @@ public abstract class AbstractPythonCodegen extends DefaultCodegen implements Co
}
@Override
public GeneratorLanguage generatorLanguage() { return GeneratorLanguage.PYTHON; }
public GeneratorLanguage generatorLanguage() {
return GeneratorLanguage.PYTHON;
}
}

View File

@@ -123,8 +123,10 @@ public class CSharpClientCodegen extends AbstractCSharpCodegen {
typeMapping.put("boolean", "bool");
typeMapping.put("integer", "int");
typeMapping.put("float", "float");
typeMapping.put("long", "long");
typeMapping.put("UnsignedInteger", "uint");
typeMapping.put("UnsignedLong", "ulong");
typeMapping.put("float", "float");
typeMapping.put("double", "double");
typeMapping.put("number", "decimal");
typeMapping.put("decimal", "decimal");
@@ -789,7 +791,8 @@ public class CSharpClientCodegen extends AbstractCSharpCodegen {
}
// number
if (datatype.startsWith("int") || datatype.startsWith("long") ||
if (datatype.startsWith("int") || datatype.startsWith("uint") ||
datatype.startsWith("ulong") || datatype.startsWith("long") ||
datatype.startsWith("double") || datatype.startsWith("float")) {
String varName = "NUMBER_" + value;
varName = varName.replaceAll("-", "MINUS_");

View File

@@ -1,160 +0,0 @@
/*
* Copyright 2018 OpenAPI-Generator Contributors (https://openapi-generator.tech)
* Copyright 2018 SmartBear Software
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.openapitools.codegen.languages;
import org.openapitools.codegen.CliOption;
import org.openapitools.codegen.CodegenConstants;
import org.openapitools.codegen.CodegenType;
import org.openapitools.codegen.SupportingFile;
import org.openapitools.codegen.meta.GeneratorMetadata;
import org.openapitools.codegen.meta.Stability;
import org.openapitools.codegen.meta.features.DocumentationFeature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
public class CSharpDotNet2ClientCodegen extends AbstractCSharpCodegen {
private final Logger LOGGER = LoggerFactory.getLogger(CSharpDotNet2ClientCodegen.class);
public static final String CLIENT_PACKAGE = "clientPackage";
protected String clientPackage = "Org.OpenAPITools.Client";
protected String apiDocPath = "docs/";
protected String modelDocPath = "docs/";
public CSharpDotNet2ClientCodegen() {
super();
modifyFeatureSet(features -> features.includeDocumentationFeatures(DocumentationFeature.Readme));
generatorMetadata = GeneratorMetadata.newBuilder(generatorMetadata)
.stability(Stability.DEPRECATED)
.build();
// clear import mapping (from default generator) as C# (2.0) does not use it
// at the moment
importMapping.clear();
modelTemplateFiles.put("model.mustache", ".cs");
apiTemplateFiles.put("api.mustache", ".cs");
setApiPackage(packageName + ".Api");
setModelPackage(packageName + ".Model");
setClientPackage(packageName + ".Client");
setSourceFolder("src" + File.separator + "main" + File.separator + "CsharpDotNet2");
modelDocTemplateFiles.put("model_doc.mustache", ".md");
apiDocTemplateFiles.put("api_doc.mustache", ".md");
cliOptions.clear();
cliOptions.add(new CliOption(CodegenConstants.PACKAGE_NAME,
"C# package name (convention: Camel.Case).")
.defaultValue(packageName));
cliOptions.add(new CliOption(CodegenConstants.PACKAGE_VERSION,
"C# package version.")
.defaultValue(packageVersion));
cliOptions.add(new CliOption(CLIENT_PACKAGE,
"C# client package name (convention: Camel.Case).")
.defaultValue(clientPackage));
}
@Override
public void processOpts() {
LOGGER.warn("Per Microsoft Product Lifecycle (https://support.microsoft.com/en-us/lifecycle/search?sort=PN&alpha=.NET%20Framework&Filter=FilterNO), support for .NET Framework 2.0 ended in 2011 so there may be security issues using the auto-generated C# 2.0 source code.");
super.processOpts();
if (additionalProperties.containsKey(CLIENT_PACKAGE)) {
setClientPackage((String) additionalProperties.get(CLIENT_PACKAGE));
} else {
additionalProperties.put(CLIENT_PACKAGE, getClientPackage());
}
final String clientPackage = getClientPackage();
final String clientPackagePath = clientPackage.replace(".", java.io.File.separator);
additionalProperties.put("apiDocPath", apiDocPath);
additionalProperties.put("modelDocPath", modelDocPath);
supportingFiles.add(new SupportingFile("Configuration.mustache",
sourceFolder + File.separator + clientPackagePath, "Configuration.cs"));
supportingFiles.add(new SupportingFile("ApiClient.mustache",
sourceFolder + File.separator + clientPackagePath, "ApiClient.cs"));
supportingFiles.add(new SupportingFile("ApiException.mustache",
sourceFolder + File.separator + clientPackagePath, "ApiException.cs"));
supportingFiles.add(new SupportingFile("packages.config.mustache", "vendor", "packages.config"));
supportingFiles.add(new SupportingFile("compile-mono.sh.mustache", "", "compile-mono.sh"));
supportingFiles.add(new SupportingFile("README.mustache", "", "README.md"));
supportingFiles.add(new SupportingFile("gitignore", "", ".gitignore"));
}
@Override
public String apiPackage() {
return packageName + ".Api";
}
@Override
public String modelPackage() {
return packageName + ".Model";
}
public String getClientPackage() {
return clientPackage;
}
public void setClientPackage(String clientPackage) {
this.clientPackage = clientPackage;
}
@Override
public CodegenType getTag() {
return CodegenType.CLIENT;
}
@Override
public String getName() {
return "csharp-dotnet2";
}
@Override
public String getHelp() {
return "Generates a C# .Net 2.0 client library (beta).";
}
@Override
public String apiFileFolder() {
return outputFolder + File.separator + sourceFolder + File.separator + apiPackage().replace('.', File.separatorChar);
}
@Override
public String modelFileFolder() {
return outputFolder + File.separator + sourceFolder + File.separator + modelPackage().replace('.', File.separatorChar);
}
@Override
public String apiDocFileFolder() {
return outputFolder + File.separator + apiDocPath.replace('/', File.separatorChar);
}
@Override
public String modelDocFileFolder() {
return outputFolder + File.separator + modelDocPath.replace('/', File.separatorChar);
}
}

View File

@@ -61,6 +61,7 @@ public class CSharpNetCoreClientCodegen extends AbstractCSharpCodegen {
protected static final String RESTSHARP = "restsharp";
protected static final String HTTPCLIENT = "httpclient";
protected static final String GENERICHOST = "generichost";
protected static final String UNITY_WEB_REQUEST = "unityWebRequest";
// Project Variable, determined from target framework. Not intended to be user-settable.
protected static final String TARGET_FRAMEWORK_IDENTIFIER = "targetFrameworkIdentifier";
@@ -100,6 +101,7 @@ public class CSharpNetCoreClientCodegen extends AbstractCSharpCodegen {
protected boolean supportsRetry = Boolean.TRUE;
protected boolean supportsAsync = Boolean.TRUE;
protected boolean netStandard = Boolean.FALSE;
protected boolean supportsFileParameters = Boolean.TRUE;
protected boolean validatable = Boolean.TRUE;
protected Map<Character, String> regexModifiers;
@@ -151,8 +153,10 @@ public class CSharpNetCoreClientCodegen extends AbstractCSharpCodegen {
typeMapping.put("ByteArray", "byte[]");
typeMapping.put("boolean", "bool");
typeMapping.put("integer", "int");
typeMapping.put("float", "float");
typeMapping.put("long", "long");
typeMapping.put("UnsignedInteger", "uint");
typeMapping.put("UnsignedLong", "ulong");
typeMapping.put("float", "float");
typeMapping.put("double", "double");
typeMapping.put("number", "decimal");
typeMapping.put("decimal", "decimal");
@@ -215,6 +219,14 @@ public class CSharpNetCoreClientCodegen extends AbstractCSharpCodegen {
CodegenConstants.PACKAGE_TAGS_DESC,
this.packageTags);
addOption(DATE_FORMAT,
"The default Date format (only `generichost` library supports this option).",
this.dateFormat);
addOption(DATETIME_FORMAT,
"The default DateTime format (only `generichost` library supports this option).",
this.dateTimeFormat);
CliOption framework = new CliOption(
CodegenConstants.DOTNET_FRAMEWORK,
CodegenConstants.DOTNET_FRAMEWORK_DESC
@@ -325,6 +337,8 @@ public class CSharpNetCoreClientCodegen extends AbstractCSharpCodegen {
+ "(Experimental. Subject to breaking changes without notice.)");
supportedLibraries.put(HTTPCLIENT, "HttpClient (https://docs.microsoft.com/en-us/dotnet/api/system.net.http.httpclient) "
+ "(Experimental. Subject to breaking changes without notice.)");
supportedLibraries.put(UNITY_WEB_REQUEST, "UnityWebRequest (...) "
+ "(Experimental. Subject to breaking changes without notice.)");
supportedLibraries.put(RESTSHARP, "RestSharp (https://github.com/restsharp/RestSharp)");
CliOption libraryOption = new CliOption(CodegenConstants.LIBRARY, "HTTP library template (sub-template) to use");
@@ -701,6 +715,10 @@ public class CSharpNetCoreClientCodegen extends AbstractCSharpCodegen {
setLibrary(HTTPCLIENT);
additionalProperties.put("useHttpClient", true);
needsUriBuilder = true;
} else if (UNITY_WEB_REQUEST.equals(getLibrary())) {
setLibrary(UNITY_WEB_REQUEST);
additionalProperties.put("useUnityWebRequest", true);
needsUriBuilder = true;
} else {
throw new RuntimeException("Invalid HTTP library " + getLibrary() + ". Only restsharp, httpclient, and generichost are supported.");
}
@@ -780,6 +798,7 @@ public class CSharpNetCoreClientCodegen extends AbstractCSharpCodegen {
syncBooleanProperty(additionalProperties, CodegenConstants.OPTIONAL_METHOD_ARGUMENT, this::setOptionalMethodArgumentFlag, optionalMethodArgumentFlag);
syncBooleanProperty(additionalProperties, CodegenConstants.NON_PUBLIC_API, this::setNonPublicApi, isNonPublicApi());
syncBooleanProperty(additionalProperties, CodegenConstants.USE_ONEOF_DISCRIMINATOR_LOOKUP, this::setUseOneOfDiscriminatorLookup, this.useOneOfDiscriminatorLookup);
syncBooleanProperty(additionalProperties, "supportsFileParameters", this::setSupportsFileParameters, this.supportsFileParameters);
final String testPackageName = testPackageName();
String packageFolder = sourceFolder + File.separator + packageName;
@@ -816,6 +835,20 @@ public class CSharpNetCoreClientCodegen extends AbstractCSharpCodegen {
addGenericHostSupportingFiles(clientPackageDir, packageFolder, excludeTests, testPackageFolder, testPackageName, modelPackageDir);
additionalProperties.put("apiDocPath", apiDocPath + File.separatorChar + "apis");
additionalProperties.put("modelDocPath", modelDocPath + File.separatorChar + "models");
} else if (UNITY_WEB_REQUEST.equals(getLibrary())) {
additionalProperties.put(CodegenConstants.VALIDATABLE, false);
setValidatable(false);
setSupportsRetry(false);
setSupportsAsync(true);
// Some consoles and tvOS do not support either Application.persistentDataPath or will refuse to
// compile/link if you even reference GetTempPath as well.
additionalProperties.put("supportsFileParameters", false);
setSupportsFileParameters(false);
addSupportingFiles(clientPackageDir, packageFolder, excludeTests, testPackageFolder, testPackageName, modelPackageDir, authPackageDir);
supportingFiles.add(new SupportingFile("ConnectionException.mustache", clientPackageDir, "ConnectionException.cs"));
supportingFiles.add(new SupportingFile("UnexpectedResponseException.mustache", clientPackageDir, "UnexpectedResponseException.cs"));
} else { //restsharp
addSupportingFiles(clientPackageDir, packageFolder, excludeTests, testPackageFolder, testPackageName, modelPackageDir, authPackageDir);
additionalProperties.put("apiDocPath", apiDocPath);
@@ -911,14 +944,24 @@ public class CSharpNetCoreClientCodegen extends AbstractCSharpCodegen {
supportingFiles.add(new SupportingFile("git_push.sh.mustache", "", "git_push.sh"));
supportingFiles.add(new SupportingFile("gitignore.mustache", "", ".gitignore"));
supportingFiles.add(new SupportingFile("Solution.mustache", "", packageName + ".sln"));
supportingFiles.add(new SupportingFile("netcore_project.mustache", packageFolder, packageName + ".csproj"));
if (Boolean.FALSE.equals(excludeTests.get())) {
supportingFiles.add(new SupportingFile("netcore_testproject.mustache", testPackageFolder, testPackageName + ".csproj"));
if (UNITY_WEB_REQUEST.equals(getLibrary())) {
supportingFiles.add(new SupportingFile("asmdef.mustache", packageFolder, packageName + ".asmdef"));
} else {
supportingFiles.add(new SupportingFile("Solution.mustache", "", packageName + ".sln"));
supportingFiles.add(new SupportingFile("netcore_project.mustache", packageFolder, packageName + ".csproj"));
}
supportingFiles.add(new SupportingFile("appveyor.mustache", "", "appveyor.yml"));
if (Boolean.FALSE.equals(excludeTests.get())) {
if (UNITY_WEB_REQUEST.equals(getLibrary())) {
supportingFiles.add(new SupportingFile("asmdef_test.mustache", testPackageFolder, testPackageName + ".asmdef"));
} else {
supportingFiles.add(new SupportingFile("netcore_testproject.mustache", testPackageFolder, testPackageName + ".csproj"));
}
}
if (!UNITY_WEB_REQUEST.equals(getLibrary())) {
supportingFiles.add(new SupportingFile("appveyor.mustache", "", "appveyor.yml"));
}
supportingFiles.add(new SupportingFile("AbstractOpenAPISchema.mustache", modelPackageDir, "AbstractOpenAPISchema.cs"));
}
@@ -1048,6 +1091,10 @@ public class CSharpNetCoreClientCodegen extends AbstractCSharpCodegen {
this.supportsAsync = supportsAsync;
}
public void setSupportsFileParameters(Boolean supportsFileParameters) {
this.supportsFileParameters = supportsFileParameters;
}
public void setSupportsRetry(Boolean supportsRetry) {
this.supportsRetry = supportsRetry;
}
@@ -1139,7 +1186,8 @@ public class CSharpNetCoreClientCodegen extends AbstractCSharpCodegen {
}
// number
if (datatype.startsWith("int") || datatype.startsWith("long") ||
if (datatype.startsWith("int") || datatype.startsWith("uint") ||
datatype.startsWith("long") || datatype.startsWith("ulong") ||
datatype.startsWith("double") || datatype.startsWith("float")) {
String varName = "NUMBER_" + value;
varName = varName.replaceAll("-", "MINUS_");

View File

@@ -71,6 +71,7 @@ public class GoClientCodegen extends AbstractGoCodegen {
.wireFormatFeatures(EnumSet.of(WireFormatFeature.JSON, WireFormatFeature.XML))
.securityFeatures(EnumSet.of(
SecurityFeature.BasicAuth,
SecurityFeature.BearerToken,
SecurityFeature.ApiKey,
SecurityFeature.OAuth2_Implicit
))

View File

@@ -50,6 +50,8 @@ public class JavaJAXRSCXFCDIServerCodegen extends JavaJAXRSSpecServerCodegen imp
// Use standard types
typeMapping.put("DateTime", "java.util.Date");
typeMapping.put("binary", "java.io.InputStream");
typeMapping.put("file", "java.io.InputStream");
// Updated template directory
embeddedTemplateDir = templateDir = JAXRS_TEMPLATE_DIRECTORY_NAME + File.separator + "cxf-cdi";

View File

@@ -289,6 +289,7 @@ public class K6ClientCodegen extends DefaultCodegen implements CodegenConfig {
}
static class HTTPRequest {
String operationId;
String method;
boolean isDelete;
String path;
@@ -304,12 +305,13 @@ public class K6ClientCodegen extends DefaultCodegen implements CodegenConfig {
@Nullable
DataExtractSubstituteParameter dataExtract;
public HTTPRequest(String method, String path, @Nullable List<Parameter> query, @Nullable HTTPBody body,
public HTTPRequest(String operationId, String method, String path, @Nullable List<Parameter> query, @Nullable HTTPBody body,
boolean hasBodyExample, @Nullable HTTPParameters params, @Nullable List<k6Check> k6Checks,
DataExtractSubstituteParameter dataExtract) {
// NOTE: https://k6.io/docs/javascript-api/k6-http/del-url-body-params
this.method = method.equals("delete") ? "del" : method;
this.isDelete = method.equals("delete");
this.operationId = operationId;
this.path = path;
this.query = query;
this.body = body;
@@ -645,7 +647,7 @@ public class K6ClientCodegen extends DefaultCodegen implements CodegenConfig {
// calculate order for this current request
Integer requestOrder = calculateRequestOrder(operationGroupingOrder, requests.size());
requests.put(requestOrder, new HTTPRequest(method.toString().toLowerCase(Locale.ROOT), path,
requests.put(requestOrder, new HTTPRequest(operationId, method.toString().toLowerCase(Locale.ROOT), path,
queryParams.size() > 0 ? queryParams : null,
bodyOrFormParams.size() > 0 ? new HTTPBody(bodyOrFormParams) : null, hasRequestBodyExample,
params.headers.size() > 0 ? params : null, k6Checks.size() > 0 ? k6Checks : null,

View File

@@ -66,6 +66,7 @@ public class KotlinSpringServerCodegen extends AbstractKotlinCodegen
public static final String GRADLE_BUILD_FILE = "gradleBuildFile";
public static final String SERVICE_INTERFACE = "serviceInterface";
public static final String SERVICE_IMPLEMENTATION = "serviceImplementation";
public static final String SKIP_DEFAULT_INTERFACE = "skipDefaultInterface";
public static final String REACTIVE = "reactive";
public static final String INTERFACE_ONLY = "interfaceOnly";
public static final String DELEGATE_PATTERN = "delegatePattern";
@@ -79,6 +80,7 @@ public class KotlinSpringServerCodegen extends AbstractKotlinCodegen
private String serverPort = "8080";
private String title = "OpenAPI Kotlin Spring";
private boolean useBeanValidation = true;
private boolean skipDefaultInterface = false;
private boolean exceptionHandler = true;
private boolean gradleBuildFile = true;
private boolean useSwaggerUI = true;
@@ -153,6 +155,7 @@ public class KotlinSpringServerCodegen extends AbstractKotlinCodegen
addSwitch(SERVICE_IMPLEMENTATION, "generate stub service implementations that extends service " +
"interfaces. If this is set to true service interfaces will also be generated", serviceImplementation);
addSwitch(USE_BEANVALIDATION, "Use BeanValidation API annotations to validate data types", useBeanValidation);
addSwitch(SKIP_DEFAULT_INTERFACE, "Whether to skip generation of default implementations for interfaces", skipDefaultInterface);
addSwitch(REACTIVE, "use coroutines for reactive behavior", reactive);
addSwitch(INTERFACE_ONLY, "Whether to generate only API interface stubs without the server files.", interfaceOnly);
addSwitch(DELEGATE_PATTERN, "Whether to generate the server files using the delegate pattern", delegatePattern);
@@ -334,6 +337,10 @@ public class KotlinSpringServerCodegen extends AbstractKotlinCodegen
this.useBeanValidation = useBeanValidation;
}
public void setSkipDefaultInterface(boolean skipDefaultInterface) {
this.skipDefaultInterface = skipDefaultInterface;
}
public boolean isReactive() {
return reactive;
}
@@ -492,6 +499,11 @@ public class KotlinSpringServerCodegen extends AbstractKotlinCodegen
}
writePropertyBack(USE_BEANVALIDATION, useBeanValidation);
if (additionalProperties.containsKey(SKIP_DEFAULT_INTERFACE)) {
this.setSkipDefaultInterface(convertPropertyToBoolean(SKIP_DEFAULT_INTERFACE));
}
writePropertyBack(SKIP_DEFAULT_INTERFACE, skipDefaultInterface);
if (additionalProperties.containsKey(REACTIVE) && library.equals(SPRING_BOOT)) {
this.setReactive(convertPropertyToBoolean(REACTIVE));
// spring webflux doesn't support @ControllerAdvice

View File

@@ -38,6 +38,7 @@ import org.slf4j.LoggerFactory;
import java.io.File;
import java.util.*;
import static org.openapitools.codegen.utils.StringUtils.escape;
import static org.openapitools.codegen.utils.StringUtils.underscore;
public class PythonNextgenClientCodegen extends AbstractPythonCodegen implements CodegenConfig {
@@ -48,6 +49,8 @@ public class PythonNextgenClientCodegen extends AbstractPythonCodegen implements
public static final String RECURSION_LIMIT = "recursionLimit";
public static final String ALLOW_STRING_IN_DATETIME_PARAMETERS = "allowStringInDateTimeParameters";
public static final String FLOAT_STRICT_TYPE = "floatStrictType";
public static final String DATETIME_FORMAT = "datetimeFormat";
public static final String DATE_FORMAT = "dateFormat";
protected String packageUrl;
protected String apiDocPath = "docs" + File.separator;
@@ -56,6 +59,8 @@ public class PythonNextgenClientCodegen extends AbstractPythonCodegen implements
protected boolean useOneOfDiscriminatorLookup = false; // use oneOf discriminator's mapping for model lookup
protected boolean allowStringInDateTimeParameters = false; // use StrictStr instead of datetime in parameters
protected boolean floatStrictType = true;
protected String datetimeFormat = "%Y-%m-%dT%H:%M:%S.%f%z";
protected String dateFormat = "%Y-%m-%d";
protected Map<Character, String> regexModifiers;
@@ -171,6 +176,10 @@ public class PythonNextgenClientCodegen extends AbstractPythonCodegen implements
.defaultValue(Boolean.FALSE.toString()));
cliOptions.add(new CliOption(FLOAT_STRICT_TYPE, "Use strict type for float, i.e. StrictFloat or confloat(strict=true, ...)")
.defaultValue(Boolean.TRUE.toString()));
cliOptions.add(new CliOption(DATETIME_FORMAT, "datetime format for query parameters")
.defaultValue("%Y-%m-%dT%H:%M:%S%z"));
cliOptions.add(new CliOption(DATE_FORMAT, "date format for query parameters")
.defaultValue("%Y-%m-%d"));
supportedLibraries.put("urllib3", "urllib3-based client");
supportedLibraries.put("asyncio", "asyncio-based client");
@@ -200,6 +209,9 @@ public class PythonNextgenClientCodegen extends AbstractPythonCodegen implements
super.processOpts();
// map to Dot instead of Period
specialCharReplacements.put(".", "Dot");
if (StringUtils.isEmpty(System.getenv("PYTHON_POST_PROCESS_FILE"))) {
LOGGER.info("Environment variable PYTHON_POST_PROCESS_FILE not defined so the Python code may not be properly formatted. To define it, try 'export PYTHON_POST_PROCESS_FILE=\"/usr/local/bin/yapf -i\"' (Linux/Mac)");
LOGGER.info("NOTE: To enable file post-processing, 'enablePostProcessFile' must be set to `true` (--enable-post-process-file for CLI).");
@@ -274,6 +286,18 @@ public class PythonNextgenClientCodegen extends AbstractPythonCodegen implements
setFloatStrictType(convertPropertyToBooleanAndWriteBack(FLOAT_STRICT_TYPE));
}
if (additionalProperties.containsKey(DATETIME_FORMAT)) {
setDatetimeFormat((String) additionalProperties.get(DATETIME_FORMAT));
} else {
additionalProperties.put(DATETIME_FORMAT, datetimeFormat);
}
if (additionalProperties.containsKey(DATE_FORMAT)) {
setDateFormat((String) additionalProperties.get(DATE_FORMAT));
} else {
additionalProperties.put(DATE_FORMAT, dateFormat);
}
String modelPath = packagePath() + File.separatorChar + modelPackage.replace('.', File.separatorChar);
String apiPath = packagePath() + File.separatorChar + apiPackage.replace('.', File.separatorChar);
@@ -297,6 +321,7 @@ public class PythonNextgenClientCodegen extends AbstractPythonCodegen implements
supportingFiles.add(new SupportingFile("github-workflow.mustache", ".github/workflows", "python.yml"));
supportingFiles.add(new SupportingFile("gitlab-ci.mustache", "", ".gitlab-ci.yml"));
supportingFiles.add(new SupportingFile("setup.mustache", "", "setup.py"));
supportingFiles.add(new SupportingFile("pyproject.mustache", "", "pyproject.toml"));
}
supportingFiles.add(new SupportingFile("configuration.mustache", packagePath(), "configuration.py"));
supportingFiles.add(new SupportingFile("__init__package.mustache", packagePath(), "__init__.py"));
@@ -403,23 +428,20 @@ public class PythonNextgenClientCodegen extends AbstractPythonCodegen implements
}
if (cp.isArray) {
if (cp.maxItems != null || cp.minItems != null) {
String maxOrMinItems = "";
if (cp.maxItems != null) {
maxOrMinItems += String.format(Locale.ROOT, ", max_items=%d", cp.maxItems);
}
if (cp.minItems != null) {
maxOrMinItems += String.format(Locale.ROOT, ", min_items=%d", cp.minItems);
}
pydanticImports.add("conlist");
return String.format(Locale.ROOT, "conlist(%s%s)",
getPydanticType(cp.items, typingImports, pydanticImports, datetimeImports, modelImports),
maxOrMinItems);
} else {
typingImports.add("List");
return String.format(Locale.ROOT, "List[%s]", getPydanticType(cp.items, typingImports, pydanticImports, datetimeImports, modelImports));
String constraints = "";
if (cp.maxItems != null) {
constraints += String.format(Locale.ROOT, ", max_items=%d", cp.maxItems);
}
if (cp.minItems != null) {
constraints += String.format(Locale.ROOT, ", min_items=%d", cp.minItems);
}
if (cp.getUniqueItems()) {
constraints += ", unique_items=True";
}
pydanticImports.add("conlist");
return String.format(Locale.ROOT, "conlist(%s%s)",
getPydanticType(cp.items, typingImports, pydanticImports, datetimeImports, modelImports),
constraints);
} else if (cp.isMap) {
typingImports.add("Dict");
return String.format(Locale.ROOT, "Dict[str, %s]", getPydanticType(cp.items, typingImports, pydanticImports, datetimeImports, modelImports));
@@ -583,7 +605,7 @@ public class PythonNextgenClientCodegen extends AbstractPythonCodegen implements
if (allowStringInDateTimeParameters) {
pydanticImports.add("StrictStr");
typingImports.add("Union");
return String.format(Locale.ROOT, "Union[%s, StrictStr]", cp.dataType);
return String.format(Locale.ROOT, "Union[StrictStr, %s]", cp.dataType);
} else {
return cp.dataType;
}
@@ -653,22 +675,21 @@ public class PythonNextgenClientCodegen extends AbstractPythonCodegen implements
return String.format(Locale.ROOT, "%sEnum", cp.nameInCamelCase);
} else*/
if (cp.isArray) {
if (cp.maxItems != null || cp.minItems != null) {
String maxOrMinItems = "";
if (cp.maxItems != null) {
maxOrMinItems += String.format(Locale.ROOT, ", max_items=%d", cp.maxItems);
}
if (cp.minItems != null) {
maxOrMinItems += String.format(Locale.ROOT, ", min_items=%d", cp.minItems);
}
pydanticImports.add("conlist");
return String.format(Locale.ROOT, "conlist(%s%s)",
getPydanticType(cp.items, typingImports, pydanticImports, datetimeImports, modelImports),
maxOrMinItems);
} else {
typingImports.add("List");
return String.format(Locale.ROOT, "List[%s]", getPydanticType(cp.items, typingImports, pydanticImports, datetimeImports, modelImports));
String constraints = "";
if (cp.maxItems != null) {
constraints += String.format(Locale.ROOT, ", max_items=%d", cp.maxItems);
}
if (cp.minItems != null) {
constraints += String.format(Locale.ROOT, ", min_items=%d", cp.minItems);
}
if (cp.getUniqueItems()) {
constraints += ", unique_items=True";
}
pydanticImports.add("conlist");
typingImports.add("List"); // for return type
return String.format(Locale.ROOT, "conlist(%s%s)",
getPydanticType(cp.items, typingImports, pydanticImports, datetimeImports, modelImports),
constraints);
} else if (cp.isMap) {
typingImports.add("Dict");
return String.format(Locale.ROOT, "Dict[str, %s]", getPydanticType(cp.items, typingImports, pydanticImports, datetimeImports, modelImports));
@@ -884,10 +905,6 @@ public class PythonNextgenClientCodegen extends AbstractPythonCodegen implements
fields.add(String.format(Locale.ROOT, "description=\"%s\"", param.description));
}
if (param.isArray && param.getUniqueItems()) { // a set
fields.add("unique_items=True");
}
/* TODO support example
if (!StringUtils.isEmpty(cp.getExample())) { // has example
fields.add(String.format(Locale.ROOT, "example=%s", cp.getExample()));
@@ -1071,10 +1088,6 @@ public class PythonNextgenClientCodegen extends AbstractPythonCodegen implements
fields.add(String.format(Locale.ROOT, "description=\"%s\"", cp.description));
}
if (cp.isArray && cp.getUniqueItems()) { // a set
fields.add("unique_items=True");
}
/* TODO review as example may break the build
if (!StringUtils.isEmpty(cp.getExample())) { // has example
fields.add(String.format(Locale.ROOT, "example=%s", cp.getExample()));
@@ -1121,15 +1134,17 @@ public class PythonNextgenClientCodegen extends AbstractPythonCodegen implements
modelImports.add(model.parent);
}
// set enum type in extensions
// set enum type in extensions and update `name` in enumVars
if (model.isEnum) {
for (Map<String, Object> enumVars : (List<Map<String, Object>>) model.getAllowableValues().get("enumVars")) {
if ((Boolean) enumVars.get("isString")) {
model.vendorExtensions.put("x-py-enum-type", "str");
model.vendorExtensions.putIfAbsent("x-py-enum-type", "str");
// update `name`, e.g.
enumVars.put("name", toEnumVariableName((String) enumVars.get("value"), "str"));
} else {
model.vendorExtensions.put("x-py-enum-type", "int");
model.vendorExtensions.putIfAbsent("x-py-enum-type", "int");
enumVars.put("name", toEnumVariableName((String) enumVars.get("value"), "int"));
}
break;
}
}
@@ -1313,38 +1328,50 @@ public class PythonNextgenClientCodegen extends AbstractPythonCodegen implements
@Override
public String toEnumVarName(String name, String datatype) {
if ("int".equals(datatype) || "float".equals(datatype)) {
return name;
} else {
return "\'" + name + "\'";
}
}
public String toEnumVariableName(String name, String datatype) {
if ("int".equals(datatype)) {
return "NUMBER_" + name;
}
// remove quote e.g. 'abc' => abc
name = name.substring(1, name.length() - 1);
if (name.length() == 0) {
return "EMPTY";
}
if (name.trim().length() == 0) {
return "SPACE_" + name.length();
if (" ".equals(name)) {
return "SPACE";
}
// for symbol, e.g. $, #
if (getSymbolName(name) != null) {
return (getSymbolName(name)).toUpperCase(Locale.ROOT);
if ("_".equals(name)) {
return "UNDERSCORE";
}
// number
if ("int".equals(datatype) || "float".equals(datatype)) {
String varName = name;
varName = varName.replaceAll("-", "MINUS_");
varName = varName.replaceAll("\\+", "PLUS_");
varName = varName.replaceAll("\\.", "_DOT_");
return "NUMBER_" + varName;
}
// string
String enumName = sanitizeName(underscore(name).toUpperCase(Locale.ROOT));
enumName = enumName.replaceFirst("^_", "");
enumName = enumName.replaceFirst("_$", "");
if (isReservedWord(enumName) || enumName.matches("\\d.*")) { // reserved word or starts with number
return escapeReservedWord(enumName);
if (reservedWords.contains(name)) {
name = name.toUpperCase(Locale.ROOT);
} else if (((CharSequence) name).chars().anyMatch(character -> specialCharReplacements.keySet().contains(String.valueOf((char) character)))) {
name = underscore(escape(name, specialCharReplacements, Collections.singletonList("_"), "_")).toUpperCase(Locale.ROOT);
} else {
return enumName;
name = name.toUpperCase(Locale.ROOT);
}
name = name.replace(" ", "_");
name = name.replaceFirst("^_", "");
name = name.replaceFirst("_$", "");
if (name.matches("\\d.*")) {
name = "ENUM_" + name.toUpperCase(Locale.ROOT);
}
return name;
}
@Override
@@ -1358,7 +1385,7 @@ public class PythonNextgenClientCodegen extends AbstractPythonCodegen implements
@Override
public String toEnumDefaultValue(String value, String datatype) {
return "self::" + datatype + "_" + value;
return value;
}
/**
@@ -1389,4 +1416,18 @@ public class PythonNextgenClientCodegen extends AbstractPythonCodegen implements
public void setFloatStrictType(boolean floatStrictType) {
this.floatStrictType = floatStrictType;
}
public void setDatetimeFormat(String datetimeFormat) {
this.datetimeFormat = datetimeFormat;
}
public void setDateFormat(String dateFormat) {
this.dateFormat = dateFormat;
}
@Override
public ModelsMap postProcessModels(ModelsMap objs) {
// process enum in models
return postProcessModelsEnum(objs);
}
}

View File

@@ -241,7 +241,7 @@ public class RustClientCodegen extends AbstractRustCodegen implements CodegenCon
discriminatorVars.add(mas);
}
// TODO: figure out how to properly have the original property type that didn't go through toVarName
String vendorExtensionTagName = cm.discriminator.getPropertyName().replace("_", "");
String vendorExtensionTagName = cm.discriminator.getPropertyName();
cm.vendorExtensions.put("x-tag-name", vendorExtensionTagName);
cm.vendorExtensions.put("x-mapped-models", discriminatorVars);
}

View File

@@ -21,14 +21,6 @@ import static org.apache.commons.lang3.StringUtils.isNotEmpty;
import static org.openapitools.codegen.utils.CamelizeOption.LOWERCASE_FIRST_LETTER;
import static org.openapitools.codegen.utils.StringUtils.camelize;
import com.samskivert.mustache.Mustache;
import io.swagger.v3.oas.models.Components;
import io.swagger.v3.oas.models.OpenAPI;
import io.swagger.v3.oas.models.Operation;
import io.swagger.v3.oas.models.PathItem;
import io.swagger.v3.oas.models.media.Schema;
import io.swagger.v3.oas.models.servers.Server;
import java.io.File;
import java.net.URL;
import java.util.ArrayList;
@@ -44,7 +36,7 @@ import java.util.Set;
import java.util.regex.Matcher;
import java.util.stream.Collectors;
import io.swagger.v3.oas.models.tags.Tag;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.tuple.Pair;
import org.openapitools.codegen.CliOption;
import org.openapitools.codegen.CodegenConstants;
@@ -73,11 +65,23 @@ import org.openapitools.codegen.model.ModelsMap;
import org.openapitools.codegen.model.OperationMap;
import org.openapitools.codegen.model.OperationsMap;
import org.openapitools.codegen.templating.mustache.SplitStringLambda;
import org.openapitools.codegen.templating.mustache.SpringHttpStatusLambda;
import org.openapitools.codegen.templating.mustache.TrimWhitespaceLambda;
import org.openapitools.codegen.utils.URLPathUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.samskivert.mustache.Mustache;
import io.swagger.v3.oas.models.Components;
import io.swagger.v3.oas.models.OpenAPI;
import io.swagger.v3.oas.models.Operation;
import io.swagger.v3.oas.models.PathItem;
import io.swagger.v3.oas.models.media.Schema;
import io.swagger.v3.oas.models.parameters.Parameter;
import io.swagger.v3.oas.models.servers.Server;
import io.swagger.v3.oas.models.tags.Tag;
public class SpringCodegen extends AbstractJavaCodegen
implements BeanValidationFeatures, PerformBeanValidationFeatures, OptionalFeatures, SwaggerUIFeatures {
private final Logger LOGGER = LoggerFactory.getLogger(SpringCodegen.class);
@@ -93,6 +97,7 @@ public class SpringCodegen extends AbstractJavaCodegen
public static final String SINGLE_CONTENT_TYPES = "singleContentTypes";
public static final String VIRTUAL_SERVICE = "virtualService";
public static final String SKIP_DEFAULT_INTERFACE = "skipDefaultInterface";
public static final String GENERATE_CONSTRUCTOR_WITH_REQUIRED_ARGS = "generatedConstructorWithRequiredArgs";
public static final String ASYNC = "async";
public static final String REACTIVE = "reactive";
@@ -106,6 +111,7 @@ public class SpringCodegen extends AbstractJavaCodegen
public static final String HATEOAS = "hateoas";
public static final String RETURN_SUCCESS_CODE = "returnSuccessCode";
public static final String UNHANDLED_EXCEPTION_HANDLING = "unhandledException";
public static final String USE_RESPONSE_ENTITY = "useResponseEntity";
public static final String USE_SPRING_BOOT3 = "useSpringBoot3";
public static final String REQUEST_MAPPING_OPTION = "requestMappingMode";
public static final String USE_REQUEST_MAPPING_ON_CONTROLLER = "useRequestMappingOnController";
@@ -153,7 +159,9 @@ public class SpringCodegen extends AbstractJavaCodegen
protected boolean unhandledException = false;
protected boolean useSpringController = false;
protected boolean useSwaggerUI = true;
protected boolean useResponseEntity = true;
protected boolean useSpringBoot3 = false;
protected boolean generatedConstructorWithRequiredArgs = true;
protected RequestMappingMode requestMappingMode = RequestMappingMode.controller;
public SpringCodegen() {
@@ -242,9 +250,16 @@ public class SpringCodegen extends AbstractJavaCodegen
cliOptions.add(CliOption.newBoolean(USE_SWAGGER_UI,
"Open the OpenApi specification in swagger-ui. Will also import and configure needed dependencies",
useSwaggerUI));
cliOptions.add(CliOption.newBoolean(USE_RESPONSE_ENTITY,
"Use the `ResponseEntity` type to wrap return values of generated API methods. "
+ "If disabled, method are annotated using a `@ResponseStatus` annotation, which has the status of the first response declared in the Api definition",
useResponseEntity));
cliOptions.add(CliOption.newBoolean(USE_SPRING_BOOT3,
"Generate code and provide dependencies for use with Spring Boot 3.x. (Use jakarta instead of javax in imports). Enabling this option will also enable `useJakartaEe`.",
useSpringBoot3));
cliOptions.add(CliOption.newBoolean(GENERATE_CONSTRUCTOR_WITH_REQUIRED_ARGS,
"Whether to generate constructors with required args for models",
generatedConstructorWithRequiredArgs));
supportedLibraries.put(SPRING_BOOT, "Spring-boot Server application.");
supportedLibraries.put(SPRING_CLOUD_LIBRARY,
@@ -454,6 +469,11 @@ public class SpringCodegen extends AbstractJavaCodegen
}
writePropertyBack(SPRING_CONTROLLER, useSpringController);
if (additionalProperties.containsKey(GENERATE_CONSTRUCTOR_WITH_REQUIRED_ARGS)) {
this.generatedConstructorWithRequiredArgs = convertPropertyToBoolean(GENERATE_CONSTRUCTOR_WITH_REQUIRED_ARGS);
}
writePropertyBack(GENERATE_CONSTRUCTOR_WITH_REQUIRED_ARGS, generatedConstructorWithRequiredArgs);
if (additionalProperties.containsKey(RETURN_SUCCESS_CODE)) {
this.setReturnSuccessCode(Boolean.parseBoolean(additionalProperties.get(RETURN_SUCCESS_CODE).toString()));
}
@@ -474,6 +494,13 @@ public class SpringCodegen extends AbstractJavaCodegen
}
additionalProperties.put(UNHANDLED_EXCEPTION_HANDLING, this.isUnhandledException());
if (additionalProperties.containsKey(USE_RESPONSE_ENTITY)) {
this.setUseResponseEntity(
Boolean.parseBoolean(additionalProperties.get(USE_RESPONSE_ENTITY).toString()));
}
writePropertyBack(USE_RESPONSE_ENTITY, useResponseEntity);
additionalProperties.put("springHttpStatus", new SpringHttpStatusLambda());
if (additionalProperties.containsKey(USE_SPRING_BOOT3)) {
this.setUseSpringBoot3(convertPropertyToBoolean(USE_SPRING_BOOT3));
}
@@ -490,6 +517,7 @@ public class SpringCodegen extends AbstractJavaCodegen
}
writePropertyBack(USE_SPRING_BOOT3, isUseSpringBoot3());
typeMapping.put("file", "org.springframework.core.io.Resource");
importMapping.put("org.springframework.core.io.Resource", "org.springframework.core.io.Resource");
importMapping.put("Pageable", "org.springframework.data.domain.Pageable");
@@ -801,6 +829,7 @@ public class SpringCodegen extends AbstractJavaCodegen
}
});
prepareVersioningParameters(ops);
handleImplicitHeaders(operation);
}
// The tag for the controller is the first tag of the first operation
@@ -854,6 +883,32 @@ public class SpringCodegen extends AbstractJavaCodegen
}
}
private void prepareVersioningParameters(List<CodegenOperation> operations) {
for (CodegenOperation operation : operations) {
if (operation.getHasHeaderParams()) {
List<CodegenParameter> versionParams = operation.headerParams.stream()
.filter(param -> {
String xVersionParam = Objects.toString(param.vendorExtensions.get(VendorExtension.X_VERSION_PARAM.getName()), "false");
return Boolean.parseBoolean(xVersionParam);
})
.collect(Collectors.toList());
operation.hasVersionHeaders = !versionParams.isEmpty();
operation.vendorExtensions.put("versionHeaderParamsList", versionParams);
}
if (operation.getHasQueryParams()) {
List<CodegenParameter> versionParams = operation.queryParams.stream()
.filter(param -> {
String xVersionParam = Objects.toString(param.vendorExtensions.get(VendorExtension.X_VERSION_PARAM.getName()), "false");
return Boolean.parseBoolean(xVersionParam);
})
.collect(Collectors.toList());
operation.hasVersionQueryParams = !versionParams.isEmpty();
operation.vendorExtensions.put("versionQueryParamsList", versionParams);
}
}
}
@Override
public Map<String, Object> postProcessSupportingFileData(Map<String, Object> objs) {
generateYAMLSpecFile(objs);
@@ -988,6 +1043,10 @@ public class SpringCodegen extends AbstractJavaCodegen
this.unhandledException = unhandledException;
}
public void setUseResponseEntity(boolean useResponseEntity) {
this.useResponseEntity = useResponseEntity;
}
@Override
public void postProcessModelProperty(CodegenModel model, CodegenProperty property) {
super.postProcessModelProperty(model, property);
@@ -1075,6 +1134,10 @@ public class SpringCodegen extends AbstractJavaCodegen
codegenModel.getImports().add(imp);
}
}
if (property.required) {
codegenModel.parentRequiredVars.add(parentVar.clone());
}
}
}
parentCodegenModel = parentCodegenModel.getParentModel();
@@ -1178,6 +1241,7 @@ public class SpringCodegen extends AbstractJavaCodegen
public List<VendorExtension> getSupportedVendorExtensions() {
List<VendorExtension> extensions = super.getSupportedVendorExtensions();
extensions.add(VendorExtension.X_SPRING_PAGINATED);
extensions.add(VendorExtension.X_VERSION_PARAM);
return extensions;
}
@@ -1196,4 +1260,60 @@ public class SpringCodegen extends AbstractJavaCodegen
public void setRequestMappingMode(RequestMappingMode requestMappingMode) {
this.requestMappingMode = requestMappingMode;
}
@Override
public CodegenParameter fromParameter( final Parameter parameter, final Set<String> imports ) {
CodegenParameter codegenParameter = super.fromParameter( parameter, imports );
if(!isListOrSet(codegenParameter)){
return codegenParameter;
}
codegenParameter.datatypeWithEnum = replaceBeanValidationCollectionType(codegenParameter.items, codegenParameter.datatypeWithEnum );
codegenParameter.dataType = replaceBeanValidationCollectionType(codegenParameter.items, codegenParameter.dataType );
return codegenParameter;
}
@Override
public CodegenProperty fromProperty( String name, Schema p, boolean required, boolean schemaIsFromAdditionalProperties ) {
CodegenProperty codegenProperty = super.fromProperty( name, p, required, schemaIsFromAdditionalProperties );
if(!isListOrSet(codegenProperty)){
return codegenProperty;
}
codegenProperty.datatypeWithEnum = replaceBeanValidationCollectionType(codegenProperty.items, codegenProperty.datatypeWithEnum );
codegenProperty.dataType = replaceBeanValidationCollectionType(codegenProperty.items, codegenProperty.dataType );
return codegenProperty;
}
// The default validation applied for non-container and non-map types is sufficient for the SpringCodegen.
// Maps are very complex for bean validation, so it's currently not supported.
private static boolean isListOrSet(CodegenProperty codegenProperty) {
return codegenProperty.isContainer && !codegenProperty.isMap;
}
// The default validation applied for non-container and non-map types is sufficient for the SpringCodegen.
// Maps are very complex for bean validation, so it's currently not supported.
private static boolean isListOrSet(CodegenParameter codegenParameter) {
return codegenParameter.isContainer && !codegenParameter.isMap;
}
private String replaceBeanValidationCollectionType(CodegenProperty codegenProperty, String dataType) {
if (!useBeanValidation() || !codegenProperty.isModel || isResponseType(codegenProperty)) {
return dataType;
}
if (StringUtils.isEmpty( dataType ) || dataType.contains( "@Valid" )) {
return dataType;
}
return dataType.replace( "<", "<@Valid " );
}
// This should prevent, that the response data types not contains a @Valid annotation.
// However, the side effect is that attributes with response as name are also affected.
private static boolean isResponseType(CodegenProperty codegenProperty) {
return codegenProperty.baseName.toLowerCase(Locale.ROOT).contains("response");
}
// SPRING_HTTP_INTERFACE does not support bean validation.
public boolean useBeanValidation() {
return useBeanValidation && !SPRING_HTTP_INTERFACE.equals(library);
}
}

View File

@@ -145,7 +145,8 @@ public class Swift5ClientCodegen extends DefaultCodegen implements CodegenConfig
"URL",
"AnyObject",
"Any",
"Decimal")
"Decimal",
"AnyCodable") // from AnyCodable dependency
);
defaultIncludes = new HashSet<>(
Arrays.asList(
@@ -731,11 +732,11 @@ public class Swift5ClientCodegen extends DefaultCodegen implements CodegenConfig
// FIXME parameter should not be assigned. Also declare it as "final"
name = sanitizeName(name);
if (!StringUtils.isEmpty(modelNameSuffix)) { // set model suffix
if (!StringUtils.isEmpty(modelNameSuffix) && !isLanguageSpecificType(name)) { // set model suffix
name = name + "_" + modelNameSuffix;
}
if (!StringUtils.isEmpty(modelNamePrefix)) { // set model prefix
if (!StringUtils.isEmpty(modelNamePrefix) && !isLanguageSpecificType(name)) { // set model prefix
name = modelNamePrefix + "_" + name;
}
@@ -1086,6 +1087,10 @@ public class Swift5ClientCodegen extends DefaultCodegen implements CodegenConfig
LOWERCASE_FIRST_LETTER);
}
private Boolean isLanguageSpecificType(String name) {
return languageSpecificPrimitives.contains(name);
}
private String replaceSpecialCharacters(String name) {
for (Map.Entry<String, String> specialCharacters : specialCharReplacements.entrySet()) {
String specialChar = specialCharacters.getKey();

View File

@@ -607,7 +607,7 @@ public class TypeScriptAngularClientCodegen extends AbstractTypeScriptClientCode
if (importMapping.containsKey(name)) {
return importMapping.get(name);
}
return DEFAULT_MODEL_IMPORT_DIRECTORY_PREFIX + modelPackage() + "/" + toModelFilename(name).substring(DEFAULT_IMPORT_PREFIX.length());
return DEFAULT_MODEL_IMPORT_DIRECTORY_PREFIX + modelPackage() + "/" + toModelFilename(removeModelPrefixSuffix(name)).substring(DEFAULT_IMPORT_PREFIX.length());
}
public String getNpmRepository() {

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