diff --git a/.github/dependabot.yml b/.github/dependabot.yml
new file mode 100644
index 0000000000..123014908b
--- /dev/null
+++ b/.github/dependabot.yml
@@ -0,0 +1,6 @@
+version: 2
+updates:
+ - package-ecosystem: "github-actions"
+ directory: "/"
+ schedule:
+ interval: "daily"
diff --git a/.github/workflows/sonar.yml b/.github/workflows/sonar.yml
index e52981a745..bc4992833b 100644
--- a/.github/workflows/sonar.yml
+++ b/.github/workflows/sonar.yml
@@ -10,7 +10,7 @@ jobs:
build:
runs-on: ubuntu-latest
-
+ if: ${{ github.repository_owner == 'OpenAPITools' }}
steps:
- uses: actions/checkout@v1
- name: Set up JDK 11
diff --git a/.travis.yml b/.travis.yml
index edbd8c27dd..9ba0b842f0 100644
--- a/.travis.yml
+++ b/.travis.yml
@@ -149,6 +149,8 @@ install:
script:
# fail fast
- set -e
+ # fail if the template files contains tabs
+ - /bin/bash ./bin/utils/detect_tab_in_templates.sh
# fail if the test files have changes
- bin/utils/detect_test_file_changes.rb bin/utils/test_file_list.yaml
# fail if templates/generators contain carriage return '\r'
diff --git a/README.md b/README.md
index 2b436786cc..677a6e338b 100644
--- a/README.md
+++ b/README.md
@@ -69,7 +69,7 @@ OpenAPI Generator allows generation of API client libraries (SDK generation), se
| | Languages/Frameworks |
| -------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
-| **API clients** | **ActionScript**, **Ada**, **Apex**, **Bash**, **C**, **C#** (.net 2.0, 3.5 or later, .NET Standard 1.3 - 2.0, .NET Core 2.0, .NET 5.0), **C++** (cpp-restsdk, Qt5, Tizen, Unreal Engine 4), **Clojure**, **Crystal**, **Dart**, **Elixir**, **Elm**, **Eiffel**, **Erlang**, **Go**, **Groovy**, **Haskell** (http-client, Servant), **Java** (Jersey1.x, Jersey2.x, OkHttp, Retrofit1.x, Retrofit2.x, Feign, RestTemplate, RESTEasy, Vertx, Google API Client Library for Java, Rest-assured, Spring 5 Web Client, MicroProfile Rest Client), **k6**, **Kotlin**, **Lua**, **Nim**, **Node.js/JavaScript** (ES5, ES6, AngularJS with Google Closure Compiler annotations, Flow types, Apollo GraphQL DataStore), **Objective-C**, **OCaml**, **Perl**, **PHP**, **PowerShell**, **Python**, **R**, **Ruby**, **Rust** (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 - 11.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.0, .NET Core 2.0, .NET 5.0. Libraries: RestSharp, HttpClient), **C++** (cpp-restsdk, Qt5, Tizen, Unreal Engine 4), **Clojure**, **Crystal**, **Dart**, **Elixir**, **Elm**, **Eiffel**, **Erlang**, **Go**, **Groovy**, **Haskell** (http-client, Servant), **Java** (Jersey1.x, Jersey2.x, OkHttp, Retrofit1.x, Retrofit2.x, Feign, RestTemplate, RESTEasy, Vertx, Google API Client Library for Java, Rest-assured, Spring 5 Web Client, MicroProfile Rest Client), **k6**, **Kotlin**, **Lua**, **Nim**, **Node.js/JavaScript** (ES5, ES6, AngularJS with Google Closure Compiler annotations, Flow types, Apollo GraphQL DataStore), **Objective-C**, **OCaml**, **Perl**, **PHP**, **PowerShell**, **Python**, **R**, **Ruby**, **Rust** (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 - 11.x), Aurelia, Axios, Fetch, Inversify, jQuery, Nestjs, Node, redux-query, Rxjs) |
| **Server stubs** | **Ada**, **C#** (ASP.NET Core, NancyFx), **C++** (Pistache, Restbed, Qt5 QHTTPEngine), **Erlang**, **F#** (Giraffe), **Go** (net/http, Gin), **Haskell** (Servant), **Java** (MSF4J, Spring, Undertow, JAX-RS: CDI, CXF, Inflector, Jersey, RestEasy, Play Framework, [PKMST](https://github.com/ProKarma-Inc/pkmst-getting-started-examples), [Vert.x](https://vertx.io/)), **Kotlin** (Spring Boot, Ktor, Vertx), **PHP** (Laravel, Lumen, Slim, Silex, [Symfony](https://symfony.com/), [Zend Expressive](https://github.com/zendframework/zend-expressive)), **Python** (Flask), **NodeJS**, **Ruby** (Sinatra, Rails5), **Rust** (rust-server), **Scala** (Akka, [Finch](https://github.com/finagle/finch), [Lagom](https://github.com/lagom/lagom), [Play](https://www.playframework.com/), Scalatra) |
| **API documentation generators** | **HTML**, **Confluence Wiki**, **Asciidoc**, **Markdown**, **PlantUML** |
| **Configuration files** | [**Apache2**](https://httpd.apache.org/) |
@@ -606,6 +606,7 @@ Here are some companies/projects (alphabetical order) using OpenAPI Generator in
- [GetYourGuide](https://www.getyourguide.com/)
- [GMO Pepabo](https://pepabo.com/en/)
- [GoDaddy](https://godaddy.com)
+- [Gumtree](https://gumtree.com)
- [Here](https://developer.here.com/)
- [IBM](https://www.ibm.com/)
- [Instana](https://www.instana.com)
@@ -801,6 +802,8 @@ Here are some companies/projects (alphabetical order) using OpenAPI Generator in
- 2020-12-15 - [Next.js + NestJS + GraphQLで変化に追従するフロントエンドへ 〜 ショッピングクーポンの事例紹介](https://techblog.yahoo.co.jp/entry/2020121530052952/) by [小倉 陸](https://github.com/ogugu9) at [Yahoo! JAPAN Tech Blog](https://techblog.yahoo.co.jp/)
- 2021-01-08 - [Hello, New API – Part 1](https://www.nginx.com/blog/hello-new-api-part-1/) by [Jeremy Schulman](https://www.nginx.com/people/jeremy-schulman/) at [Major League Baseball](https://www.mlb.com)
- 2021-01-18 - [「アプリ開発あるある」を疑うことから始まった、API Clientコードの自動生成【デブスト2020】](https://codezine.jp/article/detail/13406?p=2) by [CodeZine編集部](https://codezine.jp/author/1)
+- 2021-02-05 - [REST-API-Roundtrip with SpringDoc and OpenAPI Generator](https://blog.viadee.de/en/rest-api-roundtrip) by [Benjamin Klatt](https://twitter.com/benklatt) at [viadee](https://www.viadee.de/en/)
+- 2021-02-17 - [REST-API-Roundtrip with SpringDoc and OpenAPI Generator](https://medium.com/nerd-for-tech/rest-api-roundtrip-with-springdoc-and-openapi-generator-30bd27ccf698) by [cloud @viadee](https://cloud-viadee.medium.com/)
## [6 - About Us](#table-of-contents)
@@ -834,6 +837,7 @@ Here is a list of template creators:
* C# (.NET 2.0): @who
* C# (.NET Standard 1.3 ): @Gronsak
* C# (.NET 4.5 refactored): @jimschubert [:heart:](https://www.patreon.com/jimschubert)
+ * C# (HttpClient): @Blackclaws
* Clojure: @xhh
* Crystal: @wing328
* Dart: @yissachar
diff --git a/appveyor.yml b/appveyor.yml
index b12d075eb4..549974b249 100644
--- a/appveyor.yml
+++ b/appveyor.yml
@@ -35,12 +35,16 @@ install:
- ps: Install-Module Pester -Force -Scope CurrentUser
build_script:
- dotnet --info
+ # build C# aspnetcore 5.0 server
+ - dotnet build samples\server\petstore\aspnetcore-5.0\Org.OpenAPITools.sln
# build C# aspnetcore 3.1 server
- dotnet build samples\server\petstore\aspnetcore-3.1\Org.OpenAPITools.sln
# build C# aspnetcore 3.0 server
- dotnet build samples\server\petstore\aspnetcore-3.0\Org.OpenAPITools.sln
# build C# aspnetcore 2.2 server
- dotnet build samples\server\petstore\aspnetcore\Org.OpenAPITools.sln
+ # build C# API client (httpclient)
+ - dotnet build samples\client\petstore\csharp-netcore\OpenAPIClient-httpclient\Org.OpenAPITools.sln
# build C# API client (netcore)
- dotnet build samples\client\petstore\csharp-netcore\OpenAPIClient\Org.OpenAPITools.sln
- dotnet build samples\client\petstore\csharp-netcore\OpenAPIClientCore\Org.OpenAPITools.sln
@@ -62,6 +66,8 @@ build_script:
# run the locally installed openapi-generator-gradle-plugin
- gradle -b modules\openapi-generator-gradle-plugin\samples\local-spec\build.gradle buildGoSdk --stacktrace
test_script:
+ # test c# API client (httpclient)
+ - dotnet test samples\client\petstore\csharp-netcore\OpenAPIClient-httpclient\src\Org.OpenAPITools.Test\Org.OpenAPITools.Test.csproj
# test c# API client (netcore)
- dotnet test samples\client\petstore\csharp-netcore\OpenAPIClientCore\src\Org.OpenAPITools.Test\Org.OpenAPITools.Test.csproj
- dotnet test samples\client\petstore\csharp-netcore\OpenAPIClient\src\Org.OpenAPITools.Test\Org.OpenAPITools.Test.csproj
diff --git a/bin/configs/aspnetcore-5.0.yaml b/bin/configs/aspnetcore-5.0.yaml
new file mode 100644
index 0000000000..b4dc00c569
--- /dev/null
+++ b/bin/configs/aspnetcore-5.0.yaml
@@ -0,0 +1,7 @@
+generatorName: aspnetcore
+outputDir: samples/server/petstore/aspnetcore-5.0
+inputSpec: modules/openapi-generator/src/test/resources/3_0/petstore.yaml
+templateDir: modules/openapi-generator/src/main/resources/aspnetcore/3.0
+additionalProperties:
+ packageGuid: '{3C799344-F285-4669-8FD5-7ED9B795D5C5}'
+ aspnetCoreVersion: "5.0"
diff --git a/bin/configs/csharp-netcore-OpenAPIClient-httpclient.yaml b/bin/configs/csharp-netcore-OpenAPIClient-httpclient.yaml
new file mode 100644
index 0000000000..21fba7e257
--- /dev/null
+++ b/bin/configs/csharp-netcore-OpenAPIClient-httpclient.yaml
@@ -0,0 +1,12 @@
+# for .net standard httpclient
+generatorName: csharp-netcore
+outputDir: samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient
+inputSpec: modules/openapi-generator/src/test/resources/3_0/java/petstore-with-fake-endpoints-models-for-testing-with-http-signature.yaml
+templateDir: modules/openapi-generator/src/main/resources/csharp-netcore
+library: httpclient
+additionalProperties:
+ packageGuid: '{321C8C3F-0156-40C1-AE42-D59761FB9B6C}'
+ useCompareNetObjects: true
+ disallowAdditionalPropertiesIfNotPresent: false
+ useOneOfDiscriminatorLookup: true
+ targetFramework: netstandard2.1
diff --git a/bin/configs/dart-petstore-json-serializable-client-lib-fake.yaml b/bin/configs/dart-petstore-json-serializable-client-lib-fake.yaml
new file mode 100644
index 0000000000..cb943d3d95
--- /dev/null
+++ b/bin/configs/dart-petstore-json-serializable-client-lib-fake.yaml
@@ -0,0 +1,7 @@
+generatorName: dart
+outputDir: samples/openapi3/client/petstore/dart2/petstore_json_serializable_client_lib_fake
+inputSpec: modules/openapi-generator/src/test/resources/3_0/petstore-with-fake-endpoints-models-for-testing.yaml
+templateDir: modules/openapi-generator/src/main/resources/dart2
+additionalProperties:
+ hideGenerationTimestamp: "true"
+ serializationLibrary: json_serializable
diff --git a/bin/utils/detect_tab_in_templates.sh b/bin/utils/detect_tab_in_templates.sh
new file mode 100755
index 0000000000..e3ac60b104
--- /dev/null
+++ b/bin/utils/detect_tab_in_templates.sh
@@ -0,0 +1,28 @@
+#!/bin/bash
+#
+# Look for \t in the template folders and report errors if found
+# as these tabs should be replaced with 4-space instead
+
+## declare an array of folders
+declare -a samples=("modules/openapi-generator/src/main/resources/kotlin-server"
+ "modules/openapi-generator/src/main/resources/kotlin-spring"
+ "modules/openapi-generator/src/main/resources/dart-dio"
+ "modules/openapi-generator/src/main/resources/dart"
+ "modules/openapi-generator/src/main/resources/dart2"
+ "modules/openapi-generator/src/main/resources/aspnetcore"
+ "modules/openapi-generator/src/main/resources/powershell"
+ )
+
+## now loop through the above array
+for i in "${samples[@]}"
+do
+ # grep for \t in the folder
+ RESULT=`grep -R -P "\t" $i`
+ echo -e "$RESULT"
+
+ if [ "$RESULT" != "" ]; then
+ echo "Template files contain tab '\\t'. Please remove it or replace it with 4-space."
+ exit 1;
+ fi
+done
+
diff --git a/docs/generators/aspnetcore.md b/docs/generators/aspnetcore.md
index da3a237c6f..10efd15307 100644
--- a/docs/generators/aspnetcore.md
+++ b/docs/generators/aspnetcore.md
@@ -7,7 +7,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl
| Option | Description | Values | Default |
| ------ | ----------- | ------ | ------- |
-|aspnetCoreVersion|ASP.NET Core version: 3.1, 3.0, 2.2, 2.1, 2.0 (deprecated)| |3.1|
+|aspnetCoreVersion|ASP.NET Core version: 5.0, 3.1, 3.0, 2.2, 2.1, 2.0 (deprecated)| |3.1|
|buildTarget|Target to build an application or library| |program|
|classModifier|Class Modifier for controller classes: Empty string or abstract.| ||
|compatibilityVersion|ASP.Net Core CompatibilityVersion| |Version_2_2|
diff --git a/docs/generators/csharp-netcore.md b/docs/generators/csharp-netcore.md
index 60a347dfea..bdcc218dbb 100644
--- a/docs/generators/csharp-netcore.md
+++ b/docs/generators/csharp-netcore.md
@@ -12,6 +12,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl
|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.|
**false** The 'additionalProperties' implementation is compliant with the OAS and JSON schema specifications. **true** Keep the old (incorrect) behaviour that 'additionalProperties' is set to false by default. |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|**httpclient** HttpClient (https://docs.microsoft.com/en-us/dotnet/api/system.net.http.httpclient) (Beta support) **restsharp** RestSharp (https://github.com/restsharp/RestSharp) |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|
diff --git a/docs/generators/dart-dio.md b/docs/generators/dart-dio.md
index ffff1394c4..ebbc40b543 100644
--- a/docs/generators/dart-dio.md
+++ b/docs/generators/dart-dio.md
@@ -12,7 +12,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl
|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.|**false** The 'additionalProperties' implementation is compliant with the OAS and JSON schema specifications. **true** Keep the old (incorrect) behaviour that 'additionalProperties' is set to false by default. |true|
|ensureUniqueParams|Whether to ensure parameter names are unique in an operation (rename parameters that are not).| |true|
|legacyDiscriminatorBehavior|Set to true for generators with better support for discriminators. (Python, Java, Go, PowerShell, C#have this enabled by default).|**true** The mapping in the discriminator includes descendent schemas that allOf inherit from self and the discriminator mapping schemas in the OAS document. **false** The mapping in the discriminator includes any descendent schemas that allOf inherit from self, any oneOf schemas, any anyOf schemas, any x-discriminator-values, and the discriminator mapping schemas in the OAS document AND Codegen validates that oneOf and anyOf schemas contain the required discriminator and throws an error if the discriminator is missing. |true|
-|nullableFields|Is the null fields should be in the JSON payload| |null|
+|nullableFields|Make all fields nullable in the JSON payload| |null|
|prependFormOrBodyParameters|Add form or body parameters to the beginning of the parameter list.| |false|
|pubAuthor|Author name in generated pubspec| |null|
|pubAuthorEmail|Email address of the author in generated pubspec| |null|
diff --git a/docs/generators/dart.md b/docs/generators/dart.md
index e7dae224ef..115126907e 100644
--- a/docs/generators/dart.md
+++ b/docs/generators/dart.md
@@ -19,6 +19,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl
|pubLibrary|Library name in generated code| |null|
|pubName|Name in generated pubspec| |null|
|pubVersion|Version in generated pubspec| |null|
+|serializationLibrary|Specify serialization library|**native_serialization** Use native serializer, backwards compatible **json_serializable** Use json_serializable |native_serialization|
|sortModelPropertiesByRequiredFlag|Sort model properties to place required parameters before optional parameters.| |true|
|sortParamsByRequiredFlag|Sort method arguments to place required parameters before optional parameters.| |true|
|sourceFolder|Source folder for generated code| |null|
diff --git a/docs/generators/go-gin-server.md b/docs/generators/go-gin-server.md
index 85e24728f1..0c1d324191 100644
--- a/docs/generators/go-gin-server.md
+++ b/docs/generators/go-gin-server.md
@@ -8,6 +8,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl
| Option | Description | Values | Default |
| ------ | ----------- | ------ | ------- |
|apiPath|Name of the folder that contains the Go source code| |go|
+|enumClassPrefix|Prefix enum with class name| |false|
|hideGenerationTimestamp|Hides the generation timestamp when files are generated.| |true|
|packageName|Go package name (convention: lowercase).| |openapi|
|packageVersion|Go package version.| |1.0.0|
diff --git a/docs/generators/java.md b/docs/generators/java.md
index 38c3f19f56..dd82de49bc 100644
--- a/docs/generators/java.md
+++ b/docs/generators/java.md
@@ -52,7 +52,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl
|scmDeveloperConnection|SCM developer connection in generated pom.xml| |scm:git:git@github.com:openapitools/openapi-generator.git|
|scmUrl|SCM URL in generated pom.xml| |https://github.com/openapitools/openapi-generator|
|serializableModel|boolean - toggle "implements Serializable" for generated models| |false|
-|serializationLibrary|Serialization library, default depends from the library|**jackson** Use Jackson as serialization library **gson** Use Gson as serialization library |null|
+|serializationLibrary|Serialization library, default depends from the library|**jsonb** Use JSON-B as serialization library **jackson** Use Jackson as serialization library **gson** Use Gson as serialization library |null|
|snapshotVersion|Uses a SNAPSHOT version.|**true** Use a SnapShot Version **false** Use a Release Version |null|
|sortModelPropertiesByRequiredFlag|Sort model properties to place required parameters before optional parameters.| |true|
|sortParamsByRequiredFlag|Sort method arguments to place required parameters before optional parameters.| |true|
diff --git a/docs/generators/php-laravel.md b/docs/generators/php-laravel.md
index 10a7bde7f5..231b20da3c 100644
--- a/docs/generators/php-laravel.md
+++ b/docs/generators/php-laravel.md
@@ -33,7 +33,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl
| Type/Alias | Instantiated By |
| ---------- | --------------- |
|array|array|
-|map|map|
+|map|array|
## LANGUAGE PRIMITIVES
diff --git a/docs/generators/php-lumen.md b/docs/generators/php-lumen.md
index 8e7e77dc74..36210f7967 100644
--- a/docs/generators/php-lumen.md
+++ b/docs/generators/php-lumen.md
@@ -33,7 +33,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl
| Type/Alias | Instantiated By |
| ---------- | --------------- |
|array|array|
-|map|map|
+|map|array|
## LANGUAGE PRIMITIVES
diff --git a/docs/generators/php-mezzio-ph.md b/docs/generators/php-mezzio-ph.md
index 3a599e531a..c434a21a0d 100644
--- a/docs/generators/php-mezzio-ph.md
+++ b/docs/generators/php-mezzio-ph.md
@@ -33,7 +33,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl
| Type/Alias | Instantiated By |
| ---------- | --------------- |
|array|array|
-|map|map|
+|map|array|
## LANGUAGE PRIMITIVES
diff --git a/docs/generators/php-slim-deprecated.md b/docs/generators/php-slim-deprecated.md
index 6f8786ab00..a442c01e42 100644
--- a/docs/generators/php-slim-deprecated.md
+++ b/docs/generators/php-slim-deprecated.md
@@ -33,7 +33,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl
| Type/Alias | Instantiated By |
| ---------- | --------------- |
|array|array|
-|map|map|
+|map|array|
## LANGUAGE PRIMITIVES
diff --git a/docs/generators/php-slim4.md b/docs/generators/php-slim4.md
index 67a77f5f6b..52146c07da 100644
--- a/docs/generators/php-slim4.md
+++ b/docs/generators/php-slim4.md
@@ -34,7 +34,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl
| Type/Alias | Instantiated By |
| ---------- | --------------- |
|array|array|
-|map|map|
+|map|array|
## LANGUAGE PRIMITIVES
diff --git a/docs/generators/php-symfony.md b/docs/generators/php-symfony.md
index 9c37619391..5bdff1fef8 100644
--- a/docs/generators/php-symfony.md
+++ b/docs/generators/php-symfony.md
@@ -39,7 +39,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl
| Type/Alias | Instantiated By |
| ---------- | --------------- |
|array|array|
-|map|map|
+|map|array|
## LANGUAGE PRIMITIVES
diff --git a/docs/generators/php.md b/docs/generators/php.md
index cb4d09c3fc..177fb0daba 100644
--- a/docs/generators/php.md
+++ b/docs/generators/php.md
@@ -34,7 +34,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl
| Type/Alias | Instantiated By |
| ---------- | --------------- |
|array|array|
-|map|map|
+|map|array|
## LANGUAGE PRIMITIVES
diff --git a/docs/generators/python-aiohttp.md b/docs/generators/python-aiohttp.md
index ded84c5524..7fbe2222c6 100644
--- a/docs/generators/python-aiohttp.md
+++ b/docs/generators/python-aiohttp.md
@@ -42,13 +42,14 @@ These options may be applied as additional-properties (cli) or configOptions (pl
Dict
List
bool
-byte
-bytearray
+bytes
date
datetime
+dict
file
float
int
+list
object
str
@@ -56,9 +57,14 @@ These options may be applied as additional-properties (cli) or configOptions (pl
## RESERVED WORDS
+all_params
and
as
assert
+async
+auth_settings
+await
+body_params
break
class
continue
@@ -71,21 +77,27 @@ These options may be applied as additional-properties (cli) or configOptions (pl
false
finally
for
+form_params
from
global
+header_params
if
import
in
is
lambda
+local_var_files
none
nonlocal
not
or
pass
+path_params
print
property
+query_params
raise
+resource_path
return
self
true
diff --git a/docs/generators/python-blueplanet.md b/docs/generators/python-blueplanet.md
index eb4fdab9aa..98ee0ad818 100644
--- a/docs/generators/python-blueplanet.md
+++ b/docs/generators/python-blueplanet.md
@@ -42,13 +42,14 @@ These options may be applied as additional-properties (cli) or configOptions (pl
Dict
List
bool
-byte
-bytearray
+bytes
date
datetime
+dict
file
float
int
+list
object
str
@@ -56,9 +57,14 @@ These options may be applied as additional-properties (cli) or configOptions (pl
## RESERVED WORDS
+all_params
and
as
assert
+async
+auth_settings
+await
+body_params
break
class
continue
@@ -71,21 +77,27 @@ These options may be applied as additional-properties (cli) or configOptions (pl
false
finally
for
+form_params
from
global
+header_params
if
import
in
is
lambda
+local_var_files
none
nonlocal
not
or
pass
+path_params
print
property
+query_params
raise
+resource_path
return
self
true
diff --git a/docs/generators/python-flask.md b/docs/generators/python-flask.md
index a0b17be648..372272b45c 100644
--- a/docs/generators/python-flask.md
+++ b/docs/generators/python-flask.md
@@ -42,13 +42,14 @@ These options may be applied as additional-properties (cli) or configOptions (pl
Dict
List
bool
-byte
-bytearray
+bytes
date
datetime
+dict
file
float
int
+list
object
str
@@ -56,9 +57,14 @@ These options may be applied as additional-properties (cli) or configOptions (pl
## RESERVED WORDS
+all_params
and
as
assert
+async
+auth_settings
+await
+body_params
break
class
continue
@@ -71,21 +77,27 @@ These options may be applied as additional-properties (cli) or configOptions (pl
false
finally
for
+form_params
from
global
+header_params
if
import
in
is
lambda
+local_var_files
none
nonlocal
not
or
pass
+path_params
print
property
+query_params
raise
+resource_path
return
self
true
diff --git a/modules/openapi-generator-cli/src/main/java/org/openapitools/codegen/cmd/AuthorTemplate.java b/modules/openapi-generator-cli/src/main/java/org/openapitools/codegen/cmd/AuthorTemplate.java
index 50b6b4a281..da02a60246 100644
--- a/modules/openapi-generator-cli/src/main/java/org/openapitools/codegen/cmd/AuthorTemplate.java
+++ b/modules/openapi-generator-cli/src/main/java/org/openapitools/codegen/cmd/AuthorTemplate.java
@@ -23,7 +23,7 @@ import java.util.stream.Stream;
@Command(name = "template", description = "Retrieve templates for local modification")
public class AuthorTemplate extends OpenApiGeneratorCommand {
- private static final Logger LOGGER = LoggerFactory.getLogger(AuthorTemplate.class);
+ private final Logger LOGGER = LoggerFactory.getLogger(AuthorTemplate.class);
@Option(name = {"-g", "--generator-name"}, title = "generator name",
description = "generator to use (see list command for list)",
diff --git a/modules/openapi-generator-cli/src/main/java/org/openapitools/codegen/cmd/ConfigHelp.java b/modules/openapi-generator-cli/src/main/java/org/openapitools/codegen/cmd/ConfigHelp.java
index 57eac71571..7a7d02c272 100644
--- a/modules/openapi-generator-cli/src/main/java/org/openapitools/codegen/cmd/ConfigHelp.java
+++ b/modules/openapi-generator-cli/src/main/java/org/openapitools/codegen/cmd/ConfigHelp.java
@@ -43,7 +43,7 @@ import static org.apache.commons.lang3.StringUtils.isEmpty;
@Command(name = "config-help", description = "Config help for chosen lang")
public class ConfigHelp extends OpenApiGeneratorCommand {
- private static final Logger LOGGER = LoggerFactory.getLogger(ConfigHelp.class);
+ private final Logger LOGGER = LoggerFactory.getLogger(ConfigHelp.class);
private static final String FORMAT_TEXT = "text";
private static final String FORMAT_MARKDOWN = "markdown";
diff --git a/modules/openapi-generator-cli/src/main/java/org/openapitools/codegen/cmd/Generate.java b/modules/openapi-generator-cli/src/main/java/org/openapitools/codegen/cmd/Generate.java
index 2fcf1c04f1..f935b14e6d 100644
--- a/modules/openapi-generator-cli/src/main/java/org/openapitools/codegen/cmd/Generate.java
+++ b/modules/openapi-generator-cli/src/main/java/org/openapitools/codegen/cmd/Generate.java
@@ -217,6 +217,10 @@ public class Generate extends OpenApiGeneratorCommand {
description = CodegenConstants.REMOVE_OPERATION_ID_PREFIX_DESC)
private Boolean removeOperationIdPrefix;
+ @Option(name = {"--skip-operation-example"}, title = "skip examples defined in the operation",
+ description = CodegenConstants.SKIP_OPERATION_EXAMPLE_DESC)
+ private Boolean skipOperationExample;
+
@Option(name = {"--skip-validate-spec"},
title = "skip spec validation",
description = "Skips the default behavior of validating an input specification.")
@@ -393,6 +397,10 @@ public class Generate extends OpenApiGeneratorCommand {
configurator.setRemoveOperationIdPrefix(removeOperationIdPrefix);
}
+ if (skipOperationExample != null) {
+ configurator.setSkipOperationExample(skipOperationExample);
+ }
+
if (enablePostProcessFile != null) {
configurator.setEnablePostProcessFile(enablePostProcessFile);
}
diff --git a/modules/openapi-generator-cli/src/main/java/org/openapitools/codegen/cmd/GenerateBatch.java b/modules/openapi-generator-cli/src/main/java/org/openapitools/codegen/cmd/GenerateBatch.java
index cb2ae60dba..7c8cc543bc 100644
--- a/modules/openapi-generator-cli/src/main/java/org/openapitools/codegen/cmd/GenerateBatch.java
+++ b/modules/openapi-generator-cli/src/main/java/org/openapitools/codegen/cmd/GenerateBatch.java
@@ -65,7 +65,7 @@ import java.util.stream.Stream;
public class GenerateBatch extends OpenApiGeneratorCommand {
private static AtomicInteger failures = new AtomicInteger(0);
private static AtomicInteger successes = new AtomicInteger(0);
- private static final Logger LOGGER = LoggerFactory.getLogger(GenerateBatch.class);
+ private final Logger LOGGER = LoggerFactory.getLogger(GenerateBatch.class);
@Option(name = {"-v", "--verbose"}, description = "verbose mode")
private Boolean verbose;
diff --git a/modules/openapi-generator-core/src/main/java/org/openapitools/codegen/api/TemplateProcessor.java b/modules/openapi-generator-core/src/main/java/org/openapitools/codegen/api/TemplateProcessor.java
index 6f10516760..536d2d89ac 100644
--- a/modules/openapi-generator-core/src/main/java/org/openapitools/codegen/api/TemplateProcessor.java
+++ b/modules/openapi-generator-core/src/main/java/org/openapitools/codegen/api/TemplateProcessor.java
@@ -53,5 +53,5 @@ public interface TemplateProcessor {
* @param path The path which has caused an error
* @param context The reason for the error
*/
- default void error(Path path, String context) { };
+ default void error(Path path, String context) { }
}
diff --git a/modules/openapi-generator-core/src/main/java/org/openapitools/codegen/config/GeneratorSettings.java b/modules/openapi-generator-core/src/main/java/org/openapitools/codegen/config/GeneratorSettings.java
index 0fdfc209d5..e104409200 100644
--- a/modules/openapi-generator-core/src/main/java/org/openapitools/codegen/config/GeneratorSettings.java
+++ b/modules/openapi-generator-core/src/main/java/org/openapitools/codegen/config/GeneratorSettings.java
@@ -30,10 +30,10 @@ import java.util.*;
public final class GeneratorSettings implements Serializable {
private static final Logger LOGGER = LoggerFactory.getLogger(GeneratorSettings.class);
- private static String DEFAULT_GIT_HOST = "github.com";
- private static String DEFAULT_GIT_USER_ID = "GIT_USER_ID";
- private static String DEFAULT_GIT_REPO_ID = "GIT_REPO_ID";
- private static String DEFAULT_RELEASE_NOTE = "Minor update";
+ private static final String DEFAULT_GIT_HOST = "github.com";
+ private static final String DEFAULT_GIT_USER_ID = "GIT_USER_ID";
+ private static final String DEFAULT_GIT_REPO_ID = "GIT_REPO_ID";
+ private static final String DEFAULT_RELEASE_NOTE = "Minor update";
private String generatorName;
private String apiPackage;
@@ -48,13 +48,13 @@ public final class GeneratorSettings implements Serializable {
private String artifactVersion;
private String library;
- private ImmutableMap instantiationTypes;
- private ImmutableMap typeMappings;
- private ImmutableMap additionalProperties;
- private ImmutableMap importMappings;
- private ImmutableSet languageSpecificPrimitives;
- private ImmutableMap reservedWordMappings;
- private ImmutableMap serverVariables;
+ private final ImmutableMap instantiationTypes;
+ private final ImmutableMap typeMappings;
+ private final ImmutableMap additionalProperties;
+ private final ImmutableMap importMappings;
+ private final ImmutableSet languageSpecificPrimitives;
+ private final ImmutableMap reservedWordMappings;
+ private final ImmutableMap serverVariables;
private String gitHost;
private String gitUserId;
diff --git a/modules/openapi-generator-core/src/main/java/org/openapitools/codegen/config/WorkflowSettings.java b/modules/openapi-generator-core/src/main/java/org/openapitools/codegen/config/WorkflowSettings.java
index 8d24d3b0a5..c387f43c32 100644
--- a/modules/openapi-generator-core/src/main/java/org/openapitools/codegen/config/WorkflowSettings.java
+++ b/modules/openapi-generator-core/src/main/java/org/openapitools/codegen/config/WorkflowSettings.java
@@ -36,12 +36,13 @@ import java.util.regex.Pattern;
*/
@SuppressWarnings("WeakerAccess")
public class WorkflowSettings {
- private static final AtomicLong lastWarning = new AtomicLong(0);
+
private static final Logger LOGGER = LoggerFactory.getLogger(WorkflowSettings.class);
public static final String DEFAULT_OUTPUT_DIR = ".";
public static final boolean DEFAULT_VERBOSE = false;
public static final boolean DEFAULT_SKIP_OVERWRITE = false;
public static final boolean DEFAULT_REMOVE_OPERATION_ID_PREFIX = false;
+ public static final boolean DEFAULT_SKIP_OPERATION_EXAMPLE = false;
public static final boolean DEFAULT_LOG_TO_STDERR = false;
public static final boolean DEFAULT_VALIDATE_SPEC = true;
public static final boolean DEFAULT_ENABLE_POST_PROCESS_FILE = false;
@@ -56,6 +57,7 @@ public class WorkflowSettings {
private boolean verbose = DEFAULT_VERBOSE;
private boolean skipOverwrite = DEFAULT_SKIP_OVERWRITE;
private boolean removeOperationIdPrefix = DEFAULT_REMOVE_OPERATION_ID_PREFIX;
+ private boolean skipOperationExample = DEFAULT_SKIP_OPERATION_EXAMPLE;
private boolean logToStderr = DEFAULT_LOG_TO_STDERR;
private boolean validateSpec = DEFAULT_VALIDATE_SPEC;
private boolean enablePostProcessFile = DEFAULT_ENABLE_POST_PROCESS_FILE;
@@ -104,6 +106,7 @@ public class WorkflowSettings {
builder.verbose = copy.isVerbose();
builder.skipOverwrite = copy.isSkipOverwrite();
builder.removeOperationIdPrefix = copy.isRemoveOperationIdPrefix();
+ builder.skipOperationExample = copy.isSkipOperationExample();
builder.logToStderr = copy.isLogToStderr();
builder.validateSpec = copy.isValidateSpec();
builder.enablePostProcessFile = copy.isEnablePostProcessFile();
@@ -169,6 +172,15 @@ public class WorkflowSettings {
return removeOperationIdPrefix;
}
+ /**
+ * Indicates whether or not to skip examples defined in the operation.
+ *
+ * @return true if the examples defined in the operation should be skipped.
+ */
+ public boolean isSkipOperationExample() {
+ return skipOperationExample;
+ }
+
/**
* Indicates whether or not the generator's executor will write all log messages (not just errors) to STDOUT. Useful for
* piping the JSON output of debug options (e.g. -DdebugOperations) to an external parser directly while testing a generator.
@@ -284,6 +296,7 @@ public class WorkflowSettings {
private Boolean verbose = DEFAULT_VERBOSE;
private Boolean skipOverwrite = DEFAULT_SKIP_OVERWRITE;
private Boolean removeOperationIdPrefix = DEFAULT_REMOVE_OPERATION_ID_PREFIX;
+ private Boolean skipOperationExample = DEFAULT_SKIP_OPERATION_EXAMPLE;
private Boolean logToStderr = DEFAULT_LOG_TO_STDERR;
private Boolean validateSpec = DEFAULT_VALIDATE_SPEC;
private Boolean enablePostProcessFile = DEFAULT_ENABLE_POST_PROCESS_FILE;
@@ -295,7 +308,7 @@ public class WorkflowSettings {
private String ignoreFileOverride;
// NOTE: All collections must be mutable in the builder, and copied to a new immutable collection in .build()
- private Map globalProperties = new HashMap<>();;
+ private Map globalProperties = new HashMap<>();
private Builder() {
}
@@ -362,6 +375,17 @@ public class WorkflowSettings {
return this;
}
+ /**
+ * Sets the {@code skipOperationExample} and returns a reference to this Builder so that the methods can be chained together.
+ *
+ * @param skipOperationExample the {@code skipOperationExample} to set
+ * @return a reference to this Builder
+ */
+ public Builder withSkipOperationExample(Boolean skipOperationExample) {
+ this.skipOperationExample = skipOperationExample != null ? skipOperationExample : Boolean.valueOf(DEFAULT_REMOVE_OPERATION_ID_PREFIX);
+ return this;
+ }
+
/**
* Sets the {@code logToStderr} and returns a reference to this Builder so that the methods can be chained together.
*
@@ -568,6 +592,7 @@ public class WorkflowSettings {
return isVerbose() == that.isVerbose() &&
isSkipOverwrite() == that.isSkipOverwrite() &&
isRemoveOperationIdPrefix() == that.isRemoveOperationIdPrefix() &&
+ isSkipOperationExample() == that.isSkipOperationExample() &&
isLogToStderr() == that.isLogToStderr() &&
isValidateSpec() == that.isValidateSpec() &&
isEnablePostProcessFile() == that.isEnablePostProcessFile() &&
@@ -590,6 +615,7 @@ public class WorkflowSettings {
isVerbose(),
isSkipOverwrite(),
isRemoveOperationIdPrefix(),
+ isSkipOperationExample(),
isLogToStderr(),
isValidateSpec(),
isGenerateAliasAsModel(),
diff --git a/modules/openapi-generator-gradle-plugin/README.adoc b/modules/openapi-generator-gradle-plugin/README.adoc
index 310fd681dc..7d082a0fb0 100644
--- a/modules/openapi-generator-gradle-plugin/README.adoc
+++ b/modules/openapi-generator-gradle-plugin/README.adoc
@@ -294,6 +294,11 @@ apply plugin: 'org.openapi.generator'
|false
|Remove prefix of operationId, e.g. config_getId => getId.
+|skipOperationExample
+|Boolean
+|false
+|Skip examples defined in the operation
+
|apiFilesConstrainedTo
|List(String)
|None
diff --git a/modules/openapi-generator-gradle-plugin/samples/local-spec/gradle.properties b/modules/openapi-generator-gradle-plugin/samples/local-spec/gradle.properties
index cc9120b6ed..e60e6016e5 100644
--- a/modules/openapi-generator-gradle-plugin/samples/local-spec/gradle.properties
+++ b/modules/openapi-generator-gradle-plugin/samples/local-spec/gradle.properties
@@ -1,3 +1,3 @@
# RELEASE_VERSION
-openApiGeneratorVersion=5.0.1-SNAPSHOT
+openApiGeneratorVersion=5.1.0-SNAPSHOT
# /RELEASE_VERSION
diff --git a/modules/openapi-generator-gradle-plugin/src/main/kotlin/org/openapitools/generator/gradle/plugin/OpenApiGeneratorPlugin.kt b/modules/openapi-generator-gradle-plugin/src/main/kotlin/org/openapitools/generator/gradle/plugin/OpenApiGeneratorPlugin.kt
index 7c053b712b..4563e69e49 100644
--- a/modules/openapi-generator-gradle-plugin/src/main/kotlin/org/openapitools/generator/gradle/plugin/OpenApiGeneratorPlugin.kt
+++ b/modules/openapi-generator-gradle-plugin/src/main/kotlin/org/openapitools/generator/gradle/plugin/OpenApiGeneratorPlugin.kt
@@ -125,6 +125,7 @@ class OpenApiGeneratorPlugin : Plugin {
reservedWordsMappings.set(generate.reservedWordsMappings)
ignoreFileOverride.set(generate.ignoreFileOverride)
removeOperationIdPrefix.set(generate.removeOperationIdPrefix)
+ skipOperationExample.set(generate.skipOperationExample)
apiFilesConstrainedTo.set(generate.apiFilesConstrainedTo)
modelFilesConstrainedTo.set(generate.modelFilesConstrainedTo)
supportingFilesConstrainedTo.set(generate.supportingFilesConstrainedTo)
diff --git a/modules/openapi-generator-gradle-plugin/src/main/kotlin/org/openapitools/generator/gradle/plugin/extensions/OpenApiGeneratorGenerateExtension.kt b/modules/openapi-generator-gradle-plugin/src/main/kotlin/org/openapitools/generator/gradle/plugin/extensions/OpenApiGeneratorGenerateExtension.kt
index b9319cfaa4..4029ab9c43 100644
--- a/modules/openapi-generator-gradle-plugin/src/main/kotlin/org/openapitools/generator/gradle/plugin/extensions/OpenApiGeneratorGenerateExtension.kt
+++ b/modules/openapi-generator-gradle-plugin/src/main/kotlin/org/openapitools/generator/gradle/plugin/extensions/OpenApiGeneratorGenerateExtension.kt
@@ -201,6 +201,11 @@ open class OpenApiGeneratorGenerateExtension(project: Project) {
*/
val removeOperationIdPrefix = project.objects.property()
+ /**
+ * Skip examples defined in the operation
+ */
+ val skipOperationExample = project.objects.property()
+
/**
* Defines which API-related files should be generated. This allows you to create a subset of generated files (or none at all).
*
@@ -333,4 +338,4 @@ open class OpenApiGeneratorGenerateExtension(project: Project) {
skipValidateSpec.set(false)
generateAliasAsModel.set(false)
}
-}
\ No newline at end of file
+}
diff --git a/modules/openapi-generator-gradle-plugin/src/main/kotlin/org/openapitools/generator/gradle/plugin/tasks/GenerateTask.kt b/modules/openapi-generator-gradle-plugin/src/main/kotlin/org/openapitools/generator/gradle/plugin/tasks/GenerateTask.kt
index a7a3f84e26..3de69d41f5 100644
--- a/modules/openapi-generator-gradle-plugin/src/main/kotlin/org/openapitools/generator/gradle/plugin/tasks/GenerateTask.kt
+++ b/modules/openapi-generator-gradle-plugin/src/main/kotlin/org/openapitools/generator/gradle/plugin/tasks/GenerateTask.kt
@@ -304,6 +304,13 @@ open class GenerateTask : DefaultTask() {
@Input
val removeOperationIdPrefix = project.objects.property()
+ /**
+ * Remove examples defined in the operation
+ */
+ @Optional
+ @Input
+ val skipOperationExample = project.objects.property()
+
/**
* Defines which API-related files should be generated. This allows you to create a subset of generated files (or none at all).
*
@@ -615,6 +622,10 @@ open class GenerateTask : DefaultTask() {
configurator.setRemoveOperationIdPrefix(value!!)
}
+ skipOperationExample.ifNotEmpty { value ->
+ configurator.setSkipOperationExample(value!!)
+ }
+
logToStderr.ifNotEmpty { value ->
configurator.setLogToStderr(value)
}
diff --git a/modules/openapi-generator-maven-plugin/README.md b/modules/openapi-generator-maven-plugin/README.md
index f740dbf340..da9dd577b9 100644
--- a/modules/openapi-generator-maven-plugin/README.md
+++ b/modules/openapi-generator-maven-plugin/README.md
@@ -70,6 +70,7 @@ mvn clean compile
| `ignoreFileOverride` | `openapi.generator.maven.plugin.ignoreFileOverride` | specifies the full path to a `.openapi-generator-ignore` used for pattern based overrides of generated outputs
| `httpUserAgent` | `openapi.generator.maven.plugin.httpUserAgent` | Sets custom User-Agent header value
| `removeOperationIdPrefix` | `openapi.generator.maven.plugin.removeOperationIdPrefix` | remove operationId prefix (e.g. user_getName => getName)
+| `skipOperationExample` | `openapi.generator.maven.plugin.skipOperationExample` | skip examples defined in the operation
| `logToStderr` | `openapi.generator.maven.plugin.logToStderr` | write all log messages (not just errors) to STDOUT
| `enablePostProcessFile` | `openapi.generator.maven.plugin.` | enable file post-processing hook
| `skipValidateSpec` | `openapi.generator.maven.plugin.skipValidateSpec` | Whether or not to skip validating the input spec prior to generation. By default, invalid specifications will result in an error.
diff --git a/modules/openapi-generator-maven-plugin/src/main/java/org/openapitools/codegen/plugin/CodeGenMojo.java b/modules/openapi-generator-maven-plugin/src/main/java/org/openapitools/codegen/plugin/CodeGenMojo.java
index 80639e97ff..a697be42e3 100644
--- a/modules/openapi-generator-maven-plugin/src/main/java/org/openapitools/codegen/plugin/CodeGenMojo.java
+++ b/modules/openapi-generator-maven-plugin/src/main/java/org/openapitools/codegen/plugin/CodeGenMojo.java
@@ -73,7 +73,7 @@ import com.google.common.io.Files;
@Mojo(name = "generate", defaultPhase = LifecyclePhase.GENERATE_SOURCES, threadSafe = true)
public class CodeGenMojo extends AbstractMojo {
- private static final Logger LOGGER = LoggerFactory.getLogger(CodeGenMojo.class);
+ private final Logger LOGGER = LoggerFactory.getLogger(CodeGenMojo.class);
/**
* The build context is only avail when running from within eclipse.
@@ -237,6 +237,12 @@ public class CodeGenMojo extends AbstractMojo {
@Parameter(name = "removeOperationIdPrefix", property = "openapi.generator.maven.plugin.removeOperationIdPrefix")
private Boolean removeOperationIdPrefix;
+ /**
+ * To skip examples defined in the operation
+ */
+ @Parameter(name = "skipOperationExample", property = "openapi.generator.maven.plugin.skipOperationExample")
+ private Boolean skipOperationExample;
+
/**
* To write all log messages (not just errors) to STDOUT
*/
@@ -485,6 +491,10 @@ public class CodeGenMojo extends AbstractMojo {
configurator.setRemoveOperationIdPrefix(removeOperationIdPrefix);
}
+ if (skipOperationExample != null) {
+ configurator.setSkipOperationExample(skipOperationExample);
+ }
+
if (isNotEmpty(inputSpec)) {
configurator.setInputSpec(inputSpec);
}
@@ -748,7 +758,10 @@ public class CodeGenMojo extends AbstractMojo {
if (storedInputSpecHashFile.getParent() != null && !new File(storedInputSpecHashFile.getParent()).exists()) {
File parent = new File(storedInputSpecHashFile.getParent());
- parent.mkdirs();
+ if (!parent.mkdirs()) {
+ throw new RuntimeException("Failed to create the folder " + parent.getAbsolutePath() +
+ " to store the checksum of the input spec.");
+ }
}
Files.asCharSink(storedInputSpecHashFile, StandardCharsets.UTF_8).write(inputSpecHash);
@@ -780,7 +793,7 @@ public class CodeGenMojo extends AbstractMojo {
File inputSpecTempFile = inputSpecFile;
if (inputSpecRemoteUrl != null) {
- inputSpecTempFile = File.createTempFile("openapi-spec", ".tmp");
+ inputSpecTempFile = java.nio.file.Files.createTempFile("openapi-spec", ".tmp").toFile();
URLConnection conn = inputSpecRemoteUrl.openConnection();
if (isNotEmpty(auth)) {
@@ -888,4 +901,4 @@ public class CodeGenMojo extends AbstractMojo {
}
}
}
-}
\ No newline at end of file
+}
diff --git a/modules/openapi-generator-online/src/main/java/org/openapitools/codegen/online/service/Generator.java b/modules/openapi-generator-online/src/main/java/org/openapitools/codegen/online/service/Generator.java
index 1ea9af624d..878a33f09b 100644
--- a/modules/openapi-generator-online/src/main/java/org/openapitools/codegen/online/service/Generator.java
+++ b/modules/openapi-generator-online/src/main/java/org/openapitools/codegen/online/service/Generator.java
@@ -35,6 +35,7 @@ import org.springframework.http.HttpStatus;
import org.springframework.web.server.ResponseStatusException;
import java.io.File;
+import java.nio.file.Files;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
@@ -181,9 +182,7 @@ public class Generator {
private static File getTmpFolder() {
try {
- File outputFolder = File.createTempFile("codegen-", "-tmp");
- outputFolder.delete();
- outputFolder.mkdir();
+ File outputFolder = Files.createTempDirectory("codegen-tmp").toFile();
outputFolder.deleteOnExit();
return outputFolder;
} catch (Exception e) {
diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/CodegenConfig.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/CodegenConfig.java
index d3b5250708..f47d98c8b1 100644
--- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/CodegenConfig.java
+++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/CodegenConfig.java
@@ -214,6 +214,10 @@ public interface CodegenConfig {
void setRemoveOperationIdPrefix(boolean removeOperationIdPrefix);
+ boolean isSkipOperationExample();
+
+ void setSkipOperationExample(boolean skipOperationExample);
+
public boolean isHideGenerationTimestamp();
public void setHideGenerationTimestamp(boolean hideGenerationTimestamp);
diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/CodegenConstants.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/CodegenConstants.java
index d576eea2c4..45759aba14 100644
--- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/CodegenConstants.java
+++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/CodegenConstants.java
@@ -309,6 +309,9 @@ public class CodegenConstants {
public static final String REMOVE_OPERATION_ID_PREFIX = "removeOperationIdPrefix";
public static final String REMOVE_OPERATION_ID_PREFIX_DESC = "Remove prefix of operationId, e.g. config_getId => getId";
+ public static final String SKIP_OPERATION_EXAMPLE = "skipOperationExample";
+ public static final String SKIP_OPERATION_EXAMPLE_DESC = "Skip examples defined in operations to avoid out of memory errors.";
+
public static final String STRIP_PACKAGE_NAME = "stripPackageName";
public static final String STRIP_PACKAGE_NAME_DESC = "Whether to strip leading dot-separated packages from generated model classes";
diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/CodegenParameter.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/CodegenParameter.java
index 811d48d324..6cbaec8b74 100644
--- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/CodegenParameter.java
+++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/CodegenParameter.java
@@ -27,7 +27,7 @@ import java.util.*;
public class CodegenParameter implements IJsonSchemaValidationProperties {
public boolean isFormParam, isQueryParam, isPathParam, isHeaderParam,
isCookieParam, isBodyParam, isContainer,
- isCollectionFormatMulti, isPrimitiveType, isModel, isExplode;
+ isCollectionFormatMulti, isPrimitiveType, isModel, isExplode, isDeepObject;
public String baseName, paramName, dataType, datatypeWithEnum, dataFormat, contentType,
collectionFormat, description, unescapedDescription, baseType, defaultValue, enumName, style;
@@ -195,6 +195,7 @@ public class CodegenParameter implements IJsonSchemaValidationProperties {
output.isMap = this.isMap;
output.isExplode = this.isExplode;
output.style = this.style;
+ output.isDeepObject = this.isDeepObject;
output.contentType = this.contentType;
return output;
@@ -202,7 +203,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, enumName, style, 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, required, getMaximum(), getExclusiveMaximum(), getMinimum(), getExclusiveMinimum(), getMaxLength(), getMinLength(), getPattern(), getMaxItems(), getMinItems(), getUniqueItems(), contentType, multipleOf, isNull);
+ return Objects.hash(isFormParam, isQueryParam, isPathParam, isHeaderParam, isCookieParam, isBodyParam, isContainer, isCollectionFormatMulti, isPrimitiveType, isModel, isExplode, baseName, paramName, dataType, datatypeWithEnum, dataFormat, collectionFormat, description, unescapedDescription, baseType, defaultValue, enumName, style, isDeepObject, 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, required, getMaximum(), getExclusiveMaximum(), getMinimum(), getExclusiveMinimum(), getMaxLength(), getMinLength(), getPattern(), getMaxItems(), getMinItems(), getUniqueItems(), contentType, multipleOf, isNull);
}
@Override
@@ -262,6 +263,7 @@ public class CodegenParameter implements IJsonSchemaValidationProperties {
Objects.equals(defaultValue, that.defaultValue) &&
Objects.equals(enumName, that.enumName) &&
Objects.equals(style, that.style) &&
+ Objects.equals(isDeepObject, that.isDeepObject) &&
Objects.equals(example, that.example) &&
Objects.equals(jsonSchema, that.jsonSchema) &&
Objects.equals(_enum, that._enum) &&
@@ -311,6 +313,7 @@ public class CodegenParameter implements IJsonSchemaValidationProperties {
sb.append(", defaultValue='").append(defaultValue).append('\'');
sb.append(", enumName='").append(enumName).append('\'');
sb.append(", style='").append(style).append('\'');
+ sb.append(", deepObject='").append(isDeepObject).append('\'');
sb.append(", example='").append(example).append('\'');
sb.append(", jsonSchema='").append(jsonSchema).append('\'');
sb.append(", isString=").append(isString);
diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/DefaultCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/DefaultCodegen.java
index 1d30af652a..02a5a06e9b 100644
--- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/DefaultCodegen.java
+++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/DefaultCodegen.java
@@ -78,7 +78,7 @@ import static org.openapitools.codegen.utils.OnceLogger.once;
import static org.openapitools.codegen.utils.StringUtils.*;
public class DefaultCodegen implements CodegenConfig {
- private static final Logger LOGGER = LoggerFactory.getLogger(DefaultCodegen.class);
+ private final Logger LOGGER = LoggerFactory.getLogger(DefaultCodegen.class);
public static FeatureSet DefaultFeatureSet;
@@ -142,10 +142,10 @@ public class DefaultCodegen implements CodegenConfig {
protected GeneratorMetadata generatorMetadata;
protected String inputSpec;
protected String outputFolder = "";
- protected Set defaultIncludes = new HashSet();
- protected Map typeMapping = new HashMap();
- protected Map instantiationTypes = new HashMap();
- protected Set reservedWords = new HashSet();
+ protected Set defaultIncludes;
+ protected Map typeMapping;
+ protected Map instantiationTypes;
+ protected Set reservedWords;
protected Set languageSpecificPrimitives = new HashSet();
protected Map importMapping = new HashMap();
protected String modelPackage = "", apiPackage = "", fileSuffix;
@@ -177,6 +177,11 @@ public class DefaultCodegen implements CodegenConfig {
protected List cliOptions = new ArrayList();
protected boolean skipOverwrite;
protected boolean removeOperationIdPrefix;
+ protected boolean skipOperationExample;
+
+ protected final static Pattern JSON_MIME_PATTERN = Pattern.compile("(?i)application\\/json(;.*)?");
+ protected final static Pattern JSON_VENDOR_MIME_PATTERN = Pattern.compile("(?i)application\\/vnd.(.*)+json(;.*)?");
+ private static final Pattern COMMON_PREFIX_ENUM_NAME = Pattern.compile("[a-zA-Z0-9]+\\z");
/**
* True if the code generator supports multiple class inheritance.
@@ -314,36 +319,41 @@ public class DefaultCodegen implements CodegenConfig {
}
if (additionalProperties.containsKey(CodegenConstants.REMOVE_OPERATION_ID_PREFIX)) {
- this.setRemoveOperationIdPrefix(Boolean.valueOf(additionalProperties
+ this.setRemoveOperationIdPrefix(Boolean.parseBoolean(additionalProperties
.get(CodegenConstants.REMOVE_OPERATION_ID_PREFIX).toString()));
}
+ if (additionalProperties.containsKey(CodegenConstants.SKIP_OPERATION_EXAMPLE)) {
+ this.setSkipOperationExample(Boolean.parseBoolean(additionalProperties
+ .get(CodegenConstants.SKIP_OPERATION_EXAMPLE).toString()));
+ }
+
if (additionalProperties.containsKey(CodegenConstants.DOCEXTENSION)) {
this.setDocExtension(String.valueOf(additionalProperties
.get(CodegenConstants.DOCEXTENSION).toString()));
}
if (additionalProperties.containsKey(CodegenConstants.ENABLE_POST_PROCESS_FILE)) {
- this.setEnablePostProcessFile(Boolean.valueOf(additionalProperties
+ this.setEnablePostProcessFile(Boolean.parseBoolean(additionalProperties
.get(CodegenConstants.ENABLE_POST_PROCESS_FILE).toString()));
}
if (additionalProperties.containsKey(CodegenConstants.GENERATE_ALIAS_AS_MODEL)) {
- ModelUtils.setGenerateAliasAsModel(Boolean.valueOf(additionalProperties
+ ModelUtils.setGenerateAliasAsModel(Boolean.parseBoolean(additionalProperties
.get(CodegenConstants.GENERATE_ALIAS_AS_MODEL).toString()));
}
if (additionalProperties.containsKey(CodegenConstants.REMOVE_ENUM_VALUE_PREFIX)) {
- this.setRemoveEnumValuePrefix(Boolean.valueOf(additionalProperties
+ this.setRemoveEnumValuePrefix(Boolean.parseBoolean(additionalProperties
.get(CodegenConstants.REMOVE_ENUM_VALUE_PREFIX).toString()));
}
if (additionalProperties.containsKey(CodegenConstants.LEGACY_DISCRIMINATOR_BEHAVIOR)) {
- this.setLegacyDiscriminatorBehavior(Boolean.valueOf(additionalProperties
+ this.setLegacyDiscriminatorBehavior(Boolean.parseBoolean(additionalProperties
.get(CodegenConstants.LEGACY_DISCRIMINATOR_BEHAVIOR).toString()));
}
if (additionalProperties.containsKey(CodegenConstants.DISALLOW_ADDITIONAL_PROPERTIES_IF_NOT_PRESENT)) {
- this.setDisallowAdditionalPropertiesIfNotPresent(Boolean.valueOf(additionalProperties
+ this.setDisallowAdditionalPropertiesIfNotPresent(Boolean.parseBoolean(additionalProperties
.get(CodegenConstants.DISALLOW_ADDITIONAL_PROPERTIES_IF_NOT_PRESENT).toString()));
}
}
@@ -396,10 +406,9 @@ public class DefaultCodegen implements CodegenConfig {
Map modelValue = new HashMap<>(additionalProperties());
modelValue.put("model", cm);
- List modelsValue = Arrays.asList(modelValue);
- List> importsValue = new ArrayList>();
+ List> importsValue = new ArrayList<>();
Map objsValue = new HashMap<>();
- objsValue.put("models", modelsValue);
+ objsValue.put("models", Collections.singletonList(modelValue));
objsValue.put("package", modelPackage());
objsValue.put("imports", importsValue);
objsValue.put("classname", cm.classname);
@@ -410,7 +419,7 @@ public class DefaultCodegen implements CodegenConfig {
// Gather data from all the models that contain oneOf into OneOfImplementorAdditionalData classes
// (see docstring of that class to find out what information is gathered and why)
Map additionalDataMap = new HashMap();
- for (Map.Entry modelsEntry : objs.entrySet()) {
+ for (Map.Entry modelsEntry : objs.entrySet()) {
Map modelsAttrs = (Map) modelsEntry.getValue();
List models = (List) modelsAttrs.get("models");
List> modelsImports = (List>) modelsAttrs.getOrDefault("imports", new ArrayList>());
@@ -432,7 +441,7 @@ public class DefaultCodegen implements CodegenConfig {
}
// Add all the data from OneOfImplementorAdditionalData classes to the implementing models
- for (Map.Entry modelsEntry : objs.entrySet()) {
+ for (Map.Entry modelsEntry : objs.entrySet()) {
Map modelsAttrs = (Map) modelsEntry.getValue();
List models = (List) modelsAttrs.get("models");
List> imports = (List>) modelsAttrs.get("imports");
@@ -458,10 +467,8 @@ public class DefaultCodegen implements CodegenConfig {
protected Map getModelNameToSchemaCache() {
if (modelNameToSchemaCache == null) {
// Create a cache to efficiently lookup schema based on model name.
- Map m = new HashMap();
- ModelUtils.getSchemas(openAPI).forEach((key, schema) -> {
- m.put(toModelName(key), schema);
- });
+ Map m = new HashMap<>();
+ ModelUtils.getSchemas(openAPI).forEach((key, schema) -> m.put(toModelName(key), schema));
modelNameToSchemaCache = Collections.unmodifiableMap(m);
}
return modelNameToSchemaCache;
@@ -502,7 +509,7 @@ public class DefaultCodegen implements CodegenConfig {
cm.setParentModel(allModels.get(cm.getParent()));
}
if (cm.getInterfaces() != null && !cm.getInterfaces().isEmpty()) {
- cm.setInterfaceModels(new ArrayList(cm.getInterfaces().size()));
+ cm.setInterfaceModels(new ArrayList<>(cm.getInterfaces().size()));
for (String intf : cm.getInterfaces()) {
CodegenModel intfModel = allModels.get(intf);
if (intfModel != null) {
@@ -520,7 +527,7 @@ public class DefaultCodegen implements CodegenConfig {
// TODO Determine what to do if the parent discriminator name == the grandparent discriminator name
while (parent != null) {
if (parent.getChildren() == null) {
- parent.setChildren(new ArrayList());
+ parent.setChildren(new ArrayList<>());
}
parent.getChildren().add(cm);
parent.hasChildren = true;
@@ -569,13 +576,13 @@ public class DefaultCodegen implements CodegenConfig {
}
return prop.dataType == null ? null : prop;
})
- .filter(prop -> prop != null)
+ .filter(Objects::nonNull)
.collect(Collectors.toList());
}
private void setCircularReferencesOnProperties(final String root,
final Map> dependencyMap) {
- dependencyMap.getOrDefault(root, new ArrayList<>()).stream()
+ dependencyMap.getOrDefault(root, new ArrayList<>())
.forEach(prop -> {
final List unvisited =
Collections.singletonList(prop.isContainer ? prop.items.dataType : prop.dataType);
@@ -680,7 +687,8 @@ public class DefaultCodegen implements CodegenConfig {
String prefix = StringUtils.getCommonPrefix(listStr);
// exclude trailing characters that should be part of a valid variable
// e.g. ["status-on", "status-off"] => "status-" (not "status-o")
- return prefix.replaceAll("[a-zA-Z0-9]+\\z", "");
+ final Matcher matcher = COMMON_PREFIX_ENUM_NAME.matcher(prefix);
+ return matcher.replaceAll("");
} catch (ArrayStoreException e) {
// do nothing, just return default value
}
@@ -1622,7 +1630,7 @@ public class DefaultCodegen implements CodegenConfig {
} else if (Parameter.StyleEnum.SPACEDELIMITED.equals(qp.getStyle())) {
paramPart.append("%20");
} else {
- LOGGER.warn("query parameter '" + param.getName() + "style not support: " + qp.getStyle());
+ LOGGER.warn("query parameter '{}' style not support: {}", param.getName(), qp.getStyle());
}
} else {
paramPart.append(param.getName());
@@ -1998,7 +2006,7 @@ public class DefaultCodegen implements CodegenConfig {
}
return getAlias(schemaName);
} else {
- LOGGER.warn("Error obtaining the datatype from ref:" + unaliasSchema.get$ref() + ". Default to 'object'");
+ LOGGER.warn("Error obtaining the datatype from ref: {}. Default to 'object'", unaliasSchema.get$ref());
return "object";
}
} else { // primitive type or model
@@ -2086,7 +2094,7 @@ public class DefaultCodegen implements CodegenConfig {
return "AnyType";
} else if (StringUtils.isNotEmpty(schema.getType())) {
if (!importMapping.containsKey(schema.getType())) {
- LOGGER.warn("Unknown type found in the schema: " + schema.getType());
+ LOGGER.warn("Unknown type found in the schema: {}", schema.getType());
}
return schema.getType();
}
@@ -2793,10 +2801,10 @@ public class DefaultCodegen implements CodegenConfig {
* @return the list of oneOf and anyOf MappedModel that need to be added to the discriminator map
*/
protected List getOneOfAnyOfDescendants(String composedSchemaName, String discPropName, ComposedSchema c, OpenAPI openAPI) {
- ArrayList> listOLists = new ArrayList>();
+ ArrayList> listOLists = new ArrayList<>();
listOLists.add(c.getOneOf());
listOLists.add(c.getAnyOf());
- List descendentSchemas = new ArrayList();
+ List descendentSchemas = new ArrayList<>();
for (List schemaList : listOLists) {
if (schemaList == null) {
continue;
@@ -3055,11 +3063,11 @@ public class DefaultCodegen implements CodegenConfig {
LOGGER.error("Undefined property/schema for `{}`. Default to type:string.", name);
return null;
}
- LOGGER.debug("debugging fromProperty for " + name + " : " + p);
+ LOGGER.debug("debugging fromProperty for {} : {}", name, p);
NamedSchema ns = new NamedSchema(name, p);
CodegenProperty cpc = schemaCodegenPropertyCache.get(ns);
if (cpc != null) {
- LOGGER.debug("Cached fromProperty for " + name + " : " + p.getName());
+ LOGGER.debug("Cached fromProperty for {} : {}", name, p.getName());
return cpc;
}
// unalias schema
@@ -3311,8 +3319,8 @@ public class DefaultCodegen implements CodegenConfig {
property.isModel = (ModelUtils.isComposedSchema(refOrCurrent) || ModelUtils.isObjectSchema(refOrCurrent)) && ModelUtils.isModel(refOrCurrent);
}
- addVarsRequiredVarsAdditionaProps(p, property);
- LOGGER.debug("debugging from property return: " + property);
+ addVarsRequiredVarsAdditionalProps(p, property);
+ LOGGER.debug("debugging from property return: {}", property);
schemaCodegenPropertyCache.put(ns, property);
return property;
}
@@ -3325,7 +3333,9 @@ public class DefaultCodegen implements CodegenConfig {
*/
protected void updatePropertyForArray(CodegenProperty property, CodegenProperty innerProperty) {
if (innerProperty == null) {
- LOGGER.warn("skipping invalid array property " + Json.pretty(property));
+ if(LOGGER.isWarnEnabled()) {
+ LOGGER.warn("skipping invalid array property {}", Json.pretty(property));
+ }
return;
}
property.dataFormat = innerProperty.dataFormat;
@@ -3358,7 +3368,9 @@ public class DefaultCodegen implements CodegenConfig {
*/
protected void updatePropertyForMap(CodegenProperty property, CodegenProperty innerProperty) {
if (innerProperty == null) {
- LOGGER.warn("skipping invalid map property " + Json.pretty(property));
+ if(LOGGER.isWarnEnabled()) {
+ LOGGER.warn("skipping invalid map property {}", Json.pretty(property));
+ }
return;
}
if (!languageSpecificPrimitives.contains(innerProperty.baseType)) {
@@ -3407,7 +3419,7 @@ public class DefaultCodegen implements CodegenConfig {
protected Map getInnerEnumAllowableValues(CodegenProperty property) {
CodegenProperty currentProperty = getMostInnerItems(property);
- return currentProperty == null ? new HashMap() : currentProperty.allowableValues;
+ return currentProperty == null ? new HashMap<>() : currentProperty.allowableValues;
}
/**
@@ -3547,14 +3559,18 @@ public class DefaultCodegen implements CodegenConfig {
}
}
- // generate examples
- String exampleStatusCode = "200";
- for (String key : operation.getResponses().keySet()) {
- if (operation.getResponses().get(key) == methodResponse && !key.equals("default")) {
- exampleStatusCode = key;
+ // check skipOperationExample, which can be set to true to avoid out of memory errors for large spec
+ if (!isSkipOperationExample()) {
+ // generate examples
+ String exampleStatusCode = "200";
+ for (String key : operation.getResponses().keySet()) {
+ if (operation.getResponses().get(key) == methodResponse && !key.equals("default")) {
+ exampleStatusCode = key;
+ }
}
+ op.examples = new ExampleGenerator(schemas, this.openAPI).generateFromResponseSchema(exampleStatusCode, responseSchema, getProducesInfo(this.openAPI, operation));
}
- op.examples = new ExampleGenerator(schemas, this.openAPI).generateFromResponseSchema(exampleStatusCode, responseSchema, getProducesInfo(this.openAPI, operation));
+
op.defaultResponse = toDefaultValue(responseSchema);
op.returnType = cm.dataType;
op.returnFormat = cm.dataFormat;
@@ -3604,7 +3620,7 @@ public class DefaultCodegen implements CodegenConfig {
String httpMethod,
Operation operation,
List servers) {
- LOGGER.debug("fromOperation => operation: " + operation);
+ LOGGER.debug("fromOperation => operation: {}", operation);
if (operation == null)
throw new RuntimeException("operation cannot be null in fromOperation");
@@ -3768,7 +3784,7 @@ public class DefaultCodegen implements CodegenConfig {
// ensure unique params
if (ensureUniqueParams) {
- if (!isParameterNameUnique(p, allParams)) {
+ while (!isParameterNameUnique(p, allParams)) {
p.paramName = generateNextName(p.paramName);
}
}
@@ -3784,7 +3800,7 @@ public class DefaultCodegen implements CodegenConfig {
} else if (param instanceof CookieParameter || "cookie".equalsIgnoreCase(param.getIn())) {
cookieParams.add(p.copy());
} else {
- LOGGER.warn("Unknown parameter type " + p.baseType + " for " + p.baseName);
+ LOGGER.warn("Unknown parameter type {} for {}", p.baseType, p.baseName);
}
}
@@ -3794,7 +3810,7 @@ public class DefaultCodegen implements CodegenConfig {
if (!prependFormOrBodyParameters) {
for (CodegenParameter cp : formParams) {
if (ensureUniqueParams) {
- if (!isParameterNameUnique(cp, allParams)) {
+ while (!isParameterNameUnique(cp, allParams)) {
cp.paramName = generateNextName(cp.paramName);
}
}
@@ -3803,7 +3819,7 @@ public class DefaultCodegen implements CodegenConfig {
for (CodegenParameter cp : bodyParams) {
if (ensureUniqueParams) {
- if (!isParameterNameUnique(cp, allParams)) {
+ while (!isParameterNameUnique(cp, allParams)) {
cp.paramName = generateNextName(cp.paramName);
}
}
@@ -4021,7 +4037,7 @@ public class DefaultCodegen implements CodegenConfig {
} else if (Boolean.TRUE.equals(cp.isAnyType)) {
r.isAnyType = true;
} else {
- LOGGER.debug("Property type is not primitive: " + cp.dataType);
+ LOGGER.debug("Property type is not primitive: {}", cp.dataType);
}
if (cp.isContainer) {
@@ -4037,7 +4053,7 @@ public class DefaultCodegen implements CodegenConfig {
r.primitiveType = (r.baseType == null || languageSpecificPrimitives().contains(r.baseType));
- addVarsRequiredVarsAdditionaProps(responseSchema, r);
+ addVarsRequiredVarsAdditionalProps(responseSchema, r);
}
if (r.baseType == null) {
@@ -4133,8 +4149,8 @@ public class DefaultCodegen implements CodegenConfig {
codegenParameter.jsonSchema = Json.pretty(parameter);
if (GlobalSettings.getProperty("debugParser") != null) {
- LOGGER.info("working on Parameter " + parameter.getName());
- LOGGER.info("JSON schema: " + codegenParameter.jsonSchema);
+ LOGGER.info("working on Parameter {}", parameter.getName());
+ LOGGER.info("JSON schema: {}", codegenParameter.jsonSchema);
}
if (parameter.getExtensions() != null && !parameter.getExtensions().isEmpty()) {
@@ -4159,7 +4175,7 @@ public class DefaultCodegen implements CodegenConfig {
if (parameterSchema != null) {
parameterSchema = unaliasSchema(parameterSchema, Collections.emptyMap());
if (parameterSchema == null) {
- LOGGER.warn("warning! Schema not found for parameter \"" + parameter.getName() + "\", using String");
+ LOGGER.warn("warning! Schema not found for parameter \" {} \", using String", parameter.getName());
parameterSchema = new StringSchema().description("//TODO automatically added by openapi-generator due to missing type definition.");
}
ModelUtils.syncValidationProperties(parameterSchema, codegenParameter);
@@ -4173,6 +4189,7 @@ public class DefaultCodegen implements CodegenConfig {
if (parameter.getStyle() != null) {
codegenParameter.style = parameter.getStyle().toString();
+ codegenParameter.isDeepObject = Parameter.StyleEnum.DEEPOBJECT == parameter.getStyle();
}
// the default value is false
@@ -4307,10 +4324,10 @@ public class DefaultCodegen implements CodegenConfig {
codegenParameter.pattern != null || codegenParameter.multipleOf != null) {
codegenParameter.hasValidation = true;
}
- addVarsRequiredVarsAdditionaProps(parameterSchema, codegenParameter);
+ addVarsRequiredVarsAdditionalProps(parameterSchema, codegenParameter);
} else {
- LOGGER.error("ERROR! Not handling " + parameter + " as Body Parameter at the moment");
+ LOGGER.error("Not handling {} as Body Parameter at the moment", parameter);
}
if (parameter instanceof QueryParameter || "query".equalsIgnoreCase(parameter.getIn())) {
@@ -4323,7 +4340,7 @@ public class DefaultCodegen implements CodegenConfig {
} else if (parameter instanceof CookieParameter || "cookie".equalsIgnoreCase(parameter.getIn())) {
codegenParameter.isCookieParam = true;
} else {
- LOGGER.warn("Unknown parameter type: " + parameter.getName());
+ LOGGER.warn("Unknown parameter type: {}", parameter.getName());
}
// default to UNKNOWN_PARAMETER_NAME if paramName is null
@@ -4332,12 +4349,25 @@ public class DefaultCodegen implements CodegenConfig {
codegenParameter.paramName = "UNKNOWN_PARAMETER_NAME";
}
+ if (codegenParameter.isQueryParam && codegenParameter.isDeepObject) {
+ Schema schema = ModelUtils.getSchema(openAPI, codegenParameter.dataType);
+ codegenParameter.items = fromProperty(codegenParameter.paramName, schema);
+ Map> properties = schema.getProperties();
+ codegenParameter.items.vars =
+ properties.entrySet().stream()
+ .map(entry -> {
+ CodegenProperty property = fromProperty(entry.getKey(), entry.getValue());
+ property.baseName = codegenParameter.baseName + "[" + entry.getKey() + "]";
+ return property;
+ }).collect(Collectors.toList());
+ }
+
// set the parameter example value
// should be overridden by lang codegen
setParameterExampleValue(codegenParameter, parameter);
postProcessParameter(codegenParameter);
- LOGGER.debug("debugging codegenParameter return: " + codegenParameter);
+ LOGGER.debug("debugging codegenParameter return: {}", codegenParameter);
return codegenParameter;
}
@@ -4528,7 +4558,7 @@ public class DefaultCodegen implements CodegenConfig {
}
}
operationId = sanitizeName(builder.toString());
- LOGGER.warn("Empty operationId found for path: " + httpMethod + " " + path + ". Renamed to auto-generated operationId: " + operationId);
+ LOGGER.warn("Empty operationId found for path: {} {}. Renamed to auto-generated operationId: {}", httpMethod, path, operationId);
}
return operationId;
}
@@ -4575,7 +4605,7 @@ public class DefaultCodegen implements CodegenConfig {
Schema schema;
if (header.getSchema() == null) {
- LOGGER.warn("No schema defined for Header '" + headerEntry.getKey() + "', using a String schema");
+ LOGGER.warn("No schema defined for Header '{}', using a String schema", headerEntry.getKey());
schema = new StringSchema();
} else {
schema = header.getSchema();
@@ -4940,10 +4970,18 @@ public class DefaultCodegen implements CodegenConfig {
return removeOperationIdPrefix;
}
+ public boolean isSkipOperationExample() {
+ return skipOperationExample;
+ }
+
public void setRemoveOperationIdPrefix(boolean removeOperationIdPrefix) {
this.removeOperationIdPrefix = removeOperationIdPrefix;
}
+ public void setSkipOperationExample(boolean skipOperationExample) {
+ this.skipOperationExample = skipOperationExample;
+ }
+
public boolean isHideGenerationTimestamp() {
return hideGenerationTimestamp;
}
@@ -5304,7 +5342,7 @@ public class DefaultCodegen implements CodegenConfig {
} else if (Boolean.TRUE.equals(property.isAnyType)) {
parameter.isAnyType = true;
} else {
- LOGGER.debug("Property type is not primitive: " + property.dataType);
+ LOGGER.debug("Property type is not primitive: {}", property.dataType);
}
if (Boolean.TRUE.equals(property.isFile)) {
@@ -5475,7 +5513,7 @@ public class DefaultCodegen implements CodegenConfig {
public boolean convertPropertyToBoolean(String propertyKey) {
final Object booleanValue = additionalProperties.get(propertyKey);
- Boolean result = Boolean.FALSE;
+ boolean result = Boolean.FALSE;
if (booleanValue instanceof Boolean) {
result = (Boolean) booleanValue;
} else if (booleanValue instanceof String) {
@@ -5504,7 +5542,6 @@ public class DefaultCodegen implements CodegenConfig {
if (flow.getScopes() != null && !flow.getScopes().isEmpty()) {
List> scopes = new ArrayList<>();
- int count = 0, numScopes = flow.getScopes().size();
for (Map.Entry scopeEntry : flow.getScopes().entrySet()) {
Map scope = new HashMap<>();
scope.put("scope", scopeEntry.getKey());
@@ -5523,7 +5560,6 @@ public class DefaultCodegen implements CodegenConfig {
Set consumes = requestBody.getContent().keySet();
List> mediaTypeList = new ArrayList<>();
- int count = 0;
for (String key : consumes) {
Map mediaType = new HashMap<>();
if ("*/*".equals(key)) {
@@ -5594,13 +5630,12 @@ public class DefaultCodegen implements CodegenConfig {
existingMediaTypes.add(mediaType.get("mediaType"));
}
- int count = 0;
for (String key : produces) {
// escape quotation to avoid code injection, "*/*" is a special case, do nothing
String encodedKey = "*/*".equals(key) ? key : escapeText(escapeQuotationMark(key));
//Only unique media types should be added to "produces"
if (!existingMediaTypes.contains(encodedKey)) {
- Map mediaType = new HashMap();
+ Map mediaType = new HashMap<>();
mediaType.put("mediaType", encodedKey);
codegenOperation.produces.add(mediaType);
codegenOperation.hasProduces = Boolean.TRUE;
@@ -5664,8 +5699,8 @@ public class DefaultCodegen implements CodegenConfig {
}
public List fromRequestBodyToFormParameters(RequestBody body, Set imports) {
- List parameters = new ArrayList();
- LOGGER.debug("debugging fromRequestBodyToFormParameters= " + body);
+ List parameters = new ArrayList<>();
+ LOGGER.debug("debugging fromRequestBodyToFormParameters= {}", body);
Schema schema = ModelUtils.getSchemaFromRequestBody(body);
schema = ModelUtils.getReferencedSchema(this.openAPI, schema);
List allRequired = new ArrayList();
@@ -5674,7 +5709,7 @@ public class DefaultCodegen implements CodegenConfig {
if (!properties.isEmpty()) {
for (Map.Entry entry : properties.entrySet()) {
- CodegenParameter codegenParameter = CodegenModelFactory.newInstance(CodegenModelType.PARAMETER);
+ CodegenParameter codegenParameter;
// key => property name
// value => property schema
Schema s = entry.getValue();
@@ -5696,7 +5731,7 @@ public class DefaultCodegen implements CodegenConfig {
if (codegenParameter.baseType != null && codegenParameter.enumName != null) {
codegenParameter.datatypeWithEnum = codegenParameter.dataType.replace(codegenParameter.baseType, codegenParameter.enumName);
} else {
- LOGGER.warn("Could not compute datatypeWithEnum from " + codegenParameter.baseType + ", " + codegenParameter.enumName);
+ LOGGER.warn("Could not compute datatypeWithEnum from {}, {}", codegenParameter.baseType, codegenParameter.enumName);
}
//TODO fix collectformat for form parameters
//collectionFormat = getCollectionFormat(s);
@@ -5866,7 +5901,7 @@ public class DefaultCodegen implements CodegenConfig {
"It could be due to form parameter defined in OpenAPI v2 spec with incorrect consumes. " +
"A correct 'consumes' for form parameters should be " +
"'application/x-www-form-urlencoded' or 'multipart/?'");
- LOGGER.warn("schema: " + schema);
+ LOGGER.warn("schema: {}", schema);
LOGGER.warn("codegenModel is null. Default to UNKNOWN_BASE_TYPE");
codegenModelName = "UNKNOWN_BASE_TYPE";
codegenModelDescription = "UNKNOWN_DESCRIPTION";
@@ -5912,7 +5947,7 @@ public class DefaultCodegen implements CodegenConfig {
}
String name = null;
- LOGGER.debug("Request body = " + body);
+ LOGGER.debug("Request body = {}", body);
Schema schema = ModelUtils.getSchemaFromRequestBody(body);
if (schema == null) {
throw new RuntimeException("Request body cannot be null. Possible cause: missing schema in body parameter (OAS v2): " + body);
@@ -6065,7 +6100,7 @@ public class DefaultCodegen implements CodegenConfig {
setParameterNullable(codegenParameter, codegenProperty);
}
- addVarsRequiredVarsAdditionaProps(schema, codegenParameter);
+ addVarsRequiredVarsAdditionalProps(schema, codegenParameter);
addJsonSchemaForBodyRequestInCaseItsNotPresent(codegenParameter, body);
// set the parameter's example value
@@ -6075,7 +6110,7 @@ public class DefaultCodegen implements CodegenConfig {
return codegenParameter;
}
- private void addVarsRequiredVarsAdditionaProps(Schema schema, IJsonSchemaValidationProperties property){
+ private void addVarsRequiredVarsAdditionalProps(Schema schema, IJsonSchemaValidationProperties property){
if (!"object".equals(schema.getType())) {
return;
}
@@ -6105,7 +6140,6 @@ public class DefaultCodegen implements CodegenConfig {
CodegenProperty cp = fromProperty("", (Schema) schema.getAdditionalProperties());
property.setAdditionalProperties(cp);
}
- return;
}
private void addJsonSchemaForBodyRequestInCaseItsNotPresent(CodegenParameter codegenParameter, RequestBody body) {
@@ -6225,7 +6259,9 @@ public class DefaultCodegen implements CodegenConfig {
codegenServerVariable.value = value;
if (enums != null && !enums.isEmpty() && !enums.contains(value)) {
- LOGGER.warn("Variable override of '{}' is not listed in the enum of allowed values ({}).", value, StringUtils.join(enums, ","));
+ if(LOGGER.isWarnEnabled()) { // prevents calculating StringUtils.join when debug isn't enabled
+ LOGGER.warn("Variable override of '{}' is not listed in the enum of allowed values ({}).", value, StringUtils.join(enums, ","));
+ }
}
} else {
codegenServerVariable.value = variable.getDefault();
@@ -6365,7 +6401,7 @@ public class DefaultCodegen implements CodegenConfig {
CodegenModel cm = new CodegenModel();
- cm.discriminator = createDiscriminator("", (Schema) cs, openAPI);
+ cm.discriminator = createDiscriminator("", cs, openAPI);
if (!this.getLegacyDiscriminatorBehavior()) {
cm.addDiscriminatorMappedModelsImports();
}
@@ -6542,9 +6578,6 @@ public class DefaultCodegen implements CodegenConfig {
return ModelUtils.getAdditionalProperties(openAPI, schema);
}
- final protected static Pattern JSON_MIME_PATTERN = Pattern.compile("(?i)application\\/json(;.*)?");
- final protected static Pattern JSON_VENDOR_MIME_PATTERN = Pattern.compile("(?i)application\\/vnd.(.*)+json(;.*)?");
-
/**
* Check if the given MIME is a JSON MIME.
* JSON MIME examples:
diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/DefaultGenerator.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/DefaultGenerator.java
index e752c710c9..9fde6eaa04 100644
--- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/DefaultGenerator.java
+++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/DefaultGenerator.java
@@ -832,9 +832,8 @@ public class DefaultGenerator implements Generator {
@Override
public List generate() {
-
if (openAPI == null) {
- throw new RuntimeException("missing OpenAPI input!");
+ throw new RuntimeException("Issues with the OpenAPI input. Possible causes: invalid/missing spec, malformed JSON/YAML files, etc.");
}
if (config == null) {
diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/InlineModelResolver.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/InlineModelResolver.java
index 95aaf46b6f..3ba38b581a 100644
--- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/InlineModelResolver.java
+++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/InlineModelResolver.java
@@ -52,7 +52,7 @@ public class InlineModelResolver {
structureMapper.writer(new DefaultPrettyPrinter());
}
- static final Logger LOGGER = LoggerFactory.getLogger(InlineModelResolver.class);
+ final Logger LOGGER = LoggerFactory.getLogger(InlineModelResolver.class);
void flatten(OpenAPI openapi) {
this.openapi = openapi;
@@ -118,7 +118,7 @@ public class InlineModelResolver {
Schema model = ModelUtils.getSchemaFromRequestBody(requestBody);
if (model instanceof ObjectSchema) {
- Schema obj = (Schema) model;
+ Schema obj = model;
if (obj.getType() == null || "object".equals(obj.getType())) {
if (obj.getProperties() != null && obj.getProperties().size() > 0) {
flattenProperties(openAPI, obj.getProperties(), pathname);
@@ -213,7 +213,7 @@ public class InlineModelResolver {
Schema model = parameter.getSchema();
if (model instanceof ObjectSchema) {
- Schema obj = (Schema) model;
+ Schema obj = model;
if (obj.getType() == null || "object".equals(obj.getType())) {
if (obj.getProperties() != null && obj.getProperties().size() > 0) {
flattenProperties(openAPI, obj.getProperties(), pathname);
@@ -431,7 +431,7 @@ public class InlineModelResolver {
flattenComposedChildren(openAPI, modelName + "_anyOf", m.getAnyOf());
flattenComposedChildren(openAPI, modelName + "_oneOf", m.getOneOf());
} else if (model instanceof Schema) {
- Schema m = (Schema) model;
+ Schema m = model;
Map properties = m.getProperties();
flattenProperties(openAPI, properties, modelName);
fixStringModel(m);
diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/TemplateManager.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/TemplateManager.java
index a0e67ad273..3af30d83ba 100644
--- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/TemplateManager.java
+++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/TemplateManager.java
@@ -25,7 +25,7 @@ public class TemplateManager implements TemplatingExecutor, TemplateProcessor {
private final TemplatingEngineAdapter engineAdapter;
private final TemplatePathLocator[] templateLoaders;
- private static final Logger LOGGER = LoggerFactory.getLogger(TemplateManager.class);
+ private final Logger LOGGER = LoggerFactory.getLogger(TemplateManager.class);
/**
* Constructs a new instance of a {@link TemplateManager}
diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/config/CodegenConfigurator.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/config/CodegenConfigurator.java
index cf0de7a738..cea51acb67 100644
--- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/config/CodegenConfigurator.java
+++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/config/CodegenConfigurator.java
@@ -429,6 +429,11 @@ public class CodegenConfigurator {
return this;
}
+ public CodegenConfigurator setSkipOperationExample(boolean skipOperationExample) {
+ workflowSettingsBuilder.withSkipOperationExample(skipOperationExample);
+ return this;
+ }
+
public CodegenConfigurator setSkipOverwrite(boolean skipOverwrite) {
workflowSettingsBuilder.withSkipOverwrite(skipOverwrite);
return this;
@@ -583,6 +588,7 @@ public class CodegenConfigurator {
config.setSkipOverwrite(workflowSettings.isSkipOverwrite());
config.setIgnoreFilePathOverride(workflowSettings.getIgnoreFileOverride());
config.setRemoveOperationIdPrefix(workflowSettings.isRemoveOperationIdPrefix());
+ config.setSkipOperationExample(workflowSettings.isSkipOperationExample());
config.setEnablePostProcessFile(workflowSettings.isEnablePostProcessFile());
config.setEnableMinimalUpdate(workflowSettings.isEnableMinimalUpdate());
config.setStrictSpecBehavior(workflowSettings.isStrictSpecBehavior());
diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/examples/ExampleGenerator.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/examples/ExampleGenerator.java
index 6a6a807c6f..0c4f9ad726 100644
--- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/examples/ExampleGenerator.java
+++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/examples/ExampleGenerator.java
@@ -30,7 +30,7 @@ import java.math.BigDecimal;
import java.util.*;
public class ExampleGenerator {
- private static final Logger LOGGER = LoggerFactory.getLogger(ExampleGenerator.class);
+ private final Logger LOGGER = LoggerFactory.getLogger(ExampleGenerator.class);
// TODO: move constants to more appropriate location
private static final String MIME_TYPE_JSON = "application/json";
diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/ignore/CodegenIgnoreProcessor.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/ignore/CodegenIgnoreProcessor.java
index 00e3a340c7..c1975e595c 100644
--- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/ignore/CodegenIgnoreProcessor.java
+++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/ignore/CodegenIgnoreProcessor.java
@@ -36,7 +36,7 @@ import java.util.Locale;
*/
public class CodegenIgnoreProcessor {
- private static final Logger LOGGER = LoggerFactory.getLogger(CodegenIgnoreProcessor.class);
+ private final Logger LOGGER = LoggerFactory.getLogger(CodegenIgnoreProcessor.class);
private File ignoreFile = null;
@@ -65,7 +65,7 @@ public class CodegenIgnoreProcessor {
if (directory.exists() && directory.isDirectory()) {
loadFromFile(targetIgnoreFile);
} else {
- LOGGER.warn("Output directory does not exist, or is inaccessible. No file (.openapi-generator-ignore) will be evaluated.");
+ LOGGER.info("Output directory ({}) does not exist, or is inaccessible. No file (.openapi-generator-ignore) will be evaluated.", baseDirectory);
}
}
diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AbstractAdaCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AbstractAdaCodegen.java
index 0479852e2d..309ae0357f 100644
--- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AbstractAdaCodegen.java
+++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AbstractAdaCodegen.java
@@ -43,7 +43,7 @@ import java.util.*;
import static org.openapitools.codegen.utils.StringUtils.camelize;
abstract public class AbstractAdaCodegen extends DefaultCodegen implements CodegenConfig {
- private static final Logger LOGGER = LoggerFactory.getLogger(AbstractAdaCodegen.class);
+ private final Logger LOGGER = LoggerFactory.getLogger(AbstractAdaCodegen.class);
protected String packageName = "defaultPackage";
protected String projectName = "defaultProject";
diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AbstractApexCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AbstractApexCodegen.java
index 6b0068ddb1..37520989ff 100644
--- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AbstractApexCodegen.java
+++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AbstractApexCodegen.java
@@ -36,7 +36,7 @@ import static org.openapitools.codegen.utils.OnceLogger.once;
import static org.openapitools.codegen.utils.StringUtils.camelize;
public abstract class AbstractApexCodegen extends DefaultCodegen implements CodegenConfig {
- private static final Logger LOGGER = LoggerFactory.getLogger(AbstractApexCodegen.class);
+ private final Logger LOGGER = LoggerFactory.getLogger(AbstractApexCodegen.class);
protected Boolean serializableModel = false;
diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AbstractCSharpCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AbstractCSharpCodegen.java
index 7f164bc961..0bcdbb3a37 100644
--- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AbstractCSharpCodegen.java
+++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AbstractCSharpCodegen.java
@@ -83,7 +83,7 @@ public abstract class AbstractCSharpCodegen extends DefaultCodegen implements Co
protected Set valueTypes = new HashSet();
- private static final Logger LOGGER = LoggerFactory.getLogger(AbstractCSharpCodegen.class);
+ private final Logger LOGGER = LoggerFactory.getLogger(AbstractCSharpCodegen.class);
public AbstractCSharpCodegen() {
super();
diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AbstractCppCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AbstractCppCodegen.java
index fb99201f1f..8a2c3c5eb7 100644
--- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AbstractCppCodegen.java
+++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AbstractCppCodegen.java
@@ -48,7 +48,7 @@ import java.util.Map;
import java.util.Map.Entry;
abstract public class AbstractCppCodegen extends DefaultCodegen implements CodegenConfig {
- private static final Logger LOGGER = LoggerFactory.getLogger(AbstractCppCodegen.class);
+ private final Logger LOGGER = LoggerFactory.getLogger(AbstractCppCodegen.class);
protected static final String RESERVED_WORD_PREFIX_OPTION = "reservedWordPrefix";
protected static final String RESERVED_WORD_PREFIX_DESC = "Prefix to prepend to reserved words in order to avoid conflicts";
diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AbstractDartCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AbstractDartCodegen.java
new file mode 100644
index 0000000000..0322228f97
--- /dev/null
+++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AbstractDartCodegen.java
@@ -0,0 +1,686 @@
+package org.openapitools.codegen.languages;
+
+import com.google.common.collect.Lists;
+import com.google.common.collect.Sets;
+import io.swagger.v3.oas.models.Operation;
+import io.swagger.v3.oas.models.media.ArraySchema;
+import io.swagger.v3.oas.models.media.Schema;
+import io.swagger.v3.oas.models.media.StringSchema;
+import io.swagger.v3.oas.models.servers.Server;
+import org.apache.commons.io.FilenameUtils;
+import org.apache.commons.lang3.StringUtils;
+import org.openapitools.codegen.*;
+import org.openapitools.codegen.meta.features.*;
+import org.openapitools.codegen.utils.ModelUtils;
+
+import java.io.BufferedReader;
+import java.io.File;
+import java.io.InputStreamReader;
+import java.nio.charset.StandardCharsets;
+import java.util.*;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import static org.openapitools.codegen.utils.StringUtils.*;
+import static org.openapitools.codegen.utils.StringUtils.camelize;
+
+public abstract class AbstractDartCodegen extends DefaultCodegen {
+
+ private static final Logger LOGGER = LoggerFactory.getLogger(AbstractDartCodegen.class);
+
+ public static final String PUB_LIBRARY = "pubLibrary";
+ public static final String PUB_NAME = "pubName";
+ public static final String PUB_VERSION = "pubVersion";
+ public static final String PUB_DESCRIPTION = "pubDescription";
+ public static final String PUB_AUTHOR = "pubAuthor";
+ public static final String PUB_AUTHOR_EMAIL = "pubAuthorEmail";
+ public static final String PUB_HOMEPAGE = "pubHomepage";
+ public static final String USE_ENUM_EXTENSION = "useEnumExtension";
+
+ protected String pubLibrary = "openapi.api";
+ protected String pubName = "openapi";
+ protected String pubVersion = "1.0.0";
+ protected String pubDescription = "OpenAPI API client";
+ protected String pubAuthor = "Author";
+ protected String pubAuthorEmail = "author@homepage";
+ protected String pubHomepage = "homepage";
+ protected boolean useEnumExtension = false;
+ protected String sourceFolder = "";
+ protected String apiDocPath = "doc" + File.separator;
+ protected String modelDocPath = "doc" + File.separator;
+ protected String apiTestPath = "test" + File.separator;
+ protected String modelTestPath = "test" + File.separator;
+
+ // Names that must not be used as model names because they clash with existing
+ // default imports (dart:io, dart:async, package:http etc.) but are not basic dataTypes.
+ protected Set additionalReservedWords;
+
+ public AbstractDartCodegen() {
+ super();
+
+ modifyFeatureSet(features -> features
+ .includeDocumentationFeatures(DocumentationFeature.Readme)
+ .securityFeatures(EnumSet.of(
+ SecurityFeature.OAuth2_Implicit,
+ SecurityFeature.BasicAuth,
+ SecurityFeature.ApiKey
+ ))
+ .excludeGlobalFeatures(
+ GlobalFeature.XMLStructureDefinitions,
+ GlobalFeature.Callbacks,
+ GlobalFeature.LinkObjects,
+ GlobalFeature.ParameterStyling
+ )
+ .excludeSchemaSupportFeatures(
+ SchemaSupportFeature.Polymorphism
+ )
+ .includeParameterFeatures(
+ ParameterFeature.Cookie
+ )
+ .includeClientModificationFeatures(
+ ClientModificationFeature.BasePath
+ )
+ );
+
+ outputFolder = "generated-code/dart";
+ modelTemplateFiles.put("model.mustache", ".dart");
+ apiTemplateFiles.put("api.mustache", ".dart");
+ embeddedTemplateDir = templateDir = "dart2";
+ apiPackage = "lib.api";
+ modelPackage = "lib.model";
+ modelDocTemplateFiles.put("object_doc.mustache", ".md");
+ apiDocTemplateFiles.put("api_doc.mustache", ".md");
+
+ modelTestTemplateFiles.put("model_test.mustache", ".dart");
+ apiTestTemplateFiles.put("api_test.mustache", ".dart");
+
+ final List reservedWordsList = new ArrayList<>();
+ try(BufferedReader reader = new BufferedReader(
+ new InputStreamReader(DartClientCodegen.class.getResourceAsStream("/dart/dart-keywords.txt"),
+ StandardCharsets.UTF_8))) {
+ while (reader.ready()) {
+ reservedWordsList.add(reader.readLine());
+ }
+ } catch (Exception e) {
+ LOGGER.error("Error reading dart keywords. Exception: {}", e.getMessage());
+ }
+ setReservedWordsLowerCase(reservedWordsList);
+
+ languageSpecificPrimitives = Sets.newHashSet(
+ "String",
+ "bool",
+ "int",
+ "num",
+ "double",
+ "dynamic"
+ );
+
+ typeMapping = new HashMap<>();
+ typeMapping.put("Array", "List");
+ typeMapping.put("array", "List");
+ typeMapping.put("map", "Map");
+ typeMapping.put("List", "List");
+ typeMapping.put("set", "Set");
+ typeMapping.put("boolean", "bool");
+ typeMapping.put("string", "String");
+ typeMapping.put("char", "String");
+ typeMapping.put("int", "int");
+ typeMapping.put("long", "int");
+ typeMapping.put("short", "int");
+ typeMapping.put("number", "num");
+ typeMapping.put("float", "double");
+ typeMapping.put("double", "double");
+ typeMapping.put("decimal", "double");
+ typeMapping.put("integer", "int");
+ typeMapping.put("Date", "DateTime");
+ typeMapping.put("date", "DateTime");
+ typeMapping.put("DateTime", "DateTime");
+ typeMapping.put("file", "MultipartFile");
+ typeMapping.put("binary", "MultipartFile");
+ typeMapping.put("UUID", "String");
+ typeMapping.put("URI", "String");
+ typeMapping.put("ByteArray", "String");
+ typeMapping.put("object", "Object");
+ typeMapping.put("AnyType", "Object");
+
+ // DataTypes of the above values which are automatically imported.
+ // They are also not allowed to be model names.
+ defaultIncludes = Sets.newHashSet(
+ "String",
+ "bool",
+ "int",
+ "num",
+ "double",
+ "dynamic",
+ "List",
+ "Set",
+ "Map",
+ "DateTime",
+ "Object",
+ "MultipartFile"
+ );
+
+ additionalReservedWords = Sets.newHashSet(
+ "File",
+ "Client",
+ "Future",
+ "Response"
+ );
+
+ cliOptions.add(new CliOption(PUB_LIBRARY, "Library name in generated code"));
+ cliOptions.add(new CliOption(PUB_NAME, "Name in generated pubspec"));
+ cliOptions.add(new CliOption(PUB_VERSION, "Version in generated pubspec"));
+ cliOptions.add(new CliOption(PUB_DESCRIPTION, "Description in generated pubspec"));
+ cliOptions.add(new CliOption(PUB_AUTHOR, "Author name in generated pubspec"));
+ cliOptions.add(new CliOption(PUB_AUTHOR_EMAIL, "Email address of the author in generated pubspec"));
+ cliOptions.add(new CliOption(PUB_HOMEPAGE, "Homepage in generated pubspec"));
+ cliOptions.add(new CliOption(USE_ENUM_EXTENSION, "Allow the 'x-enum-values' extension for enums"));
+ cliOptions.add(new CliOption(CodegenConstants.SOURCE_FOLDER, "Source folder for generated code"));
+
+ }
+
+ @Override
+ public CodegenType getTag() {
+ return CodegenType.CLIENT;
+ }
+
+ @Override
+ public String getName() {
+ return "dart";
+ }
+
+ @Override
+ public String getHelp() {
+ return "Generates a Dart 2.x client library.";
+ }
+
+ @Override
+ public void processOpts() {
+ super.processOpts();
+
+ if (StringUtils.isEmpty(System.getenv("DART_POST_PROCESS_FILE"))) {
+ LOGGER.info("Environment variable DART_POST_PROCESS_FILE not defined so the Dart code may not be properly formatted. To define it, try `export DART_POST_PROCESS_FILE=\"/usr/local/bin/dartfmt -w\"` (Linux/Mac)");
+ LOGGER.info("NOTE: To enable file post-processing, 'enablePostProcessFile' must be set to `true` (--enable-post-process-file for CLI).");
+ }
+
+ if (additionalProperties.containsKey(PUB_NAME)) {
+ this.setPubName((String) additionalProperties.get(PUB_NAME));
+ } else {
+ //not set, use to be passed to template
+ additionalProperties.put(PUB_NAME, pubName);
+ }
+
+ if (additionalProperties.containsKey(PUB_LIBRARY)) {
+ this.setPubLibrary((String) additionalProperties.get(PUB_LIBRARY));
+ } else {
+ //not set, use to be passed to template
+ additionalProperties.put(PUB_LIBRARY, pubLibrary);
+ }
+
+ if (additionalProperties.containsKey(PUB_VERSION)) {
+ this.setPubVersion((String) additionalProperties.get(PUB_VERSION));
+ } else {
+ //not set, use to be passed to template
+ additionalProperties.put(PUB_VERSION, pubVersion);
+ }
+
+ if (additionalProperties.containsKey(PUB_DESCRIPTION)) {
+ this.setPubDescription((String) additionalProperties.get(PUB_DESCRIPTION));
+ } else {
+ //not set, use to be passed to template
+ additionalProperties.put(PUB_DESCRIPTION, pubDescription);
+ }
+
+ if (additionalProperties.containsKey(PUB_AUTHOR)) {
+ this.setPubAuthor((String) additionalProperties.get(PUB_AUTHOR));
+ } else {
+ //not set, use to be passed to template
+ additionalProperties.put(PUB_AUTHOR, pubAuthor);
+ }
+
+ if (additionalProperties.containsKey(PUB_AUTHOR_EMAIL)) {
+ this.setPubAuthorEmail((String) additionalProperties.get(PUB_AUTHOR_EMAIL));
+ } else {
+ //not set, use to be passed to template
+ additionalProperties.put(PUB_AUTHOR_EMAIL, pubAuthorEmail);
+ }
+
+ if (additionalProperties.containsKey(PUB_HOMEPAGE)) {
+ this.setPubHomepage((String) additionalProperties.get(PUB_HOMEPAGE));
+ } else {
+ //not set, use to be passed to template
+ additionalProperties.put(PUB_HOMEPAGE, pubHomepage);
+ }
+
+ if (additionalProperties.containsKey(USE_ENUM_EXTENSION)) {
+ this.setUseEnumExtension(convertPropertyToBooleanAndWriteBack(USE_ENUM_EXTENSION));
+ } else {
+ // Not set, use to be passed to template.
+ additionalProperties.put(USE_ENUM_EXTENSION, useEnumExtension);
+ }
+
+ if (additionalProperties.containsKey(CodegenConstants.SOURCE_FOLDER)) {
+ this.setSourceFolder((String) additionalProperties.get(CodegenConstants.SOURCE_FOLDER));
+ }
+
+ // make api and model doc path available in mustache template
+ additionalProperties.put("apiDocPath", apiDocPath);
+ additionalProperties.put("modelDocPath", modelDocPath);
+
+ // check to not overwrite a custom templateDir
+ if (templateDir == null) {
+ embeddedTemplateDir = templateDir = "dart2";
+ }
+ }
+
+ @Override
+ protected boolean isReservedWord(String word) {
+ // consider everything as reserved that is either a keyword,
+ // a default included type, or a type include through some library
+ return super.isReservedWord(word) ||
+ defaultIncludes().contains(word) ||
+ additionalReservedWords.contains(word);
+ }
+
+ @Override
+ public String escapeReservedWord(String name) {
+ return name + "_";
+ }
+
+ @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 apiTestFileFolder() {
+ return outputFolder + File.separator + apiTestPath.replace('/', File.separatorChar);
+ }
+
+ @Override
+ public String modelTestFileFolder() {
+ return outputFolder + File.separator + modelTestPath.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);
+ }
+
+ @Override
+ public String toVarName(String name) {
+ // replace - with _ e.g. created-at => created_at
+ name = name.replace("-", "_");
+
+ // always need to replace leading underscores first
+ name = name.replaceAll("^_", "");
+
+ // if it's all upper case, do nothing
+ if (name.matches("^[A-Z_]*$")) {
+ return name;
+ }
+
+ // replace all characters that have a mapping but ignore underscores
+ // append an underscore to each replacement so that it can be camelized
+ if (name.chars().anyMatch(character -> specialCharReplacements.containsKey("" + ((char) character)))) {
+ name = escape(name, specialCharReplacements, Lists.newArrayList("_"), "_");
+ }
+ // remove the rest
+ name = sanitizeName(name);
+
+ // camelize (lower first character) the variable name
+ // pet_id => petId
+ name = camelize(name, true);
+
+ if (name.matches("^\\d.*")) {
+ name = "n" + name;
+ }
+
+ if (isReservedWord(name)) {
+ name = escapeReservedWord(name);
+ }
+
+ return name;
+ }
+
+ @Override
+ public String toParamName(String name) {
+ // should be the same as variable name
+ return toVarName(name);
+ }
+
+ @Override
+ public String toModelName(final String name) {
+ String nameWithPrefixSuffix = sanitizeName(name);
+ if (!StringUtils.isEmpty(modelNamePrefix)) {
+ // add '_' so that model name can be camelized correctly
+ nameWithPrefixSuffix = modelNamePrefix + "_" + nameWithPrefixSuffix;
+ }
+
+ if (!StringUtils.isEmpty(modelNameSuffix)) {
+ // add '_' so that model name can be camelized correctly
+ nameWithPrefixSuffix = nameWithPrefixSuffix + "_" + modelNameSuffix;
+ }
+
+ // camelize the model name
+ // phone_number => PhoneNumber
+ final String camelizedName = camelize(nameWithPrefixSuffix);
+
+ // model name cannot use reserved keyword, e.g. return
+ if (isReservedWord(camelizedName)) {
+ final String modelName = "Model" + camelizedName;
+ LOGGER.warn(camelizedName + " (reserved word) cannot be used as model name. Renamed to " + modelName);
+ return modelName;
+ }
+
+ // model name starts with number
+ if (camelizedName.matches("^\\d.*")) {
+ final String modelName = "Model" + camelizedName; // e.g. 200Response => Model200Response (after camelize)
+ LOGGER.warn(name + " (model name starts with number) cannot be used as model name. Renamed to " + modelName);
+ return modelName;
+ }
+
+ return camelizedName;
+ }
+
+ @Override
+ public String toModelFilename(String name) {
+ return underscore(toModelName(name));
+ }
+
+ @Override public String toModelDocFilename(String name) {
+ return toModelName(name);
+ }
+
+ @Override
+ public String toApiFilename(String name) {
+ return underscore(toApiName(name));
+ }
+
+ @Override
+ public String toApiTestFilename(String name) {
+ return toApiFilename(name) + "_test";
+ }
+
+ @Override
+ public String toModelTestFilename(String name) {
+ return toModelFilename(name) + "_test";
+ }
+
+ @Override
+ public String toDefaultValue(Schema schema) {
+ if (ModelUtils.isMapSchema(schema) || ModelUtils.isSet(schema)) {
+ return "const {}";
+ }
+ if (ModelUtils.isArraySchema(schema)) {
+ return "const []";
+ }
+
+ if (schema.getDefault() != null) {
+ if (ModelUtils.isDateSchema(schema) || ModelUtils.isDateTimeSchema(schema)) {
+ // this is currently not supported and would create compile errors
+ return null;
+ }
+ if (ModelUtils.isStringSchema(schema)) {
+ return "'" + schema.getDefault().toString().replace("'", "\\'") + "'";
+ }
+ return schema.getDefault().toString();
+ }
+ return null;
+ }
+
+ @Override
+ public String getTypeDeclaration(Schema p) {
+ Schema> schema = ModelUtils.unaliasSchema(this.openAPI, p, importMapping);
+ Schema> target = ModelUtils.isGenerateAliasAsModel() ? p : schema;
+ if (ModelUtils.isArraySchema(target)) {
+ Schema> items = getSchemaItems((ArraySchema) schema);
+ return getSchemaType(target) + "<" + getTypeDeclaration(items) + ">";
+ }
+ if (ModelUtils.isMapSchema(target)) {
+ // Note: ModelUtils.isMapSchema(p) returns true when p is a composed schema that also defines
+ // additionalproperties: true
+ Schema> inner = getAdditionalProperties(target);
+ if (inner == null) {
+ LOGGER.error("`{}` (map property) does not have a proper inner type defined. Default to type:string", p.getName());
+ inner = new StringSchema().description("TODO default missing map inner type to string");
+ p.setAdditionalProperties(inner);
+ }
+ return getSchemaType(target) + "";
+ }
+ return super.getTypeDeclaration(p);
+ }
+
+ @Override
+ public String getSchemaType(Schema p) {
+ String openAPIType = super.getSchemaType(p);
+ if (openAPIType == null) {
+ LOGGER.error("No Type defined for Schema " + p);
+ }
+ if (typeMapping.containsKey(openAPIType)) {
+ return typeMapping.get(openAPIType);
+ }
+ if (languageSpecificPrimitives.contains(openAPIType)) {
+ return openAPIType;
+ }
+ return toModelName(openAPIType);
+ }
+
+ @Override
+ public Map postProcessModels(Map objs) {
+ return postProcessModelsEnum(objs);
+ }
+
+ @Override
+ public void postProcessModelProperty(CodegenModel model, CodegenProperty property) {
+ super.postProcessModelProperty(model, property);
+ if (!model.isEnum && property.isEnum) {
+ // These are inner enums, enums which do not exist as models, just as properties.
+ // They are handled via the enum_inline template and and are generated in the
+ // same file as the containing class. To prevent name clashes the inline enum classes
+ // are prefix with the classname of the containing class in the template.
+ // Here the datatypeWithEnum template variable gets updated to match that scheme.
+ // Also taking into account potential collection types e.g. List -> List
+ final String enumName = model.classname + property.enumName;
+ if (property.items != null) {
+ // inner items e.g. enums in collections, only works for one level
+ // but same is the case for DefaultCodegen
+ property.setDatatypeWithEnum(property.datatypeWithEnum.replace(property.items.datatypeWithEnum, enumName));
+ property.items.setDatatypeWithEnum(enumName);
+ property.items.setEnumName(enumName);
+ } else {
+ // plain enum property
+ property.setDatatypeWithEnum(property.datatypeWithEnum.replace(property.enumName, enumName));
+ }
+ property.setEnumName(enumName);
+ }
+ }
+
+ @Override
+ public CodegenOperation fromOperation(String path, String httpMethod, Operation operation, List servers) {
+ final CodegenOperation op = super.fromOperation(path, httpMethod, operation, servers);
+ for (CodegenResponse r : op.responses) {
+ // By default only set types are automatically added to operation imports, not sure why.
+ // Add all container type imports here, by default 'dart:core' imports are skipped
+ // but other sub classes may required specific container type imports.
+ if (r.containerType != null && typeMapping().containsKey(r.containerType)) {
+ final String value = typeMapping().get(r.containerType);
+ if (needToImport(value)) {
+ op.imports.add(value);
+ }
+ }
+ }
+ for (CodegenParameter p : op.allParams) {
+ if (p.isContainer) {
+ final String type = p.isArray ? "array" : "map";
+ if (typeMapping().containsKey(type)) {
+ final String value = typeMapping().get(type);
+ // Also add container imports for parameters.
+ if (needToImport(value)) {
+ op.imports.add(value);
+ }
+ }
+ }
+ }
+ return op;
+ }
+
+ @Override
+ protected void updateEnumVarsWithExtensions(List> enumVars, Map vendorExtensions, String dataType) {
+ if (vendorExtensions != null && useEnumExtension && vendorExtensions.containsKey("x-enum-values")) {
+ // Use the x-enum-values extension for this enum
+ // Existing enumVars added by the default handling need to be removed first
+ enumVars.clear();
+
+ Object extension = vendorExtensions.get("x-enum-values");
+ List> values = (List>) extension;
+ for (Map value : values) {
+ Map enumVar = new HashMap<>();
+ enumVar.put("name", toEnumVarName((String) value.get("identifier"), dataType));
+ enumVar.put("value", toEnumValue(value.get("numericValue").toString(), dataType));
+ enumVar.put("isString", isDataTypeString(dataType));
+ if (value.containsKey("description")) {
+ enumVar.put("description", value.get("description").toString());
+ }
+ enumVars.add(enumVar);
+ }
+ } else {
+ super.updateEnumVarsWithExtensions(enumVars, vendorExtensions, dataType);
+ }
+ }
+
+ @Override
+ public String toEnumVarName(String value, String datatype) {
+ if (value.length() == 0) {
+ return "empty";
+ }
+ if (("number".equalsIgnoreCase(datatype) ||
+ "double".equalsIgnoreCase(datatype) ||
+ "int".equalsIgnoreCase(datatype)) &&
+ value.matches("^-?\\d.*")) {
+ // Only rename numeric values when the datatype is numeric
+ // AND the name is not changed by enum extensions (matches a numeric value).
+ boolean isNegative = value.startsWith("-");
+ return toVarName("number" + (isNegative ? "_negative" : "") + value);
+ }
+ return toVarName(value);
+ }
+
+ @Override
+ public String toEnumValue(String value, String datatype) {
+ if ("number".equalsIgnoreCase(datatype) ||
+ "int".equalsIgnoreCase(datatype)) {
+ return value;
+ } else {
+ return "'" + escapeText(value) + "'";
+ }
+ }
+
+ @Override
+ public String toOperationId(String operationId) {
+ operationId = super.toOperationId(operationId);
+
+ operationId = camelize(sanitizeName(operationId), true);
+
+ // method name cannot use reserved keyword, e.g. return
+ if (isReservedWord(operationId)) {
+ String newOperationId = camelize("call_" + operationId, true);
+ LOGGER.warn(operationId + " (reserved word) cannot be used as method name. Renamed to " + newOperationId);
+ return newOperationId;
+ }
+
+ // operationId starts with a number
+ if (operationId.matches("^\\d.*")) {
+ LOGGER.warn(operationId + " (starting with a number) cannot be used as method name. Renamed to " + camelize("call_" + operationId), true);
+ operationId = camelize("call_" + operationId, true);
+ }
+
+ return operationId;
+ }
+
+ public void setPubLibrary(String pubLibrary) {
+ this.pubLibrary = pubLibrary;
+ }
+
+ public void setPubName(String pubName) {
+ this.pubName = pubName;
+ }
+
+ public void setPubVersion(String pubVersion) {
+ this.pubVersion = pubVersion;
+ }
+
+ public void setPubDescription(String pubDescription) {
+ this.pubDescription = pubDescription;
+ }
+
+ public void setPubAuthor(String pubAuthor) {
+ this.pubAuthor = pubAuthor;
+ }
+
+ public void setPubAuthorEmail(String pubAuthorEmail) {
+ this.pubAuthorEmail = pubAuthorEmail;
+ }
+
+ public void setPubHomepage(String pubHomepage) {
+ this.pubHomepage = pubHomepage;
+ }
+
+ public void setUseEnumExtension(boolean useEnumExtension) {
+ this.useEnumExtension = useEnumExtension;
+ }
+
+ public void setSourceFolder(String sourceFolder) {
+ this.sourceFolder = sourceFolder;
+ }
+
+ @Override
+ public String escapeQuotationMark(String input) {
+ // remove " to avoid code injection
+ return input.replace("\"", "");
+ }
+
+ @Override
+ public String escapeUnsafeCharacters(String input) {
+ return input.replace("*/", "*_/").replace("/*", "/_*");
+ }
+
+ @Override
+ public void postProcessFile(File file, String fileType) {
+ if (file == null) {
+ return;
+ }
+
+ String dartPostProcessFile = System.getenv("DART_POST_PROCESS_FILE");
+ if (StringUtils.isEmpty(dartPostProcessFile)) {
+ return; // skip if DART_POST_PROCESS_FILE env variable is not defined
+ }
+
+ // process all files with dart extension
+ if ("dart".equals(FilenameUtils.getExtension(file.toString()))) {
+ // currently only support "dartfmt -w yourcode.dart"
+ String command = dartPostProcessFile + " " + file.toString();
+ try {
+ Process p = Runtime.getRuntime().exec(command);
+ int exitValue = p.waitFor();
+ if (exitValue != 0) {
+ LOGGER.error("Error running the command ({}). Exit code: {}", command, exitValue);
+ } else {
+ LOGGER.info("Successfully executed: {}", command);
+ }
+ } catch (Exception e) {
+ LOGGER.error("Error running the command ({}). Exception: {}", command, e.getMessage());
+ }
+ }
+ }
+}
diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AbstractEiffelCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AbstractEiffelCodegen.java
index f80183a7ef..04b8d62b36 100644
--- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AbstractEiffelCodegen.java
+++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AbstractEiffelCodegen.java
@@ -36,7 +36,7 @@ import static org.openapitools.codegen.utils.StringUtils.camelize;
import static org.openapitools.codegen.utils.StringUtils.underscore;
public abstract class AbstractEiffelCodegen extends DefaultCodegen implements CodegenConfig {
- private static final Logger LOGGER = LoggerFactory.getLogger(AbstractEiffelCodegen.class);
+ private final Logger LOGGER = LoggerFactory.getLogger(AbstractEiffelCodegen.class);
private final Set parentModels = new HashSet<>();
private final Multimap childrenByParent = ArrayListMultimap.create();
diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AbstractFSharpCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AbstractFSharpCodegen.java
index c2e3fee78d..f13c9e7800 100644
--- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AbstractFSharpCodegen.java
+++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AbstractFSharpCodegen.java
@@ -77,7 +77,7 @@ public abstract class AbstractFSharpCodegen extends DefaultCodegen implements Co
protected Set nullableType = new HashSet();
- private static final Logger LOGGER = LoggerFactory.getLogger(AbstractFSharpCodegen.class);
+ private final Logger LOGGER = LoggerFactory.getLogger(AbstractFSharpCodegen.class);
public AbstractFSharpCodegen() {
super();
diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AbstractGoCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AbstractGoCodegen.java
index 694f53281e..f0585137d8 100644
--- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AbstractGoCodegen.java
+++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AbstractGoCodegen.java
@@ -34,7 +34,7 @@ import static org.openapitools.codegen.utils.StringUtils.underscore;
public abstract class AbstractGoCodegen extends DefaultCodegen implements CodegenConfig {
- private static final Logger LOGGER = LoggerFactory.getLogger(AbstractGoCodegen.class);
+ private final Logger LOGGER = LoggerFactory.getLogger(AbstractGoCodegen.class);
private static final String NUMERIC_ENUM_PREFIX = "_";
protected boolean withGoCodegenComment = false;
@@ -393,7 +393,7 @@ public abstract class AbstractGoCodegen extends DefaultCodegen implements Codege
String type = null;
if (ref != null && !ref.isEmpty()) {
- type = openAPIType;
+ type = toModelName(openAPIType);
} else if ("object".equals(openAPIType) && isAnyTypeSchema(p)) {
// Arbitrary type. Note this is not the same thing as free-form object.
type = "interface{}";
diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AbstractGraphQLCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AbstractGraphQLCodegen.java
index ddfaa16c86..5246963a8b 100644
--- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AbstractGraphQLCodegen.java
+++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AbstractGraphQLCodegen.java
@@ -32,7 +32,7 @@ import static org.openapitools.codegen.utils.StringUtils.underscore;
public abstract class AbstractGraphQLCodegen extends DefaultCodegen implements CodegenConfig {
- private static final Logger LOGGER = LoggerFactory.getLogger(AbstractGraphQLCodegen.class);
+ private final Logger LOGGER = LoggerFactory.getLogger(AbstractGraphQLCodegen.class);
protected String specFolder = "spec";
protected String packageName = "openapi2graphql";
diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AbstractJavaCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AbstractJavaCodegen.java
index bf4e138bcb..e9a24c9c10 100644
--- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AbstractJavaCodegen.java
+++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AbstractJavaCodegen.java
@@ -49,7 +49,7 @@ import static org.openapitools.codegen.utils.StringUtils.*;
public abstract class AbstractJavaCodegen extends DefaultCodegen implements CodegenConfig {
- private static final Logger LOGGER = LoggerFactory.getLogger(AbstractJavaCodegen.class);
+ private final Logger LOGGER = LoggerFactory.getLogger(AbstractJavaCodegen.class);
private static final String ARTIFACT_VERSION_DEFAULT_VALUE = "1.0.0";
public static final String FULL_JAVA_UTIL = "fullJavaUtil";
@@ -540,13 +540,6 @@ public abstract class AbstractJavaCodegen extends DefaultCodegen implements Code
}
}
- if (additionalProperties.containsKey(WITH_XML)) {
- setWithXml(Boolean.parseBoolean(additionalProperties.get(WITH_XML).toString()));
- if (withXml) {
- additionalProperties.put(WITH_XML, "true");
- }
- }
-
if (additionalProperties.containsKey(DATE_LIBRARY)) {
setDateLibrary(additionalProperties.get("dateLibrary").toString());
}
diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AbstractJavaJAXRSServerCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AbstractJavaJAXRSServerCodegen.java
index eef2d352c9..8ee05fcd3e 100644
--- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AbstractJavaJAXRSServerCodegen.java
+++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AbstractJavaJAXRSServerCodegen.java
@@ -49,7 +49,7 @@ public abstract class AbstractJavaJAXRSServerCodegen extends AbstractJavaCodegen
protected boolean useBeanValidation = true;
protected boolean useTags = false;
- private static final Logger LOGGER = LoggerFactory.getLogger(AbstractJavaJAXRSServerCodegen.class);
+ private final Logger LOGGER = LoggerFactory.getLogger(AbstractJavaJAXRSServerCodegen.class);
public AbstractJavaJAXRSServerCodegen() {
super();
diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AbstractKotlinCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AbstractKotlinCodegen.java
index 79152024e3..abe950e6e9 100644
--- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AbstractKotlinCodegen.java
+++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AbstractKotlinCodegen.java
@@ -49,7 +49,7 @@ public abstract class AbstractKotlinCodegen extends DefaultCodegen implements Co
public static final String MODEL_MUTABLE = "modelMutable";
public static final String MODEL_MUTABLE_DESC = "Create mutable models";
- private static final Logger LOGGER = LoggerFactory.getLogger(AbstractKotlinCodegen.class);
+ private final Logger LOGGER = LoggerFactory.getLogger(AbstractKotlinCodegen.class);
protected String artifactId;
protected String artifactVersion = "1.0.0";
diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AbstractPhpCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AbstractPhpCodegen.java
index 3b0efcaa38..fb6b73e5fd 100644
--- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AbstractPhpCodegen.java
+++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AbstractPhpCodegen.java
@@ -37,7 +37,7 @@ import static org.openapitools.codegen.utils.StringUtils.underscore;
public abstract class AbstractPhpCodegen extends DefaultCodegen implements CodegenConfig {
- private static final Logger LOGGER = LoggerFactory.getLogger(AbstractPhpCodegen.class);
+ private final Logger LOGGER = LoggerFactory.getLogger(AbstractPhpCodegen.class);
public static final String VARIABLE_NAMING_CONVENTION = "variableNamingConvention";
public static final String PACKAGE_NAME = "packageName";
@@ -98,7 +98,7 @@ public abstract class AbstractPhpCodegen extends DefaultCodegen implements Codeg
);
instantiationTypes.put("array", "array");
- instantiationTypes.put("map", "map");
+ instantiationTypes.put("map", "array");
// provide primitives to mustache template
@@ -119,7 +119,7 @@ public abstract class AbstractPhpCodegen extends DefaultCodegen implements Codeg
typeMapping.put("Date", "\\DateTime");
typeMapping.put("DateTime", "\\DateTime");
typeMapping.put("file", "\\SplFileObject");
- typeMapping.put("map", "map");
+ typeMapping.put("map", "array");
typeMapping.put("array", "array");
typeMapping.put("list", "array");
typeMapping.put("object", "object");
@@ -307,7 +307,7 @@ public abstract class AbstractPhpCodegen extends DefaultCodegen implements Codeg
LOGGER.warn(p.getName() + "(map property) does not have a proper inner type defined. Default to string");
inner = new StringSchema().description("TODO default missing map inner type to string");
}
- return getSchemaType(p) + "[string," + getTypeDeclaration(inner) + "]";
+ return getSchemaType(p) + "";
} else if (StringUtils.isNotBlank(p.get$ref())) { // model
String type = super.getTypeDeclaration(p);
return (!languageSpecificPrimitives.contains(type))
diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AbstractPythonCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AbstractPythonCodegen.java
new file mode 100644
index 0000000000..d3482e1724
--- /dev/null
+++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AbstractPythonCodegen.java
@@ -0,0 +1,702 @@
+/*
+ * Copyright 2018 OpenAPI-Generator Contributors (https://openapi-generator.tech)
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.openapitools.codegen.languages;
+
+import com.github.curiousoddman.rgxgen.RgxGen;
+import io.swagger.v3.oas.models.examples.Example;
+import io.swagger.v3.oas.models.media.ArraySchema;
+import io.swagger.v3.oas.models.media.Schema;
+import io.swagger.v3.oas.models.parameters.Parameter;
+import org.apache.commons.io.FilenameUtils;
+import org.apache.commons.lang3.StringUtils;
+import org.openapitools.codegen.*;
+import org.openapitools.codegen.utils.ModelUtils;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.io.BufferedReader;
+import java.io.File;
+import java.io.InputStreamReader;
+import java.nio.charset.StandardCharsets;
+import java.time.LocalDate;
+import java.time.ZoneId;
+import java.util.*;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+
+import static org.openapitools.codegen.utils.StringUtils.camelize;
+import static org.openapitools.codegen.utils.StringUtils.underscore;
+
+abstract public class AbstractPythonCodegen extends DefaultCodegen implements CodegenConfig {
+ private final Logger LOGGER = LoggerFactory.getLogger(AbstractPythonCodegen.class);
+
+ protected String packageName = "openapi_client";
+ protected String packageVersion = "1.0.0";
+ protected String projectName; // for setup.py, e.g. petstore-api
+
+ public AbstractPythonCodegen() {
+ super();
+
+ // from https://docs.python.org/3/reference/lexical_analysis.html#keywords
+ setReservedWordsLowerCase(
+ Arrays.asList(
+ // local variable name used in API methods (endpoints)
+ "all_params", "resource_path", "path_params", "query_params",
+ "header_params", "form_params", "local_var_files", "body_params", "auth_settings",
+ // @property
+ "property",
+ // python reserved words
+ "and", "del", "from", "not", "while", "as", "elif", "global", "or", "with",
+ "assert", "else", "if", "pass", "yield", "break", "except", "import",
+ "print", "class", "exec", "in", "raise", "continue", "finally", "is",
+ "return", "def", "for", "lambda", "try", "self", "nonlocal", "None", "True",
+ "False", "async", "await"));
+
+ languageSpecificPrimitives.clear();
+ languageSpecificPrimitives.add("int");
+ languageSpecificPrimitives.add("float");
+ languageSpecificPrimitives.add("list");
+ languageSpecificPrimitives.add("dict");
+ languageSpecificPrimitives.add("bool");
+ languageSpecificPrimitives.add("str");
+ languageSpecificPrimitives.add("datetime");
+ languageSpecificPrimitives.add("date");
+ languageSpecificPrimitives.add("object");
+ // TODO file and binary is mapped as `file`
+ languageSpecificPrimitives.add("file");
+ languageSpecificPrimitives.add("bytes");
+
+ typeMapping.clear();
+ typeMapping.put("integer", "int");
+ typeMapping.put("float", "float");
+ typeMapping.put("number", "float");
+ typeMapping.put("long", "int");
+ typeMapping.put("double", "float");
+ typeMapping.put("array", "list");
+ typeMapping.put("set", "list");
+ typeMapping.put("map", "dict");
+ typeMapping.put("boolean", "bool");
+ typeMapping.put("string", "str");
+ typeMapping.put("date", "date");
+ typeMapping.put("DateTime", "datetime");
+ typeMapping.put("object", "object");
+ typeMapping.put("AnyType", "object");
+ typeMapping.put("file", "file");
+ // TODO binary should be mapped to byte array
+ // mapped to String as a workaround
+ typeMapping.put("binary", "str");
+ typeMapping.put("ByteArray", "str");
+ // map uuid to string for the time being
+ typeMapping.put("UUID", "str");
+ typeMapping.put("URI", "str");
+ typeMapping.put("null", "none_type");
+ }
+
+ @Override
+ public void processOpts() {
+ super.processOpts();
+
+ 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).");
+ }
+ }
+
+ @Override
+ public String escapeReservedWord(String name) {
+ if (this.reservedWordsMappings().containsKey(name)) {
+ return this.reservedWordsMappings().get(name);
+ }
+ return "_" + name;
+ }
+
+ @Override
+ public String getTypeDeclaration(Schema p) {
+ if (ModelUtils.isArraySchema(p)) {
+ ArraySchema ap = (ArraySchema) p;
+ Schema inner = ap.getItems();
+ return getSchemaType(p) + "[" + getTypeDeclaration(inner) + "]";
+ } else if (ModelUtils.isMapSchema(p)) {
+ Schema inner = getAdditionalProperties(p);
+
+ return getSchemaType(p) + "(str, " + getTypeDeclaration(inner) + ")";
+ }
+ return super.getTypeDeclaration(p);
+ }
+
+ /**
+ * Return the default value of the property
+ *
+ * @param p OpenAPI property object
+ * @return string presentation of the default value of the property
+ */
+ @Override
+ public String toDefaultValue(Schema p) {
+ if (ModelUtils.isBooleanSchema(p)) {
+ if (p.getDefault() != null) {
+ if (Boolean.valueOf(p.getDefault().toString()) == false)
+ return "False";
+ else
+ return "True";
+ }
+ } else if (ModelUtils.isDateSchema(p)) {
+ // TODO
+ } else if (ModelUtils.isDateTimeSchema(p)) {
+ // TODO
+ } else if (ModelUtils.isNumberSchema(p)) {
+ if (p.getDefault() != null) {
+ return p.getDefault().toString();
+ }
+ } else if (ModelUtils.isIntegerSchema(p)) {
+ if (p.getDefault() != null) {
+ return p.getDefault().toString();
+ }
+ } else if (ModelUtils.isStringSchema(p)) {
+ if (p.getDefault() != null) {
+ if (Pattern.compile("\r\n|\r|\n").matcher((String) p.getDefault()).find())
+ return "'''" + p.getDefault() + "'''";
+ else
+ return "'" + ((String) p.getDefault()).replaceAll("'", "\'") + "'";
+ }
+ } else if (ModelUtils.isArraySchema(p)) {
+ if (p.getDefault() != null) {
+ return p.getDefault().toString();
+ }
+ }
+
+ return null;
+ }
+
+
+ @Override
+ public String toVarName(String name) {
+ // sanitize name
+ name = sanitizeName(name); // FIXME: a parameter should not be assigned. Also declare the methods parameters as 'final'.
+
+ // remove dollar sign
+ name = name.replaceAll("$", "");
+
+ // if it's all uppper case, convert to lower case
+ if (name.matches("^[A-Z_]*$")) {
+ name = name.toLowerCase(Locale.ROOT);
+ }
+
+ // underscore the variable name
+ // petId => pet_id
+ name = underscore(name);
+
+ // remove leading underscore
+ name = name.replaceAll("^_*", "");
+
+ // for reserved word or word starting with number, append _
+ if (isReservedWord(name) || name.matches("^\\d.*")) {
+ name = escapeReservedWord(name);
+ }
+
+ return name;
+ }
+
+ @Override
+ public String toRegularExpression(String pattern) {
+ return addRegularExpressionDelimiter(pattern);
+ }
+
+ @Override
+ public String toParamName(String name) {
+ // to avoid conflicts with 'callback' parameter for async call
+ if ("callback".equals(name)) {
+ return "param_callback";
+ }
+
+ // should be the same as variable name
+ return toVarName(name);
+ }
+
+ @Override
+ public String toOperationId(String operationId) {
+ // throw exception if method name is empty (should not occur as an auto-generated method name will be used)
+ if (StringUtils.isEmpty(operationId)) {
+ throw new RuntimeException("Empty method name (operationId) not allowed");
+ }
+
+ // method name cannot use reserved keyword, e.g. return
+ if (isReservedWord(operationId)) {
+ LOGGER.warn(operationId + " (reserved word) cannot be used as method name. Renamed to " + underscore(sanitizeName("call_" + operationId)));
+ operationId = "call_" + operationId;
+ }
+
+ // operationId starts with a number
+ if (operationId.matches("^\\d.*")) {
+ LOGGER.warn(operationId + " (starting with a number) cannot be used as method name. Renamed to " + underscore(sanitizeName("call_" + operationId)));
+ operationId = "call_" + operationId;
+ }
+
+ return underscore(sanitizeName(operationId));
+ }
+
+ @Override
+ public String escapeQuotationMark(String input) {
+ // remove ' to avoid code injection
+ return input.replace("'", "");
+ }
+
+ @Override
+ public String escapeUnsafeCharacters(String input) {
+ // remove multiline comment
+ return input.replace("'''", "'_'_'");
+ }
+
+ @Override
+ public void postProcessFile(File file, String fileType) {
+ if (file == null) {
+ return;
+ }
+ String pythonPostProcessFile = System.getenv("PYTHON_POST_PROCESS_FILE");
+ if (StringUtils.isEmpty(pythonPostProcessFile)) {
+ return; // skip if PYTHON_POST_PROCESS_FILE env variable is not defined
+ }
+
+ // only process files with py extension
+ if ("py".equals(FilenameUtils.getExtension(file.toString()))) {
+ String command = pythonPostProcessFile + " " + file.toString();
+ try {
+ Process p = Runtime.getRuntime().exec(command);
+ int exitValue = p.waitFor();
+ if (exitValue != 0) {
+ LOGGER.error("Error running the command ({}). Exit value: {}", command, exitValue);
+ } else {
+ LOGGER.info("Successfully executed: " + command);
+ }
+ } catch (Exception e) {
+ LOGGER.error("Error running the command ({}). Exception: {}", command, e.getMessage());
+ }
+ }
+ }
+
+ @Override
+ public String toExampleValue(Schema schema) {
+ return toExampleValueRecursive(schema, new ArrayList(), 5);
+ }
+
+ private String toExampleValueRecursive(Schema schema, List included_schemas, int indentation) {
+ String indentation_string = "";
+ for (int i = 0; i < indentation; i++) indentation_string += " ";
+ String example = null;
+ if (schema.getExample() != null) {
+ example = schema.getExample().toString();
+ }
+
+ if (ModelUtils.isNullType(schema) && null != example) {
+ // The 'null' type is allowed in OAS 3.1 and above. It is not supported by OAS 3.0.x,
+ // though this tooling supports it.
+ return "None";
+ }
+ // correct "true"s into "True"s, since super.toExampleValue uses "toString()" on Java booleans
+ if (ModelUtils.isBooleanSchema(schema) && null != example) {
+ if ("false".equalsIgnoreCase(example)) example = "False";
+ else example = "True";
+ }
+
+ // correct "'"s into "'"s after toString()
+ if (ModelUtils.isStringSchema(schema) && schema.getDefault() != null && !ModelUtils.isDateSchema(schema) && !ModelUtils.isDateTimeSchema(schema)) {
+ example = (String) schema.getDefault();
+ }
+
+ if (StringUtils.isNotBlank(example) && !"null".equals(example)) {
+ if (ModelUtils.isStringSchema(schema)) {
+ example = "'" + example + "'";
+ }
+ return example;
+ }
+
+ if (schema.getEnum() != null && !schema.getEnum().isEmpty()) {
+ // Enum case:
+ example = schema.getEnum().get(0).toString();
+ if (ModelUtils.isStringSchema(schema)) {
+ example = "'" + escapeText(example) + "'";
+ }
+ if (null == example)
+ LOGGER.warn("Empty enum. Cannot built an example!");
+
+ return example;
+ } else if (null != schema.get$ref()) {
+ // $ref case:
+ Map allDefinitions = ModelUtils.getSchemas(this.openAPI);
+ String ref = ModelUtils.getSimpleRef(schema.get$ref());
+ if (allDefinitions != null) {
+ Schema refSchema = allDefinitions.get(ref);
+ if (null == refSchema) {
+ return "None";
+ } else {
+ String refTitle = refSchema.getTitle();
+ if (StringUtils.isBlank(refTitle) || "null".equals(refTitle)) {
+ refSchema.setTitle(ref);
+ }
+ if (StringUtils.isNotBlank(schema.getTitle()) && !"null".equals(schema.getTitle())) {
+ included_schemas.add(schema.getTitle());
+ }
+ return toExampleValueRecursive(refSchema, included_schemas, indentation);
+ }
+ } else {
+ LOGGER.warn("allDefinitions not defined in toExampleValue!\n");
+ }
+ }
+ if (ModelUtils.isDateSchema(schema)) {
+ example = "datetime.datetime.strptime('1975-12-30', '%Y-%m-%d').date()";
+ return example;
+ } else if (ModelUtils.isDateTimeSchema(schema)) {
+ example = "datetime.datetime.strptime('2013-10-20 19:20:30.00', '%Y-%m-%d %H:%M:%S.%f')";
+ return example;
+ } else if (ModelUtils.isBinarySchema(schema)) {
+ example = "bytes(b'blah')";
+ return example;
+ } else if (ModelUtils.isByteArraySchema(schema)) {
+ example = "YQ==";
+ } else if (ModelUtils.isStringSchema(schema)) {
+ // a BigDecimal:
+ if ("Number".equalsIgnoreCase(schema.getFormat())) {
+ return "1";
+ }
+ if (StringUtils.isNotBlank(schema.getPattern())) {
+ String pattern = schema.getPattern();
+ RgxGen rgxGen = new RgxGen(patternCorrection(pattern));
+ // this seed makes it so if we have [a-z] we pick a
+ Random random = new Random(18);
+ String sample = rgxGen.generate(random);
+ // omit leading / and trailing /, omit trailing /i
+ Pattern valueExtractor = Pattern.compile("^/\\^?(.+?)\\$?/.?$");
+ Matcher m = valueExtractor.matcher(sample);
+ if (m.find()) {
+ example = m.group(m.groupCount());
+ } else {
+ example = sample;
+ }
+ }
+ if (example == null) {
+ example = "";
+ }
+ int len = 0;
+ if (null != schema.getMinLength()) {
+ len = schema.getMinLength().intValue();
+ if (len < 1) {
+ example = "";
+ } else {
+ for (int i = 0; i < len; i++) example += i;
+ }
+ }
+ } else if (ModelUtils.isIntegerSchema(schema)) {
+ if (schema.getMinimum() != null)
+ example = schema.getMinimum().toString();
+ else
+ example = "56";
+ } else if (ModelUtils.isNumberSchema(schema)) {
+ if (schema.getMinimum() != null)
+ example = schema.getMinimum().toString();
+ else
+ example = "1.337";
+ } else if (ModelUtils.isBooleanSchema(schema)) {
+ example = "True";
+ } else if (ModelUtils.isArraySchema(schema)) {
+ if (StringUtils.isNotBlank(schema.getTitle()) && !"null".equals(schema.getTitle())) {
+ included_schemas.add(schema.getTitle());
+ }
+ ArraySchema arrayschema = (ArraySchema) schema;
+ example = "[\n" + indentation_string + toExampleValueRecursive(arrayschema.getItems(), included_schemas, indentation + 1) + "\n" + indentation_string + "]";
+ } else if (ModelUtils.isMapSchema(schema)) {
+ if (StringUtils.isNotBlank(schema.getTitle()) && !"null".equals(schema.getTitle())) {
+ included_schemas.add(schema.getTitle());
+ }
+ Object additionalObject = schema.getAdditionalProperties();
+ if (additionalObject instanceof Schema) {
+ Schema additional = (Schema) additionalObject;
+ String the_key = "'key'";
+ if (additional.getEnum() != null && !additional.getEnum().isEmpty()) {
+ the_key = additional.getEnum().get(0).toString();
+ if (ModelUtils.isStringSchema(additional)) {
+ the_key = "'" + escapeText(the_key) + "'";
+ }
+ }
+ example = "{\n" + indentation_string + the_key + " : " + toExampleValueRecursive(additional, included_schemas, indentation + 1) + "\n" + indentation_string + "}";
+ } else {
+ example = "{ }";
+ }
+ } else if (ModelUtils.isObjectSchema(schema)) {
+ if (StringUtils.isBlank(schema.getTitle())) {
+ example = "None";
+ return example;
+ }
+
+ // I remove any property that is a discriminator, since it is not well supported by the python generator
+ String toExclude = null;
+ if (schema.getDiscriminator() != null) {
+ toExclude = schema.getDiscriminator().getPropertyName();
+ }
+
+ example = packageName + ".models." + underscore(schema.getTitle()) + "." + schema.getTitle() + "(";
+
+ // if required only:
+ // List reqs = schema.getRequired();
+
+ // if required and optionals
+ List reqs = new ArrayList<>();
+ if (schema.getProperties() != null && !schema.getProperties().isEmpty()) {
+ for (Object toAdd : schema.getProperties().keySet()) {
+ reqs.add((String) toAdd);
+ }
+
+ Map properties = schema.getProperties();
+ Set propkeys = null;
+ if (properties != null) propkeys = properties.keySet();
+ if (toExclude != null && reqs.contains(toExclude)) {
+ reqs.remove(toExclude);
+ }
+ for (String toRemove : included_schemas) {
+ if (reqs.contains(toRemove)) {
+ reqs.remove(toRemove);
+ }
+ }
+ if (StringUtils.isNotBlank(schema.getTitle()) && !"null".equals(schema.getTitle())) {
+ included_schemas.add(schema.getTitle());
+ }
+ if (null != schema.getRequired()) for (Object toAdd : schema.getRequired()) {
+ reqs.add((String) toAdd);
+ }
+ if (null != propkeys) for (String propname : propkeys) {
+ Schema schema2 = properties.get(propname);
+ if (reqs.contains(propname)) {
+ String refTitle = schema2.getTitle();
+ if (StringUtils.isBlank(refTitle) || "null".equals(refTitle)) {
+ schema2.setTitle(propname);
+ }
+ example += "\n" + indentation_string + underscore(propname) + " = " +
+ toExampleValueRecursive(schema2, included_schemas, indentation + 1) + ", ";
+ }
+ }
+ }
+ example += ")";
+ } else {
+ LOGGER.warn("Type " + schema.getType() + " not handled properly in toExampleValue");
+ }
+
+ if (ModelUtils.isStringSchema(schema)) {
+ example = "'" + escapeText(example) + "'";
+ }
+
+ return example;
+ }
+
+ @Override
+ public void setParameterExampleValue(CodegenParameter p) {
+ String example;
+
+ if (p.defaultValue == null) {
+ example = p.example;
+ } else {
+ p.example = p.defaultValue;
+ return;
+ }
+
+ String type = p.baseType;
+ if (type == null) {
+ type = p.dataType;
+ }
+
+ if ("String".equalsIgnoreCase(type) || "str".equalsIgnoreCase(type)) {
+ if (example == null) {
+ example = p.paramName + "_example";
+ }
+ example = "'" + escapeText(example) + "'";
+ } else if ("Integer".equals(type) || "int".equals(type)) {
+ if (example == null) {
+ example = "56";
+ }
+ } else if ("Float".equalsIgnoreCase(type) || "Double".equalsIgnoreCase(type)) {
+ if (example == null) {
+ example = "3.4";
+ }
+ } else if ("BOOLEAN".equalsIgnoreCase(type) || "bool".equalsIgnoreCase(type)) {
+ if (example == null) {
+ example = "True";
+ }
+ } else if ("file".equalsIgnoreCase(type)) {
+ if (example == null) {
+ example = "/path/to/file";
+ }
+ example = "'" + escapeText(example) + "'";
+ } else if ("Date".equalsIgnoreCase(type)) {
+ if (example == null) {
+ example = "2013-10-20";
+ }
+ example = "'" + escapeText(example) + "'";
+ } else if ("DateTime".equalsIgnoreCase(type)) {
+ if (example == null) {
+ example = "2013-10-20T19:20:30+01:00";
+ }
+ example = "'" + escapeText(example) + "'";
+ } else if (!languageSpecificPrimitives.contains(type)) {
+ // type is a model class, e.g. User
+ example = this.packageName + "." + type + "()";
+ } else {
+ LOGGER.warn("Type " + type + " not handled properly in setParameterExampleValue");
+ }
+
+ if (example == null) {
+ example = "None";
+ } else if (Boolean.TRUE.equals(p.isArray)) {
+ example = "[" + example + "]";
+ } else if (Boolean.TRUE.equals(p.isMap)) {
+ example = "{'key': " + example + "}";
+ }
+
+ p.example = example;
+ }
+
+ @Override
+ public void setParameterExampleValue(CodegenParameter codegenParameter, Parameter parameter) {
+ Schema schema = parameter.getSchema();
+
+ if (parameter.getExample() != null) {
+ codegenParameter.example = parameter.getExample().toString();
+ } else if (parameter.getExamples() != null && !parameter.getExamples().isEmpty()) {
+ Example example = parameter.getExamples().values().iterator().next();
+ if (example.getValue() != null) {
+ codegenParameter.example = example.getValue().toString();
+ }
+ } else if (schema != null && schema.getExample() != null) {
+ codegenParameter.example = schema.getExample().toString();
+ }
+
+ setParameterExampleValue(codegenParameter);
+ }
+
+ @Override
+ public String sanitizeTag(String tag) {
+ return sanitizeName(tag);
+ }
+
+ public String patternCorrection(String pattern) {
+ // Java does not recognize starting and ending forward slashes and mode modifiers
+ // It considers them as characters with no special meaning and tries to find them in the match string
+ boolean checkEnding = pattern.endsWith("/i") || pattern.endsWith("/g") || pattern.endsWith("/m");
+ if (checkEnding) pattern = pattern.substring(0, pattern.length() - 2);
+ if (pattern.endsWith("/")) pattern = pattern.substring(0, pattern.length() - 1);
+ if (pattern.startsWith("/")) pattern = pattern.substring(1);
+ return pattern;
+ }
+
+ public void setPackageName(String packageName) {
+ this.packageName = packageName;
+ }
+
+ public void setProjectName(String projectName) {
+ this.projectName = projectName;
+ }
+
+ public void setPackageVersion(String packageVersion) {
+ this.packageVersion = packageVersion;
+ }
+
+ @Override
+ public String getSchemaType(Schema p) {
+ String openAPIType = super.getSchemaType(p);
+ String type = null;
+ if (typeMapping.containsKey(openAPIType)) {
+ type = typeMapping.get(openAPIType);
+ if (languageSpecificPrimitives.contains(type)) {
+ return type;
+ }
+ } else {
+ type = toModelName(openAPIType);
+ }
+ return type;
+ }
+
+
+ @Override
+ public String toModelName(String name) {
+ name = sanitizeName(name); // FIXME: a parameter should not be assigned. Also declare the methods parameters as 'final'.
+ // remove dollar sign
+ name = name.replaceAll("$", "");
+
+ // model name cannot use reserved keyword, e.g. return
+ if (isReservedWord(name)) {
+ LOGGER.warn(name + " (reserved word) cannot be used as model name. Renamed to " + camelize("model_" + name));
+ name = "model_" + name; // e.g. return => ModelReturn (after camelize)
+ }
+
+ // model name starts with number
+ if (name.matches("^\\d.*")) {
+ LOGGER.warn(name + " (model name starts with number) cannot be used as model name. Renamed to " + camelize("model_" + name));
+ name = "model_" + name; // e.g. 200Response => Model200Response (after camelize)
+ }
+
+ if (!StringUtils.isEmpty(modelNamePrefix)) {
+ name = modelNamePrefix + "_" + name;
+ }
+
+ if (!StringUtils.isEmpty(modelNameSuffix)) {
+ name = name + "_" + modelNameSuffix;
+ }
+
+ // camelize the model name
+ // phone_number => PhoneNumber
+ return camelize(name);
+ }
+
+ @Override
+ public String toModelFilename(String name) {
+ // underscore the model file name
+ // PhoneNumber => phone_number
+ return underscore(dropDots(toModelName(name)));
+ }
+
+ @Override
+ public String toModelTestFilename(String name) {
+ return "test_" + toModelFilename(name);
+ }
+
+ @Override
+ public String toApiFilename(String name) {
+ // replace - with _ e.g. created-at => created_at
+ name = name.replaceAll("-", "_");
+
+ // e.g. PhoneNumberApi.py => phone_number_api.py
+ return underscore(name + "_" + apiNameSuffix);
+ }
+
+ @Override
+ public String toApiTestFilename(String name) {
+ return "test_" + toApiFilename(name);
+ }
+
+ @Override
+ public String toApiName(String name) {
+ return super.toApiName(name);
+ }
+
+ @Override
+ public String toApiVarName(String name) {
+ if (name.length() == 0) {
+ return "default_api";
+ }
+ return underscore(name + "_" + apiNameSuffix);
+ }
+
+ protected static String dropDots(String str) {
+ return str.replaceAll("\\.", "_");
+ }
+}
diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AbstractPythonConnexionServerCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AbstractPythonConnexionServerCodegen.java
index e9195a684b..d6972edcde 100644
--- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AbstractPythonConnexionServerCodegen.java
+++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AbstractPythonConnexionServerCodegen.java
@@ -43,8 +43,8 @@ import java.util.*;
import static org.openapitools.codegen.utils.StringUtils.camelize;
import static org.openapitools.codegen.utils.StringUtils.underscore;
-public abstract class AbstractPythonConnexionServerCodegen extends DefaultCodegen implements CodegenConfig {
- private static final Logger LOGGER = LoggerFactory.getLogger(AbstractPythonConnexionServerCodegen.class);
+public abstract class AbstractPythonConnexionServerCodegen extends AbstractPythonCodegen implements CodegenConfig {
+ private final Logger LOGGER = LoggerFactory.getLogger(AbstractPythonConnexionServerCodegen.class);
public static final String CONTROLLER_PACKAGE = "controllerPackage";
public static final String DEFAULT_CONTROLLER = "defaultController";
@@ -56,8 +56,6 @@ public abstract class AbstractPythonConnexionServerCodegen extends DefaultCodege
static final String MEDIA_TYPE = "mediaType";
protected int serverPort = 8080;
- protected String packageName;
- protected String packageVersion;
protected String controllerPackage;
protected String defaultController;
protected Map regexModifiers;
@@ -75,49 +73,11 @@ public abstract class AbstractPythonConnexionServerCodegen extends DefaultCodege
modelPackage = "models";
testPackage = "test";
- languageSpecificPrimitives.clear();
- languageSpecificPrimitives.add("int");
- languageSpecificPrimitives.add("float");
+ // TODO may remove these later to default to the setting in abstract python base class instead
languageSpecificPrimitives.add("List");
languageSpecificPrimitives.add("Dict");
- languageSpecificPrimitives.add("bool");
- languageSpecificPrimitives.add("str");
- languageSpecificPrimitives.add("datetime");
- languageSpecificPrimitives.add("date");
- languageSpecificPrimitives.add("file");
- languageSpecificPrimitives.add("object");
- languageSpecificPrimitives.add("byte");
- languageSpecificPrimitives.add("bytearray");
-
- typeMapping.clear();
- typeMapping.put("integer", "int");
- typeMapping.put("float", "float");
- typeMapping.put("number", "float");
- typeMapping.put("long", "int");
- typeMapping.put("double", "float");
typeMapping.put("array", "List");
typeMapping.put("map", "Dict");
- typeMapping.put("boolean", "bool");
- typeMapping.put("string", "str");
- typeMapping.put("date", "date");
- typeMapping.put("DateTime", "datetime");
- typeMapping.put("object", "object");
- typeMapping.put("file", "file");
- typeMapping.put("UUID", "str");
- typeMapping.put("URI", "str");
- typeMapping.put("byte", "bytearray");
- typeMapping.put("ByteArray", "bytearray");
-
- // from https://docs.python.org/3/reference/lexical_analysis.html#keywords
- setReservedWordsLowerCase(
- Arrays.asList(
- // @property
- "property",
- // python reserved words
- "and", "del", "from", "not", "while", "as", "elif", "global", "or", "with",
- "assert", "else", "if", "pass", "yield", "break", "except", "import",
- "print", "class", "exec", "in", "raise", "continue", "finally", "is",
- "return", "def", "for", "lambda", "try", "self", "None", "True", "False", "nonlocal"));
// set the output folder here
outputFolder = "generated-code/connexion";
@@ -182,11 +142,6 @@ public abstract class AbstractPythonConnexionServerCodegen extends DefaultCodege
public void processOpts() {
super.processOpts();
- 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).");
- }
-
//apiTemplateFiles.clear();
if (additionalProperties.containsKey(CodegenConstants.PACKAGE_NAME)) {
@@ -266,6 +221,7 @@ public abstract class AbstractPythonConnexionServerCodegen extends DefaultCodege
}
}
+
public String pythonSrcOutputFolder() {
return outputFolder + File.separator + pythonSrcRoot;
}
@@ -274,10 +230,6 @@ public abstract class AbstractPythonConnexionServerCodegen extends DefaultCodege
return pkg.replace(".", File.separator);
}
- private static String dropDots(String str) {
- return str.replaceAll("\\.", "_");
- }
-
@Override
public String apiPackage() {
return controllerPackage;
@@ -324,20 +276,6 @@ public abstract class AbstractPythonConnexionServerCodegen extends DefaultCodege
return "test_" + toApiFilename(name);
}
- /**
- * Escapes a reserved word as defined in the `reservedWords` array. Handle escaping
- * those terms here. This logic is only called if a variable matches the reserved words
- *
- * @return the escaped term
- */
- @Override
- public String escapeReservedWord(String name) {
- if (this.reservedWordsMappings().containsKey(name)) {
- return this.reservedWordsMappings().get(name);
- }
- return "_" + name; // add an underscore to the name
- }
-
/**
* Location to write api files. You can use the apiPackage() as defined when the class is
* instantiated
@@ -367,21 +305,6 @@ public abstract class AbstractPythonConnexionServerCodegen extends DefaultCodege
return super.getTypeDeclaration(p);
}
- @Override
- public String getSchemaType(Schema p) {
- String schemaType = super.getSchemaType(p);
- String type = null;
- if (typeMapping.containsKey(schemaType)) {
- type = typeMapping.get(schemaType);
- if (languageSpecificPrimitives.contains(type)) {
- return type;
- }
- } else {
- type = toModelName(schemaType);
- }
- return type;
- }
-
@Override
public void preprocessOpenAPI(OpenAPI openAPI) {
// need vendor extensions for x-openapi-router-controller
@@ -614,251 +537,11 @@ public abstract class AbstractPythonConnexionServerCodegen extends DefaultCodege
return super.postProcessSupportingFileData(objs);
}
- @Override
- public String toVarName(String name) {
- // sanitize name
- name = sanitizeName(name); // FIXME: a parameter should not be assigned. Also declare the methods parameters as 'final'.
-
- // remove dollar sign
- name = name.replaceAll("$", "");
-
- // if it's all uppper case, convert to lower case
- if (name.matches("^[A-Z_]*$")) {
- name = name.toLowerCase(Locale.ROOT);
- }
-
- // underscore the variable name
- // petId => pet_id
- name = underscore(name);
-
- // remove leading underscore
- name = name.replaceAll("^_*", "");
-
- // for reserved word or word starting with number, append _
- if (isReservedWord(name) || name.matches("^\\d.*")) {
- name = escapeReservedWord(name);
- }
-
- return name;
- }
-
- @Override
- public String toParamName(String name) {
- // to avoid conflicts with 'callback' parameter for async call
- if ("callback".equals(name)) {
- return "param_callback";
- }
-
- // should be the same as variable name
- return toVarName(name);
- }
-
- @Override
- public String toModelFilename(String name) {
- // underscore the model file name
- // PhoneNumber => phone_number
- return underscore(dropDots(toModelName(name)));
- }
-
- @Override
- public String toModelName(String name) {
- name = sanitizeName(name); // FIXME: a parameter should not be assigned. Also declare the methods parameters as 'final'.
- // remove dollar sign
- name = name.replaceAll("$", "");
-
- // model name cannot use reserved keyword, e.g. return
- if (isReservedWord(name)) {
- LOGGER.warn(name + " (reserved word) cannot be used as model name. Renamed to " + camelize("model_" + name));
- name = "model_" + name; // e.g. return => ModelReturn (after camelize)
- }
-
- // model name starts with number
- if (name.matches("^\\d.*")) {
- LOGGER.warn(name + " (model name starts with number) cannot be used as model name. Renamed to " + camelize("model_" + name));
- name = "model_" + name; // e.g. 200Response => Model200Response (after camelize)
- }
-
- if (!StringUtils.isEmpty(modelNamePrefix)) {
- name = modelNamePrefix + "_" + name;
- }
-
- if (!StringUtils.isEmpty(modelNameSuffix)) {
- name = name + "_" + modelNameSuffix;
- }
-
- // camelize the model name
- // phone_number => PhoneNumber
- return camelize(name);
- }
-
- @Override
- public String toOperationId(String operationId) {
- // throw exception if method name is empty (should not occur as an auto-generated method name will be used)
- if (StringUtils.isEmpty(operationId)) {
- throw new RuntimeException("Empty method name (operationId) not allowed");
- }
-
- // method name cannot use reserved keyword, e.g. return
- if (isReservedWord(operationId)) {
- LOGGER.warn(operationId + " (reserved word) cannot be used as method name. Renamed to " + underscore(sanitizeName("call_" + operationId)));
- operationId = "call_" + operationId;
- }
-
- return underscore(sanitizeName(operationId));
- }
-
- /**
- * Return the default value of the property
- *
- * @param p OpenAPI property object
- * @return string presentation of the default value of the property
- */
- @Override
- public String toDefaultValue(Schema p) {
- if (ModelUtils.isBooleanSchema(p)) {
- if (p.getDefault() != null) {
- if (p.getDefault().toString().equalsIgnoreCase("false"))
- return "False";
- else
- return "True";
- }
- } else if (ModelUtils.isDateSchema(p)) {
- // TODO
- } else if (ModelUtils.isDateTimeSchema(p)) {
- // TODO
- } else if (ModelUtils.isNumberSchema(p)) {
- if (p.getDefault() != null) {
- return p.getDefault().toString();
- }
- } else if (ModelUtils.isIntegerSchema(p)) {
- if (p.getDefault() != null) {
- return p.getDefault().toString();
- }
- } else if (ModelUtils.isStringSchema(p)) {
- if (p.getDefault() != null) {
- return "'" + (String) p.getDefault() + "'";
- }
- }
-
- return null;
- }
-
- @Override
- public void setParameterExampleValue(CodegenParameter p) {
- String example;
-
- if (p.defaultValue == null) {
- example = p.example;
- } else {
- p.example = p.defaultValue;
- return;
- }
-
- String type = p.baseType;
- if (type == null) {
- type = p.dataType;
- }
-
- if ("String".equalsIgnoreCase(type) || "str".equalsIgnoreCase(type)) {
- if (example == null) {
- example = p.paramName + "_example";
- }
- example = "'" + escapeText(example) + "'";
- } else if ("Integer".equals(type) || "int".equals(type)) {
- if (p.minimum != null) {
- example = "" + (Integer.valueOf(p.minimum) + 1);
- }
- if (p.maximum != null) {
- example = "" + p.maximum;
- } else if (example == null) {
- example = "56";
- }
-
- } else if ("Long".equalsIgnoreCase(type)) {
- if (p.minimum != null) {
- example = "" + (Long.valueOf(p.minimum) + 1);
- }
- if (p.maximum != null) {
- example = "" + p.maximum;
- } else if (example == null) {
- example = "789";
- }
- } else if ("Float".equalsIgnoreCase(type) || "Double".equalsIgnoreCase(type)) {
- if (p.minimum != null) {
- example = "" + p.minimum;
- } else if (p.maximum != null) {
- example = "" + p.maximum;
- } else if (example == null) {
- example = "3.4";
- }
- } else if ("BOOLEAN".equalsIgnoreCase(type) || "bool".equalsIgnoreCase(type)) {
- if (example == null) {
- example = "True";
- }
- } else if ("file".equalsIgnoreCase(type)) {
- example = "(BytesIO(b'some file data'), 'file.txt')";
- } else if ("Date".equalsIgnoreCase(type)) {
- if (example == null) {
- example = "2013-10-20";
- }
- example = "'" + escapeText(example) + "'";
- } else if ("DateTime".equalsIgnoreCase(type)) {
- if (example == null) {
- example = "2013-10-20T19:20:30+01:00";
- }
- example = "'" + escapeText(example) + "'";
- } else if (!languageSpecificPrimitives.contains(type)) {
- // type is a model class, e.g. User
- example = "{}";
- } else {
- LOGGER.warn("Type " + type + " not handled properly in setParameterExampleValue");
- }
-
- if (p.items != null && p.items.defaultValue != null) {
- example = p.items.defaultValue;
- }
- if (example == null) {
- if (Boolean.TRUE.equals(p.isArray)) {
- example = "[]";
- } else {
- example = "None";
- }
- } else if (Boolean.TRUE.equals(p.isArray)) {
- if (Boolean.TRUE.equals(p.isBodyParam)) {
- example = "[" + example + "]";
- }
- } else if (Boolean.TRUE.equals(p.isMap)) {
- example = "{'key': " + example + "}";
- }
-
- p.example = example;
- }
-
- public void setPackageName(String packageName) {
- this.packageName = packageName;
- }
-
- public void setPackageVersion(String packageVersion) {
- this.packageVersion = packageVersion;
- }
-
public String packagePath() {
String pkgPath = packageName.replace('.', File.separatorChar);
return pythonSrcRoot + pkgPath;
}
- @Override
- public String escapeQuotationMark(String input) {
- // remove ' to avoid code injection
- return input.replace("'", "");
- }
-
- @Override
- public String escapeUnsafeCharacters(String input) {
- // remove multiline comment
- return input.replace("'''", "'_'_'");
- }
-
@Override
public String toModelImport(String name) {
String modelImport;
@@ -1008,41 +691,4 @@ public abstract class AbstractPythonConnexionServerCodegen extends DefaultCodege
vendorExtensions.put("x-modifiers", modifiers);
}
}
-
- @Override
- public void postProcessFile(File file, String fileType) {
- if (file == null) {
- return;
- }
- String pythonPostProcessFile = System.getenv("PYTHON_POST_PROCESS_FILE");
- if (StringUtils.isEmpty(pythonPostProcessFile)) {
- return; // skip if PYTHON_POST_PROCESS_FILE env variable is not defined
- }
-
- // only process files with py extension
- if ("py".equals(FilenameUtils.getExtension(file.toString()))) {
- String command = pythonPostProcessFile + " " + file.toString();
- try {
- Process p = Runtime.getRuntime().exec(command);
- int exitValue = p.waitFor();
- if (exitValue != 0) {
- LOGGER.error("Error running the command ({}). Exit value: {}", command, exitValue);
- } else {
- LOGGER.info("Successfully executed: " + command);
- }
- } catch (Exception e) {
- LOGGER.error("Error running the command ({}). Exception: {}", command, e.getMessage());
- }
- }
- }
-
- /*
- * We don't want to run `escapeText` on the pattern
- * but forward it directly to the Python implementation.
- */
- @Override
- public String toRegularExpression(String pattern) {
- return addRegularExpressionDelimiter(pattern);
- }
-
}
diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AbstractRubyCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AbstractRubyCodegen.java
index 0bd5968187..f3f002ddae 100644
--- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AbstractRubyCodegen.java
+++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AbstractRubyCodegen.java
@@ -40,7 +40,7 @@ import java.util.Locale;
import static org.openapitools.codegen.utils.StringUtils.underscore;
abstract public class AbstractRubyCodegen extends DefaultCodegen implements CodegenConfig {
- private static final Logger LOGGER = LoggerFactory.getLogger(AbstractRubyCodegen.class);
+ private final Logger LOGGER = LoggerFactory.getLogger(AbstractRubyCodegen.class);
public AbstractRubyCodegen() {
super();
diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AbstractScalaCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AbstractScalaCodegen.java
index 6f87d96f13..6fc5363626 100644
--- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AbstractScalaCodegen.java
+++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AbstractScalaCodegen.java
@@ -36,7 +36,7 @@ import static org.openapitools.codegen.utils.StringUtils.camelize;
import static org.openapitools.codegen.utils.StringUtils.underscore;
public abstract class AbstractScalaCodegen extends DefaultCodegen {
- private static final Logger LOGGER = LoggerFactory.getLogger(AbstractScalaCodegen.class);
+ private final Logger LOGGER = LoggerFactory.getLogger(AbstractScalaCodegen.class);
protected String modelPropertyNaming = CodegenConstants.ENUM_PROPERTY_NAMING_TYPE.camelCase.name();
protected String invokerPackage = "org.openapitools.client";
diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AbstractTypeScriptClientCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AbstractTypeScriptClientCodegen.java
index a74b43a257..8829bf37c1 100644
--- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AbstractTypeScriptClientCodegen.java
+++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AbstractTypeScriptClientCodegen.java
@@ -45,7 +45,7 @@ import static org.openapitools.codegen.utils.StringUtils.camelize;
import static org.openapitools.codegen.utils.StringUtils.underscore;
public abstract class AbstractTypeScriptClientCodegen extends DefaultCodegen implements CodegenConfig {
- private static final Logger LOGGER = LoggerFactory.getLogger(AbstractTypeScriptClientCodegen.class);
+ private final Logger LOGGER = LoggerFactory.getLogger(AbstractTypeScriptClientCodegen.class);
private static final String X_DISCRIMINATOR_TYPE = "x-discriminator-value";
private static final String UNDEFINED_VALUE = "undefined";
diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AndroidClientCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AndroidClientCodegen.java
index 3f87fcc77c..2fa04946c8 100644
--- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AndroidClientCodegen.java
+++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AndroidClientCodegen.java
@@ -33,7 +33,7 @@ import java.util.HashSet;
import static org.openapitools.codegen.utils.StringUtils.camelize;
public class AndroidClientCodegen extends DefaultCodegen implements CodegenConfig {
- private static final Logger LOGGER = LoggerFactory.getLogger(AndroidClientCodegen.class);
+ private final Logger LOGGER = LoggerFactory.getLogger(AndroidClientCodegen.class);
public static final String USE_ANDROID_MAVEN_GRADLE_PLUGIN = "useAndroidMavenGradlePlugin";
public static final String ANDROID_GRADLE_VERSION = "androidGradleVersion";
public static final String ANDROID_SDK_VERSION = "androidSdkVersion";
diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/Apache2ConfigCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/Apache2ConfigCodegen.java
index cd0a392fb2..924c509a19 100644
--- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/Apache2ConfigCodegen.java
+++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/Apache2ConfigCodegen.java
@@ -29,7 +29,7 @@ import static org.openapitools.codegen.utils.OnceLogger.once;
public class Apache2ConfigCodegen extends DefaultCodegen implements CodegenConfig {
public static final String USER_INFO_PATH = "userInfoPath";
- private static final Logger LOGGER = LoggerFactory.getLogger(Apache2ConfigCodegen.class);
+ private final Logger LOGGER = LoggerFactory.getLogger(Apache2ConfigCodegen.class);
protected String userInfoPath = "/var/www/html/";
diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/ApexClientCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/ApexClientCodegen.java
index fe7cdcfb59..fff53c7d0a 100644
--- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/ApexClientCodegen.java
+++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/ApexClientCodegen.java
@@ -42,7 +42,7 @@ public class ApexClientCodegen extends AbstractApexCodegen {
private static final String API_VERSION = "apiVersion";
private static final String BUILD_METHOD = "buildMethod";
private static final String NAMED_CREDENTIAL = "namedCredential";
- private static final Logger LOGGER = LoggerFactory.getLogger(ApexClientCodegen.class);
+ private final Logger LOGGER = LoggerFactory.getLogger(ApexClientCodegen.class);
private String classPrefix = "OAS";
private String apiVersion = "42.0";
private String buildMethod = "sfdx";
diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AsciidocDocumentationCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AsciidocDocumentationCodegen.java
index db3b11e426..6c2dd4ac43 100644
--- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AsciidocDocumentationCodegen.java
+++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AsciidocDocumentationCodegen.java
@@ -44,7 +44,7 @@ import io.swagger.v3.oas.models.OpenAPI;
*/
public class AsciidocDocumentationCodegen extends DefaultCodegen implements CodegenConfig {
- private static final Logger LOGGER = LoggerFactory.getLogger(AsciidocDocumentationCodegen.class);
+ private final Logger LOGGER = LoggerFactory.getLogger(AsciidocDocumentationCodegen.class);
public static final String SPEC_DIR = "specDir";
public static final String SNIPPET_DIR = "snippetDir";
diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AspNetCoreServerCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AspNetCoreServerCodegen.java
index e899fb5eeb..6e95e56dc2 100644
--- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AspNetCoreServerCodegen.java
+++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AspNetCoreServerCodegen.java
@@ -48,6 +48,7 @@ public class AspNetCoreServerCodegen extends AbstractCSharpCodegen {
public static final String GENERATE_BODY = "generateBody";
public static final String BUILD_TARGET = "buildTarget";
public static final String MODEL_CLASS_MODIFIER = "modelClassModifier";
+ public static final String TARGET_FRAMEWORK= "targetFramework";
public static final String PROJECT_SDK = "projectSdk";
public static final String SDK_WEB = "Microsoft.NET.Sdk.Web";
@@ -68,7 +69,7 @@ public class AspNetCoreServerCodegen extends AbstractCSharpCodegen {
protected int serverPort = 8080;
protected String serverHost = "0.0.0.0";
protected CliOption swashbuckleVersion = new CliOption(SWASHBUCKLE_VERSION, "Swashbuckle version: 3.0.0, 4.0.0, 5.0.0");
- protected CliOption aspnetCoreVersion = new CliOption(ASPNET_CORE_VERSION, "ASP.NET Core version: 3.1, 3.0, 2.2, 2.1, 2.0 (deprecated)");
+ protected CliOption aspnetCoreVersion = new CliOption(ASPNET_CORE_VERSION, "ASP.NET Core version: 5.0, 3.1, 3.0, 2.2, 2.1, 2.0 (deprecated)");
private CliOption classModifier = new CliOption(CLASS_MODIFIER, "Class Modifier for controller classes: Empty string or abstract.");
private CliOption operationModifier = new CliOption(OPERATION_MODIFIER, "Operation Modifier can be virtual or abstract");
private CliOption modelClassModifier = new CliOption(MODEL_CLASS_MODIFIER, "Model Class Modifier can be nothing or partial");
@@ -123,7 +124,7 @@ public class AspNetCoreServerCodegen extends AbstractCSharpCodegen {
modelTemplateFiles.put("model.mustache", ".cs");
apiTemplateFiles.put("controller.mustache", ".cs");
- embeddedTemplateDir = templateDir = "aspnetcore/2.1";
+ embeddedTemplateDir = templateDir = "aspnetcore/3.0";
// contextually reserved words
// NOTE: C# uses camel cased reserved words, while models are title cased. We don't want lowercase comparisons.
@@ -190,6 +191,7 @@ public class AspNetCoreServerCodegen extends AbstractCSharpCodegen {
aspnetCoreVersion.addEnum("2.2", "ASP.NET Core 2.2");
aspnetCoreVersion.addEnum("3.0", "ASP.NET Core 3.0");
aspnetCoreVersion.addEnum("3.1", "ASP.NET Core 3.1");
+ aspnetCoreVersion.addEnum("5.0", "ASP.NET Core 5.0");
aspnetCoreVersion.setDefault("3.1");
aspnetCoreVersion.setOptValue(aspnetCoreVersion.getDefault());
addOption(aspnetCoreVersion.getOpt(), aspnetCoreVersion.getDescription(), aspnetCoreVersion.getOptValue());
@@ -367,7 +369,7 @@ public class AspNetCoreServerCodegen extends AbstractCSharpCodegen {
supportingFiles.add(new SupportingFile("gitignore", packageFolder, ".gitignore"));
supportingFiles.add(new SupportingFile("validateModel.mustache", packageFolder + File.separator + "Attributes", "ValidateModelStateAttribute.cs"));
supportingFiles.add(new SupportingFile("typeConverter.mustache", packageFolder + File.separator + "Converters", "CustomEnumConverter.cs"));
- if (aspnetCoreVersion.getOptValue().startsWith("3.")) {
+ if (aspnetCoreVersion.getOptValue().startsWith("3.") || aspnetCoreVersion.getOptValue().startsWith("5.0")) {
supportingFiles.add(new SupportingFile("OpenApi" + File.separator + "TypeExtensions.mustache", packageFolder + File.separator + "OpenApi", "TypeExtensions.cs"));
}
supportingFiles.add(new SupportingFile("Project.csproj.mustache", packageFolder, packageName + ".csproj"));
@@ -535,7 +537,7 @@ public class AspNetCoreServerCodegen extends AbstractCSharpCodegen {
private void setAspnetCoreVersion(String packageFolder) {
setCliOption(aspnetCoreVersion);
- if (aspnetCoreVersion.getOptValue().startsWith("3.")) {
+ if (aspnetCoreVersion.getOptValue().startsWith("3.") || aspnetCoreVersion.getOptValue().startsWith("5.0")) {
compatibilityVersion = null;
} else if ("2.0".equals(aspnetCoreVersion.getOptValue())) {
compatibilityVersion = null;
@@ -552,6 +554,7 @@ public class AspNetCoreServerCodegen extends AbstractCSharpCodegen {
private String determineTemplateVersion(String frameworkVersion) {
switch (frameworkVersion) {
+ case "5.0":
case "3.1":
return "3.0";
@@ -593,17 +596,25 @@ public class AspNetCoreServerCodegen extends AbstractCSharpCodegen {
LOGGER.warn("ASP.NET core version is " + aspnetCoreVersion.getOptValue() + " so changing to use frameworkReference instead of packageReference ");
useFrameworkReference = true;
additionalProperties.put(USE_FRAMEWORK_REFERENCE, useFrameworkReference);
+ additionalProperties.put(TARGET_FRAMEWORK, "netcoreapp" + aspnetCoreVersion);
+ } else if (aspnetCoreVersion.getOptValue().startsWith("5.")) {// default, do nothing
+ LOGGER.warn("ASP.NET core version is " + aspnetCoreVersion.getOptValue() + " so changing to use frameworkReference instead of packageReference ");
+ useFrameworkReference = true;
+ additionalProperties.put(USE_FRAMEWORK_REFERENCE, useFrameworkReference);
+ additionalProperties.put(TARGET_FRAMEWORK, "net5.0");
} else {
if (additionalProperties.containsKey(USE_FRAMEWORK_REFERENCE)) {
useFrameworkReference = convertPropertyToBooleanAndWriteBack(USE_FRAMEWORK_REFERENCE);
} else {
additionalProperties.put(USE_FRAMEWORK_REFERENCE, useFrameworkReference);
}
+ additionalProperties.put(TARGET_FRAMEWORK, "netcoreapp" + aspnetCoreVersion);
}
}
private void setUseNewtonsoft() {
if (aspnetCoreVersion.getOptValue().startsWith("2.")) {
+ LOGGER.warn("ASP.NET core version 2.X support has been deprecated. Please use ASP.NET core version 3.1 instead");
LOGGER.warn("ASP.NET core version is " + aspnetCoreVersion.getOptValue() + " so staying on default json library.");
useNewtonsoft = false;
additionalProperties.put(USE_NEWTONSOFT, useNewtonsoft);
@@ -617,7 +628,7 @@ public class AspNetCoreServerCodegen extends AbstractCSharpCodegen {
}
private void setUseEndpointRouting() {
- if (aspnetCoreVersion.getOptValue().startsWith("3.")) {
+ if (aspnetCoreVersion.getOptValue().startsWith("3.") || aspnetCoreVersion.getOptValue().startsWith("5.")) {
LOGGER.warn("ASP.NET core version is " + aspnetCoreVersion.getOptValue() + " so switching to old style endpoint routing.");
useDefaultRouting = false;
additionalProperties.put(USE_DEFAULT_ROUTING, useDefaultRouting);
@@ -633,7 +644,7 @@ public class AspNetCoreServerCodegen extends AbstractCSharpCodegen {
private void setSwashbuckleVersion() {
setCliOption(swashbuckleVersion);
- if (aspnetCoreVersion.getOptValue().startsWith("3.")) {
+ if (aspnetCoreVersion.getOptValue().startsWith("3.") || aspnetCoreVersion.getOptValue().startsWith("5.")) {
LOGGER.warn("ASP.NET core version is " + aspnetCoreVersion.getOptValue() + " so changing default Swashbuckle version to 5.0.0.");
swashbuckleVersion.setOptValue("5.0.0");
additionalProperties.put(SWASHBUCKLE_VERSION, swashbuckleVersion.getOptValue());
diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/BashClientCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/BashClientCodegen.java
index 13c10ae2c9..ea212c92f1 100644
--- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/BashClientCodegen.java
+++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/BashClientCodegen.java
@@ -39,7 +39,7 @@ import java.util.*;
import static org.openapitools.codegen.utils.StringUtils.*;
public class BashClientCodegen extends DefaultCodegen implements CodegenConfig {
- private static final Logger LOGGER = LoggerFactory.getLogger(BashClientCodegen.class);
+ private final Logger LOGGER = LoggerFactory.getLogger(BashClientCodegen.class);
protected String apiVersion = "1.0.0";
diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/CLibcurlClientCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/CLibcurlClientCodegen.java
index 62d1a13f9c..c87ec1dc0e 100644
--- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/CLibcurlClientCodegen.java
+++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/CLibcurlClientCodegen.java
@@ -34,7 +34,7 @@ import static org.openapitools.codegen.utils.StringUtils.camelize;
import static org.openapitools.codegen.utils.StringUtils.underscore;
public class CLibcurlClientCodegen extends DefaultCodegen implements CodegenConfig {
- private static final Logger LOGGER = LoggerFactory.getLogger(CLibcurlClientCodegen.class);
+ private final Logger LOGGER = LoggerFactory.getLogger(CLibcurlClientCodegen.class);
public static final String PROJECT_NAME = "projectName";
protected String moduleName;
diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/CSharpClientCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/CSharpClientCodegen.java
index 9b8117a8fd..bae1eb7250 100644
--- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/CSharpClientCodegen.java
+++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/CSharpClientCodegen.java
@@ -36,7 +36,7 @@ import static org.openapitools.codegen.utils.StringUtils.underscore;
public class CSharpClientCodegen extends AbstractCSharpCodegen {
@SuppressWarnings({"hiding"})
- private static final Logger LOGGER = LoggerFactory.getLogger(CSharpClientCodegen.class);
+ private final Logger LOGGER = LoggerFactory.getLogger(CSharpClientCodegen.class);
private static final String NUNIT = "nunit";
private static final String RESTSHARP = "restsharp";
private static final String NEWTONSOFT_JSON = "newtonsoft-json";
diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/CSharpDotNet2ClientCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/CSharpDotNet2ClientCodegen.java
index d76aa736d5..d9b2f5d5c2 100644
--- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/CSharpDotNet2ClientCodegen.java
+++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/CSharpDotNet2ClientCodegen.java
@@ -31,7 +31,7 @@ import org.slf4j.LoggerFactory;
import java.io.File;
public class CSharpDotNet2ClientCodegen extends AbstractCSharpCodegen {
- private static final Logger LOGGER = LoggerFactory.getLogger(CSharpDotNet2ClientCodegen.class);
+ private final Logger LOGGER = LoggerFactory.getLogger(CSharpDotNet2ClientCodegen.class);
public static final String CLIENT_PACKAGE = "clientPackage";
protected String clientPackage = "Org.OpenAPITools.Client";
diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/CSharpNancyFXServerCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/CSharpNancyFXServerCodegen.java
index 93c2d0d213..88815de2f2 100644
--- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/CSharpNancyFXServerCodegen.java
+++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/CSharpNancyFXServerCodegen.java
@@ -42,7 +42,7 @@ import static org.openapitools.codegen.CodegenType.SERVER;
import static org.openapitools.codegen.utils.StringUtils.camelize;
public class CSharpNancyFXServerCodegen extends AbstractCSharpCodegen {
- private static final Logger LOGGER = LoggerFactory.getLogger(CSharpNancyFXServerCodegen.class);
+ private final Logger LOGGER = LoggerFactory.getLogger(CSharpNancyFXServerCodegen.class);
private static final String API_NAMESPACE = "Modules";
private static final String MODEL_NAMESPACE = "Models";
diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/CSharpNetCoreClientCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/CSharpNetCoreClientCodegen.java
index 91763105be..8aa4cc08ff 100644
--- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/CSharpNetCoreClientCodegen.java
+++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/CSharpNetCoreClientCodegen.java
@@ -20,6 +20,7 @@ import com.google.common.collect.ImmutableMap;
import com.samskivert.mustache.Mustache;
import io.swagger.v3.oas.models.media.ArraySchema;
import io.swagger.v3.oas.models.media.Schema;
+import io.swagger.v3.parser.util.SchemaTypeUtil;
import org.openapitools.codegen.*;
import org.openapitools.codegen.meta.features.*;
import org.openapitools.codegen.utils.ModelUtils;
@@ -42,9 +43,14 @@ public class CSharpNetCoreClientCodegen extends AbstractCSharpCodegen {
// Defines the sdk option for targeted frameworks, which differs from targetFramework and targetFrameworkNuget
protected static final String MCS_NET_VERSION_KEY = "x-mcs-sdk";
protected static final String SUPPORTS_UWP = "supportsUWP";
+ protected static final String SUPPORTS_RETRY = "supportsRetry";
protected static final String NET_STANDARD = "netStandard";
+ // HTTP libraries
+ protected static final String RESTSHARP = "restsharp";
+ protected static final String HTTPCLIENT = "httpclient";
+
// Project Variable, determined from target framework. Not intended to be user-settable.
protected static final String TARGET_FRAMEWORK_IDENTIFIER = "targetFrameworkIdentifier";
// Project Variable, determined from target framework. Not intended to be user-settable.
@@ -80,6 +86,7 @@ public class CSharpNetCoreClientCodegen extends AbstractCSharpCodegen {
// Defines nuget identifiers for target framework
protected String targetFrameworkNuget = targetFramework;
+ protected boolean supportsRetry = Boolean.TRUE;
protected boolean supportsAsync = Boolean.TRUE;
protected boolean netStandard = Boolean.FALSE;
@@ -94,6 +101,9 @@ public class CSharpNetCoreClientCodegen extends AbstractCSharpCodegen {
protected String packageTags;
protected boolean useOneOfDiscriminatorLookup = false; // use oneOf discriminator's mapping for model lookup
+ protected boolean needsCustomHttpMethod = false;
+ protected boolean needsUriBuilder = false;
+
public CSharpNetCoreClientCodegen() {
super();
@@ -290,6 +300,16 @@ public class CSharpNetCoreClientCodegen extends AbstractCSharpCodegen {
regexModifiers.put('m', "Multiline");
regexModifiers.put('s', "Singleline");
regexModifiers.put('x', "IgnorePatternWhitespace");
+
+ supportedLibraries.put(HTTPCLIENT, "HttpClient (https://docs.microsoft.com/en-us/dotnet/api/system.net.http.httpclient) (Beta support)");
+ supportedLibraries.put(RESTSHARP, "RestSharp (https://github.com/restsharp/RestSharp)");
+
+ CliOption libraryOption = new CliOption(CodegenConstants.LIBRARY, "HTTP library template (sub-template) to use");
+ libraryOption.setEnum(supportedLibraries);
+ // set RESTSHARP as the default
+ libraryOption.setDefault(RESTSHARP);
+ cliOptions.add(libraryOption);
+ setLibrary(RESTSHARP);
}
@Override
@@ -556,8 +576,20 @@ public class CSharpNetCoreClientCodegen extends AbstractCSharpCodegen {
if (isEmpty(modelPackage)) {
setModelPackage("Model");
}
+
clientPackage = "Client";
+ if (RESTSHARP.equals(getLibrary())) {
+ additionalProperties.put("useRestSharp", true);
+ needsCustomHttpMethod = true;
+ } else if (HTTPCLIENT.equals(getLibrary())) {
+ setLibrary(HTTPCLIENT);
+ additionalProperties.put("useHttpClient", true);
+ needsUriBuilder = true;
+ } else {
+ throw new RuntimeException("Invalid HTTP library " + getLibrary() + ". Only restsharp, httpclient are supported.");
+ }
+
String framework = (String) additionalProperties.getOrDefault(CodegenConstants.DOTNET_FRAMEWORK, defaultFramework.name);
boolean strategyMatched = false;
FrameworkStrategy strategy = defaultFramework;
@@ -578,7 +610,6 @@ public class CSharpNetCoreClientCodegen extends AbstractCSharpCodegen {
}
strategy.configureAdditionalProperties(additionalProperties);
-
setTargetFrameworkNuget(strategy.getNugetFrameworkIdentifier());
setTargetFramework(strategy.name);
setTestTargetFramework(strategy.testTargetFramework);
@@ -614,6 +645,7 @@ public class CSharpNetCoreClientCodegen extends AbstractCSharpCodegen {
syncBooleanProperty(additionalProperties, CodegenConstants.VALIDATABLE, this::setValidatable, this.validatable);
syncBooleanProperty(additionalProperties, CodegenConstants.SUPPORTS_ASYNC, this::setSupportsAsync, this.supportsAsync);
+ syncBooleanProperty(additionalProperties, SUPPORTS_RETRY, this::setSupportsRetry, this.supportsRetry);
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);
@@ -644,7 +676,12 @@ public class CSharpNetCoreClientCodegen extends AbstractCSharpCodegen {
supportingFiles.add(new SupportingFile("ExceptionFactory.mustache", clientPackageDir, "ExceptionFactory.cs"));
supportingFiles.add(new SupportingFile("OpenAPIDateConverter.mustache", clientPackageDir, "OpenAPIDateConverter.cs"));
supportingFiles.add(new SupportingFile("ClientUtils.mustache", clientPackageDir, "ClientUtils.cs"));
- supportingFiles.add(new SupportingFile("HttpMethod.mustache", clientPackageDir, "HttpMethod.cs"));
+ if(needsCustomHttpMethod) {
+ supportingFiles.add(new SupportingFile("HttpMethod.mustache", clientPackageDir, "HttpMethod.cs"));
+ }
+ if(needsUriBuilder) {
+ supportingFiles.add(new SupportingFile("WebRequestPathBuilder.mustache", clientPackageDir, "WebRequestPathBuilder.cs"));
+ }
if (ProcessUtils.hasHttpSignatureMethods(openAPI)) {
supportingFiles.add(new SupportingFile("HttpSigningConfiguration.mustache", clientPackageDir, "HttpSigningConfiguration.cs"));
}
@@ -654,7 +691,10 @@ public class CSharpNetCoreClientCodegen extends AbstractCSharpCodegen {
supportingFiles.add(new SupportingFile("ISynchronousClient.mustache", clientPackageDir, "ISynchronousClient.cs"));
supportingFiles.add(new SupportingFile("RequestOptions.mustache", clientPackageDir, "RequestOptions.cs"));
supportingFiles.add(new SupportingFile("Multimap.mustache", clientPackageDir, "Multimap.cs"));
- supportingFiles.add(new SupportingFile("RetryConfiguration.mustache", clientPackageDir, "RetryConfiguration.cs"));
+
+ if (supportsRetry) {
+ supportingFiles.add(new SupportingFile("RetryConfiguration.mustache", clientPackageDir, "RetryConfiguration.cs"));
+ }
supportingFiles.add(new SupportingFile("IReadableConfiguration.mustache",
clientPackageDir, "IReadableConfiguration.cs"));
@@ -717,6 +757,10 @@ public class CSharpNetCoreClientCodegen extends AbstractCSharpCodegen {
this.supportsAsync = supportsAsync;
}
+ public void setSupportsRetry(Boolean supportsRetry) {
+ this.supportsRetry = supportsRetry;
+ }
+
public void setTargetFramework(String dotnetFramework) {
if (!frameworks.containsKey(dotnetFramework)) {
throw new IllegalArgumentException("Invalid .NET framework version: " +
@@ -1009,4 +1053,16 @@ public class CSharpNetCoreClientCodegen extends AbstractCSharpCodegen {
return objs;
}
+
+ @Override
+ public void postProcess() {
+ System.out.println("################################################################################");
+ System.out.println("# Thanks for using OpenAPI Generator. #");
+ System.out.println("# Please consider donation to help us maintain this project \uD83D\uDE4F #");
+ System.out.println("# https://opencollective.com/openapi_generator/donate #");
+ System.out.println("# #");
+ System.out.println("# This generator's contributed by Jim Schubert (https://github.com/jimschubert)#");
+ System.out.println("# Please support his work directly via https://patreon.com/jimschubert \uD83D\uDE4F #");
+ System.out.println("################################################################################");
+ }
}
diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/ClojureClientCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/ClojureClientCodegen.java
index 5af22a8d3f..c2a23a978e 100644
--- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/ClojureClientCodegen.java
+++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/ClojureClientCodegen.java
@@ -38,7 +38,7 @@ import static org.openapitools.codegen.utils.StringUtils.dashize;
import static org.openapitools.codegen.utils.StringUtils.underscore;
public class ClojureClientCodegen extends DefaultCodegen implements CodegenConfig {
- private static final Logger LOGGER = LoggerFactory.getLogger(ClojureClientCodegen.class);
+ private final Logger LOGGER = LoggerFactory.getLogger(ClojureClientCodegen.class);
private static final String PROJECT_NAME = "projectName";
private static final String PROJECT_DESCRIPTION = "projectDescription";
private static final String PROJECT_VERSION = "projectVersion";
diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/CppPistacheServerCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/CppPistacheServerCodegen.java
index 6cd08e70a4..b4507ff180 100644
--- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/CppPistacheServerCodegen.java
+++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/CppPistacheServerCodegen.java
@@ -36,7 +36,7 @@ import static org.openapitools.codegen.utils.OnceLogger.once;
import static org.openapitools.codegen.utils.StringUtils.underscore;
public class CppPistacheServerCodegen extends AbstractCppCodegen {
- private static final Logger LOGGER = LoggerFactory.getLogger(CppPistacheServerCodegen.class);
+ private final Logger LOGGER = LoggerFactory.getLogger(CppPistacheServerCodegen.class);
protected String implFolder = "impl";
protected boolean isAddExternalLibs = true;
diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/CppQt5AbstractCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/CppQt5AbstractCodegen.java
index c322718221..1c4aa5c608 100644
--- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/CppQt5AbstractCodegen.java
+++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/CppQt5AbstractCodegen.java
@@ -16,7 +16,7 @@ import java.util.*;
import static org.openapitools.codegen.utils.OnceLogger.once;
public class CppQt5AbstractCodegen extends AbstractCppCodegen implements CodegenConfig {
- private static final Logger LOGGER = LoggerFactory.getLogger(CppQt5AbstractCodegen.class);
+ private final Logger LOGGER = LoggerFactory.getLogger(CppQt5AbstractCodegen.class);
protected final String PREFIX = "OAI";
protected String apiVersion = "1.0.0";
protected static final String CPP_NAMESPACE = "cppNamespace";
@@ -105,6 +105,7 @@ public class CppQt5AbstractCodegen extends AbstractCppCodegen implements Codegen
typeMapping.put("number", "double");
typeMapping.put("array", "QList");
typeMapping.put("map", "QMap");
+ typeMapping.put("set", "QSet");
typeMapping.put("object", PREFIX + "Object");
// mapped as "file" type for OAS 3.0
typeMapping.put("ByteArray", "QByteArray");
@@ -122,6 +123,7 @@ public class CppQt5AbstractCodegen extends AbstractCppCodegen implements Codegen
systemIncludes.add("QString");
systemIncludes.add("QList");
systemIncludes.add("QMap");
+ systemIncludes.add("QSet");
systemIncludes.add("QDate");
systemIncludes.add("QDateTime");
systemIncludes.add("QByteArray");
diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/CrystalClientCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/CrystalClientCodegen.java
index 7a5b347180..6af013a177 100644
--- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/CrystalClientCodegen.java
+++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/CrystalClientCodegen.java
@@ -42,7 +42,7 @@ import static org.openapitools.codegen.utils.StringUtils.camelize;
import static org.openapitools.codegen.utils.StringUtils.underscore;
public class CrystalClientCodegen extends DefaultCodegen {
- private static final Logger LOGGER = LoggerFactory.getLogger(CrystalClientCodegen.class);
+ private final Logger LOGGER = LoggerFactory.getLogger(CrystalClientCodegen.class);
private static final String NUMERIC_ENUM_PREFIX = "N";
protected static int emptyMethodNameCounter = 0;
diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/DartClientCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/DartClientCodegen.java
index 91b1f05ddd..266fbee013 100644
--- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/DartClientCodegen.java
+++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/DartClientCodegen.java
@@ -17,290 +17,51 @@
package org.openapitools.codegen.languages;
-import java.io.BufferedReader;
-import java.io.File;
-import java.io.IOException;
-import java.io.InputStreamReader;
-import java.net.URI;
-import java.net.URISyntaxException;
-import java.nio.charset.StandardCharsets;
-import java.nio.file.*;
-import java.util.*;
-import java.util.stream.Collectors;
-
-import com.google.common.collect.Lists;
-import com.google.common.collect.Sets;
-
-import io.swagger.v3.oas.models.Operation;
-import io.swagger.v3.oas.models.media.StringSchema;
-import io.swagger.v3.oas.models.servers.Server;
-import org.apache.commons.io.FilenameUtils;
-import org.apache.commons.lang3.StringUtils;
-import org.openapitools.codegen.*;
-import org.openapitools.codegen.meta.features.ClientModificationFeature;
-import org.openapitools.codegen.meta.features.DocumentationFeature;
-import org.openapitools.codegen.meta.features.GlobalFeature;
-import org.openapitools.codegen.meta.features.ParameterFeature;
-import org.openapitools.codegen.meta.features.SchemaSupportFeature;
-import org.openapitools.codegen.meta.features.SecurityFeature;
-import org.openapitools.codegen.utils.ModelUtils;
+import org.openapitools.codegen.CliOption;
+import org.openapitools.codegen.CodegenConstants;
+import org.openapitools.codegen.SupportingFile;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import io.swagger.v3.oas.models.media.ArraySchema;
-import io.swagger.v3.oas.models.media.Schema;
+import java.io.File;
+import java.util.HashMap;
+import java.util.Map;
-import static org.openapitools.codegen.utils.StringUtils.*;
+public class DartClientCodegen extends AbstractDartCodegen {
-public class DartClientCodegen extends DefaultCodegen {
- private static final Logger LOGGER = LoggerFactory.getLogger(DartClientCodegen.class);
+ private final Logger LOGGER = LoggerFactory.getLogger(DartClientCodegen.class);
- public static final String PUB_LIBRARY = "pubLibrary";
- public static final String PUB_NAME = "pubName";
- public static final String PUB_VERSION = "pubVersion";
- public static final String PUB_DESCRIPTION = "pubDescription";
- public static final String PUB_AUTHOR = "pubAuthor";
- public static final String PUB_AUTHOR_EMAIL = "pubAuthorEmail";
- public static final String PUB_HOMEPAGE = "pubHomepage";
- public static final String USE_ENUM_EXTENSION = "useEnumExtension";
-
- protected String pubLibrary = "openapi.api";
- protected String pubName = "openapi";
- protected String pubVersion = "1.0.0";
- protected String pubDescription = "OpenAPI API client";
- protected String pubAuthor = "Author";
- protected String pubAuthorEmail = "author@homepage";
- protected String pubHomepage = "homepage";
- protected boolean useEnumExtension = false;
- protected String sourceFolder = "";
- protected String apiDocPath = "doc" + File.separator;
- protected String modelDocPath = "doc" + File.separator;
- protected String apiTestPath = "test" + File.separator;
- protected String modelTestPath = "test" + File.separator;
-
- // Names that must not be used as model names because they clash with existing
- // default imports (dart:io, dart:async, package:http etc.) but are not basic dataTypes.
- protected Set additionalReservedWords;
+ public static final String SERIALIZATION_LIBRARY_NATIVE = "native_serialization";
+ public static final String SERIALIZATION_LIBRARY_JSON_SERIALIZABLE = "json_serializable";
public DartClientCodegen() {
super();
- modifyFeatureSet(features -> features
- .includeDocumentationFeatures(DocumentationFeature.Readme)
- .securityFeatures(EnumSet.of(
- SecurityFeature.OAuth2_Implicit,
- SecurityFeature.BasicAuth,
- SecurityFeature.ApiKey
- ))
- .excludeGlobalFeatures(
- GlobalFeature.XMLStructureDefinitions,
- GlobalFeature.Callbacks,
- GlobalFeature.LinkObjects,
- GlobalFeature.ParameterStyling
- )
- .excludeSchemaSupportFeatures(
- SchemaSupportFeature.Polymorphism
- )
- .includeParameterFeatures(
- ParameterFeature.Cookie
- )
- .includeClientModificationFeatures(
- ClientModificationFeature.BasePath
- )
- );
+ final CliOption serializationLibrary = new CliOption(CodegenConstants.SERIALIZATION_LIBRARY,
+ "Specify serialization library");
+ serializationLibrary.setDefault(SERIALIZATION_LIBRARY_NATIVE);
+ serializationLibrary.setType("String");
- outputFolder = "generated-code/dart";
- modelTemplateFiles.put("model.mustache", ".dart");
- apiTemplateFiles.put("api.mustache", ".dart");
- embeddedTemplateDir = templateDir = "dart2";
- apiPackage = "lib.api";
- modelPackage = "lib.model";
- modelDocTemplateFiles.put("object_doc.mustache", ".md");
- apiDocTemplateFiles.put("api_doc.mustache", ".md");
-
- modelTestTemplateFiles.put("model_test.mustache", ".dart");
- apiTestTemplateFiles.put("api_test.mustache", ".dart");
-
- final List reservedWordsList = new ArrayList<>();
- try(BufferedReader reader = new BufferedReader(
- new InputStreamReader(DartClientCodegen.class.getResourceAsStream("/dart/dart-keywords.txt"),
- StandardCharsets.UTF_8))) {
- while (reader.ready()) {
- reservedWordsList.add(reader.readLine());
- }
- } catch (Exception e) {
- LOGGER.error("Error reading dart keywords. Exception: {}", e.getMessage());
- }
- setReservedWordsLowerCase(reservedWordsList);
-
- languageSpecificPrimitives = Sets.newHashSet(
- "String",
- "bool",
- "int",
- "num",
- "double",
- "dynamic"
- );
-
- typeMapping = new HashMap<>();
- typeMapping.put("Array", "List");
- typeMapping.put("array", "List");
- typeMapping.put("map", "Map");
- typeMapping.put("List", "List");
- typeMapping.put("set", "Set");
- typeMapping.put("boolean", "bool");
- typeMapping.put("string", "String");
- typeMapping.put("char", "String");
- typeMapping.put("int", "int");
- typeMapping.put("long", "int");
- typeMapping.put("short", "int");
- typeMapping.put("number", "num");
- typeMapping.put("float", "double");
- typeMapping.put("double", "double");
- typeMapping.put("decimal", "double");
- typeMapping.put("integer", "int");
- typeMapping.put("Date", "DateTime");
- typeMapping.put("date", "DateTime");
- typeMapping.put("DateTime", "DateTime");
- typeMapping.put("file", "MultipartFile");
- typeMapping.put("binary", "MultipartFile");
- typeMapping.put("UUID", "String");
- typeMapping.put("URI", "String");
- typeMapping.put("ByteArray", "String");
- typeMapping.put("object", "Object");
- typeMapping.put("AnyType", "Object");
-
- // DataTypes of the above values which are automatically imported.
- // They are also not allowed to be model names.
- defaultIncludes = Sets.newHashSet(
- "String",
- "bool",
- "int",
- "num",
- "double",
- "dynamic",
- "List",
- "Set",
- "Map",
- "DateTime",
- "Object",
- "MultipartFile"
- );
-
- additionalReservedWords = Sets.newHashSet(
- "File",
- "Client",
- "Future",
- "Response"
- );
-
- cliOptions.add(new CliOption(PUB_LIBRARY, "Library name in generated code"));
- cliOptions.add(new CliOption(PUB_NAME, "Name in generated pubspec"));
- cliOptions.add(new CliOption(PUB_VERSION, "Version in generated pubspec"));
- cliOptions.add(new CliOption(PUB_DESCRIPTION, "Description in generated pubspec"));
- cliOptions.add(new CliOption(PUB_AUTHOR, "Author name in generated pubspec"));
- cliOptions.add(new CliOption(PUB_AUTHOR_EMAIL, "Email address of the author in generated pubspec"));
- cliOptions.add(new CliOption(PUB_HOMEPAGE, "Homepage in generated pubspec"));
- cliOptions.add(new CliOption(USE_ENUM_EXTENSION, "Allow the 'x-enum-values' extension for enums"));
- cliOptions.add(new CliOption(CodegenConstants.SOURCE_FOLDER, "Source folder for generated code"));
- }
-
- @Override
- public CodegenType getTag() {
- return CodegenType.CLIENT;
- }
-
- @Override
- public String getName() {
- return "dart";
- }
-
- @Override
- public String getHelp() {
- return "Generates a Dart 2.x client library.";
- }
-
- protected void defaultProcessOpts() {
- super.processOpts();
+ final Map serializationOptions = new HashMap<>();
+ serializationOptions.put(SERIALIZATION_LIBRARY_NATIVE, "Use native serializer, backwards compatible");
+ serializationOptions.put(SERIALIZATION_LIBRARY_JSON_SERIALIZABLE, "Use json_serializable");
+ serializationLibrary.setEnum(serializationOptions);
+ cliOptions.add(serializationLibrary);
}
@Override
public void processOpts() {
- defaultProcessOpts();
+ super.processOpts();
- if (StringUtils.isEmpty(System.getenv("DART_POST_PROCESS_FILE"))) {
- LOGGER.info("Environment variable DART_POST_PROCESS_FILE not defined so the Dart code may not be properly formatted. To define it, try `export DART_POST_PROCESS_FILE=\"/usr/local/bin/dartfmt -w\"` (Linux/Mac)");
- LOGGER.info("NOTE: To enable file post-processing, 'enablePostProcessFile' must be set to `true` (--enable-post-process-file for CLI).");
- }
-
- if (additionalProperties.containsKey(PUB_NAME)) {
- this.setPubName((String) additionalProperties.get(PUB_NAME));
+ // handle library not being set
+ if(additionalProperties.get(CodegenConstants.SERIALIZATION_LIBRARY) == null) {
+ this.library = SERIALIZATION_LIBRARY_NATIVE;
+ LOGGER.debug("Serialization library not set, using default {}", SERIALIZATION_LIBRARY_NATIVE);
} else {
- //not set, use to be passed to template
- additionalProperties.put(PUB_NAME, pubName);
+ this.library = additionalProperties.get(CodegenConstants.SERIALIZATION_LIBRARY).toString();
}
- if (additionalProperties.containsKey(PUB_LIBRARY)) {
- this.setPubLibrary((String) additionalProperties.get(PUB_LIBRARY));
- } else {
- //not set, use to be passed to template
- additionalProperties.put(PUB_LIBRARY, pubLibrary);
- }
-
- if (additionalProperties.containsKey(PUB_VERSION)) {
- this.setPubVersion((String) additionalProperties.get(PUB_VERSION));
- } else {
- //not set, use to be passed to template
- additionalProperties.put(PUB_VERSION, pubVersion);
- }
-
- if (additionalProperties.containsKey(PUB_DESCRIPTION)) {
- this.setPubDescription((String) additionalProperties.get(PUB_DESCRIPTION));
- } else {
- //not set, use to be passed to template
- additionalProperties.put(PUB_DESCRIPTION, pubDescription);
- }
-
- if (additionalProperties.containsKey(PUB_AUTHOR)) {
- this.setPubAuthor((String) additionalProperties.get(PUB_AUTHOR));
- } else {
- //not set, use to be passed to template
- additionalProperties.put(PUB_AUTHOR, pubAuthor);
- }
-
- if (additionalProperties.containsKey(PUB_AUTHOR_EMAIL)) {
- this.setPubAuthorEmail((String) additionalProperties.get(PUB_AUTHOR_EMAIL));
- } else {
- //not set, use to be passed to template
- additionalProperties.put(PUB_AUTHOR_EMAIL, pubAuthorEmail);
- }
-
- if (additionalProperties.containsKey(PUB_HOMEPAGE)) {
- this.setPubHomepage((String) additionalProperties.get(PUB_HOMEPAGE));
- } else {
- //not set, use to be passed to template
- additionalProperties.put(PUB_HOMEPAGE, pubHomepage);
- }
-
- if (additionalProperties.containsKey(USE_ENUM_EXTENSION)) {
- this.setUseEnumExtension(convertPropertyToBooleanAndWriteBack(USE_ENUM_EXTENSION));
- } else {
- // Not set, use to be passed to template.
- additionalProperties.put(USE_ENUM_EXTENSION, useEnumExtension);
- }
-
- if (additionalProperties.containsKey(CodegenConstants.SOURCE_FOLDER)) {
- this.setSourceFolder((String) additionalProperties.get(CodegenConstants.SOURCE_FOLDER));
- }
-
- // make api and model doc path available in mustache template
- additionalProperties.put("apiDocPath", apiDocPath);
- additionalProperties.put("modelDocPath", modelDocPath);
-
- // check to not overwrite a custom templateDir
- if (templateDir == null) {
- embeddedTemplateDir = templateDir = "dart2";
- }
+ this.setSerializationLibrary();
final String libFolder = sourceFolder + File.separator + "lib";
supportingFiles.add(new SupportingFile("pubspec.mustache", "", "pubspec.yaml"));
@@ -319,410 +80,26 @@ public class DartClientCodegen extends DefaultCodegen {
supportingFiles.add(new SupportingFile("gitignore.mustache", "", ".gitignore"));
supportingFiles.add(new SupportingFile("README.mustache", "", "README.md"));
supportingFiles.add(new SupportingFile("travis.mustache", "", ".travis.yml"));
+
}
- @Override
- protected boolean isReservedWord(String word) {
- // consider everything as reserved that is either a keyword,
- // a default included type, or a type include through some library
- return super.isReservedWord(word) ||
- defaultIncludes().contains(word) ||
- additionalReservedWords.contains(word);
- }
+ private void setSerializationLibrary() {
+ final String serialization_library = getLibrary();
+ LOGGER.info("Using serialization library {}", serialization_library);
- @Override
- public String escapeReservedWord(String name) {
- return name + "_";
- }
+ switch (serialization_library) {
+ case SERIALIZATION_LIBRARY_JSON_SERIALIZABLE:
+ additionalProperties.put(SERIALIZATION_LIBRARY_JSON_SERIALIZABLE, "true");
+ // json_serializable requires build.yaml
+ supportingFiles.add(new SupportingFile("build.yaml.mustache",
+ "" /* main project dir */,
+ "build.yaml"));
+ break;
- @Override
- public String apiFileFolder() {
- return outputFolder + File.separator + sourceFolder + File.separator + apiPackage().replace('.', File.separatorChar);
- }
+ case SERIALIZATION_LIBRARY_NATIVE: // fall trough to default backwards compatible generator
+ default:
+ additionalProperties.put(SERIALIZATION_LIBRARY_NATIVE, "true");
- @Override
- public String modelFileFolder() {
- return outputFolder + File.separator + sourceFolder + File.separator + modelPackage().replace('.', File.separatorChar);
- }
-
- @Override
- public String apiTestFileFolder() {
- return outputFolder + File.separator + apiTestPath.replace('/', File.separatorChar);
- }
-
- @Override
- public String modelTestFileFolder() {
- return outputFolder + File.separator + modelTestPath.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);
- }
-
- @Override
- public String toVarName(String name) {
- // replace - with _ e.g. created-at => created_at
- name = name.replace("-", "_");
-
- // always need to replace leading underscores first
- name = name.replaceAll("^_", "");
-
- // if it's all upper case, do nothing
- if (name.matches("^[A-Z_]*$")) {
- return name;
- }
-
- // replace all characters that have a mapping but ignore underscores
- // append an underscore to each replacement so that it can be camelized
- if (name.chars().anyMatch(character -> specialCharReplacements.containsKey("" + ((char) character)))) {
- name = escape(name, specialCharReplacements, Lists.newArrayList("_"), "_");
- }
- // remove the rest
- name = sanitizeName(name);
-
- // camelize (lower first character) the variable name
- // pet_id => petId
- name = camelize(name, true);
-
- if (name.matches("^\\d.*")) {
- name = "n" + name;
- }
-
- if (isReservedWord(name)) {
- name = escapeReservedWord(name);
- }
-
- return name;
- }
-
- @Override
- public String toParamName(String name) {
- // should be the same as variable name
- return toVarName(name);
- }
-
- @Override
- public String toModelName(final String name) {
- String nameWithPrefixSuffix = sanitizeName(name);
- if (!StringUtils.isEmpty(modelNamePrefix)) {
- // add '_' so that model name can be camelized correctly
- nameWithPrefixSuffix = modelNamePrefix + "_" + nameWithPrefixSuffix;
- }
-
- if (!StringUtils.isEmpty(modelNameSuffix)) {
- // add '_' so that model name can be camelized correctly
- nameWithPrefixSuffix = nameWithPrefixSuffix + "_" + modelNameSuffix;
- }
-
- // camelize the model name
- // phone_number => PhoneNumber
- final String camelizedName = camelize(nameWithPrefixSuffix);
-
- // model name cannot use reserved keyword, e.g. return
- if (isReservedWord(camelizedName)) {
- final String modelName = "Model" + camelizedName;
- LOGGER.warn(camelizedName + " (reserved word) cannot be used as model name. Renamed to " + modelName);
- return modelName;
- }
-
- // model name starts with number
- if (camelizedName.matches("^\\d.*")) {
- final String modelName = "Model" + camelizedName; // e.g. 200Response => Model200Response (after camelize)
- LOGGER.warn(name + " (model name starts with number) cannot be used as model name. Renamed to " + modelName);
- return modelName;
- }
-
- return camelizedName;
- }
-
- @Override
- public String toModelFilename(String name) {
- return underscore(toModelName(name));
- }
-
- @Override public String toModelDocFilename(String name) {
- return toModelName(name);
- }
-
- @Override
- public String toApiFilename(String name) {
- return underscore(toApiName(name));
- }
-
- @Override
- public String toApiTestFilename(String name) {
- return toApiFilename(name) + "_test";
- }
-
- @Override
- public String toModelTestFilename(String name) {
- return toModelFilename(name) + "_test";
- }
-
- @Override
- public String toDefaultValue(Schema schema) {
- if (ModelUtils.isMapSchema(schema) || ModelUtils.isSet(schema)) {
- return "const {}";
- }
- if (ModelUtils.isArraySchema(schema)) {
- return "const []";
- }
-
- if (schema.getDefault() != null) {
- if (ModelUtils.isDateSchema(schema) || ModelUtils.isDateTimeSchema(schema)) {
- // this is currently not supported and would create compile errors
- return null;
- }
- if (ModelUtils.isStringSchema(schema)) {
- return "'" + schema.getDefault().toString().replace("'", "\\'") + "'";
- }
- return schema.getDefault().toString();
- }
- return null;
- }
-
- @Override
- public String getTypeDeclaration(Schema p) {
- Schema> schema = ModelUtils.unaliasSchema(this.openAPI, p, importMapping);
- Schema> target = ModelUtils.isGenerateAliasAsModel() ? p : schema;
- if (ModelUtils.isArraySchema(target)) {
- Schema> items = getSchemaItems((ArraySchema) schema);
- return getSchemaType(target) + "<" + getTypeDeclaration(items) + ">";
- }
- if (ModelUtils.isMapSchema(target)) {
- // Note: ModelUtils.isMapSchema(p) returns true when p is a composed schema that also defines
- // additionalproperties: true
- Schema> inner = getAdditionalProperties(target);
- if (inner == null) {
- LOGGER.error("`{}` (map property) does not have a proper inner type defined. Default to type:string", p.getName());
- inner = new StringSchema().description("TODO default missing map inner type to string");
- p.setAdditionalProperties(inner);
- }
- return getSchemaType(target) + "";
- }
- return super.getTypeDeclaration(p);
- }
-
- @Override
- public String getSchemaType(Schema p) {
- String openAPIType = super.getSchemaType(p);
- if (openAPIType == null) {
- LOGGER.error("No Type defined for Schema " + p);
- }
- if (typeMapping.containsKey(openAPIType)) {
- return typeMapping.get(openAPIType);
- }
- if (languageSpecificPrimitives.contains(openAPIType)) {
- return openAPIType;
- }
- return toModelName(openAPIType);
- }
-
- @Override
- public Map postProcessModels(Map objs) {
- return postProcessModelsEnum(objs);
- }
-
- @Override
- public void postProcessModelProperty(CodegenModel model, CodegenProperty property) {
- super.postProcessModelProperty(model, property);
- if (!model.isEnum && property.isEnum) {
- // These are inner enums, enums which do not exist as models, just as properties.
- // They are handled via the enum_inline template and and are generated in the
- // same file as the containing class. To prevent name clashes the inline enum classes
- // are prefix with the classname of the containing class in the template.
- // Here the datatypeWithEnum template variable gets updated to match that scheme.
- // Also taking into account potential collection types e.g. List -> List
- if (property.items != null) {
- // basically inner items e.g. map of maps etc.
- property.setDatatypeWithEnum(property.datatypeWithEnum.replace(property.items.datatypeWithEnum, model.classname + property.items.datatypeWithEnum));
- } else {
- property.setDatatypeWithEnum(property.datatypeWithEnum.replace(property.enumName, model.classname + property.enumName));
- }
- }
- }
-
- @Override
- public CodegenOperation fromOperation(String path, String httpMethod, Operation operation, List servers) {
- final CodegenOperation op = super.fromOperation(path, httpMethod, operation, servers);
- for (CodegenResponse r : op.responses) {
- // By default only set types are automatically added to operation imports, not sure why.
- // Add all container type imports here, by default 'dart:core' imports are skipped
- // but other sub classes may required specific container type imports.
- if (r.containerType != null && typeMapping().containsKey(r.containerType)) {
- final String value = typeMapping().get(r.containerType);
- if (needToImport(value)) {
- op.imports.add(value);
- }
- }
- }
- for (CodegenParameter p : op.allParams) {
- if (p.isContainer) {
- final String type = p.isArray ? "array" : "map";
- if (typeMapping().containsKey(type)) {
- final String value = typeMapping().get(type);
- // Also add container imports for parameters.
- if (needToImport(value)) {
- op.imports.add(value);
- }
- }
- }
- }
- return op;
- }
-
- @Override
- protected void updateEnumVarsWithExtensions(List> enumVars, Map vendorExtensions, String dataType) {
- if (vendorExtensions != null && useEnumExtension && vendorExtensions.containsKey("x-enum-values")) {
- // Use the x-enum-values extension for this enum
- // Existing enumVars added by the default handling need to be removed first
- enumVars.clear();
-
- Object extension = vendorExtensions.get("x-enum-values");
- List> values = (List>) extension;
- for (Map value : values) {
- Map enumVar = new HashMap<>();
- enumVar.put("name", toEnumVarName((String) value.get("identifier"), dataType));
- enumVar.put("value", toEnumValue(value.get("numericValue").toString(), dataType));
- enumVar.put("isString", isDataTypeString(dataType));
- if (value.containsKey("description")) {
- enumVar.put("description", value.get("description").toString());
- }
- enumVars.add(enumVar);
- }
- } else {
- super.updateEnumVarsWithExtensions(enumVars, vendorExtensions, dataType);
- }
- }
-
- @Override
- public String toEnumVarName(String value, String datatype) {
- if (value.length() == 0) {
- return "empty";
- }
- if (("number".equalsIgnoreCase(datatype) ||
- "double".equalsIgnoreCase(datatype) ||
- "int".equalsIgnoreCase(datatype)) &&
- value.matches("^-?\\d.*")) {
- // Only rename numeric values when the datatype is numeric
- // AND the name is not changed by enum extensions (matches a numeric value).
- boolean isNegative = value.startsWith("-");
- return toVarName("number" + (isNegative ? "_negative" : "") + value);
- }
- return toVarName(value);
- }
-
- @Override
- public String toEnumValue(String value, String datatype) {
- if ("number".equalsIgnoreCase(datatype) ||
- "int".equalsIgnoreCase(datatype)) {
- return value;
- } else {
- return "'" + escapeText(value) + "'";
- }
- }
-
- @Override
- public String toOperationId(String operationId) {
- operationId = super.toOperationId(operationId);
-
- operationId = camelize(sanitizeName(operationId), true);
-
- // method name cannot use reserved keyword, e.g. return
- if (isReservedWord(operationId)) {
- String newOperationId = camelize("call_" + operationId, true);
- LOGGER.warn(operationId + " (reserved word) cannot be used as method name. Renamed to " + newOperationId);
- return newOperationId;
- }
-
- // operationId starts with a number
- if (operationId.matches("^\\d.*")) {
- LOGGER.warn(operationId + " (starting with a number) cannot be used as method name. Renamed to " + camelize("call_" + operationId), true);
- operationId = camelize("call_" + operationId, true);
- }
-
- return operationId;
- }
-
- public void setPubLibrary(String pubLibrary) {
- this.pubLibrary = pubLibrary;
- }
-
- public void setPubName(String pubName) {
- this.pubName = pubName;
- }
-
- public void setPubVersion(String pubVersion) {
- this.pubVersion = pubVersion;
- }
-
- public void setPubDescription(String pubDescription) {
- this.pubDescription = pubDescription;
- }
-
- public void setPubAuthor(String pubAuthor) {
- this.pubAuthor = pubAuthor;
- }
-
- public void setPubAuthorEmail(String pubAuthorEmail) {
- this.pubAuthorEmail = pubAuthorEmail;
- }
-
- public void setPubHomepage(String pubHomepage) {
- this.pubHomepage = pubHomepage;
- }
-
- public void setUseEnumExtension(boolean useEnumExtension) {
- this.useEnumExtension = useEnumExtension;
- }
-
- public void setSourceFolder(String sourceFolder) {
- this.sourceFolder = sourceFolder;
- }
-
- @Override
- public String escapeQuotationMark(String input) {
- // remove " to avoid code injection
- return input.replace("\"", "");
- }
-
- @Override
- public String escapeUnsafeCharacters(String input) {
- return input.replace("*/", "*_/").replace("/*", "/_*");
- }
-
- @Override
- public void postProcessFile(File file, String fileType) {
- if (file == null) {
- return;
- }
-
- String dartPostProcessFile = System.getenv("DART_POST_PROCESS_FILE");
- if (StringUtils.isEmpty(dartPostProcessFile)) {
- return; // skip if DART_POST_PROCESS_FILE env variable is not defined
- }
-
- // process all files with dart extension
- if ("dart".equals(FilenameUtils.getExtension(file.toString()))) {
- // currently only support "dartfmt -w yourcode.dart"
- String command = dartPostProcessFile + " " + file.toString();
- try {
- Process p = Runtime.getRuntime().exec(command);
- int exitValue = p.waitFor();
- if (exitValue != 0) {
- LOGGER.error("Error running the command ({}). Exit code: {}", command, exitValue);
- } else {
- LOGGER.info("Successfully executed: {}", command);
- }
- } catch (Exception e) {
- LOGGER.error("Error running the command ({}). Exception: {}", command, e.getMessage());
- }
}
}
}
diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/DartDioClientCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/DartDioClientCodegen.java
index 66be8bc418..54d94d7f1c 100644
--- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/DartDioClientCodegen.java
+++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/DartDioClientCodegen.java
@@ -32,15 +32,16 @@ import java.util.*;
import static org.openapitools.codegen.utils.StringUtils.underscore;
-public class DartDioClientCodegen extends DartClientCodegen {
- private static final Logger LOGGER = LoggerFactory.getLogger(DartDioClientCodegen.class);
+public class DartDioClientCodegen extends AbstractDartCodegen {
+
+ private final Logger LOGGER = LoggerFactory.getLogger(DartDioClientCodegen.class);
public static final String NULLABLE_FIELDS = "nullableFields";
public static final String DATE_LIBRARY = "dateLibrary";
private static final String CLIENT_NAME = "clientName";
- private boolean nullableFields = true;
+ private boolean nullableFields = false;
private String dateLibrary = "core";
public DartDioClientCodegen() {
@@ -49,7 +50,7 @@ public class DartDioClientCodegen extends DartClientCodegen {
embeddedTemplateDir = "dart-dio";
this.setTemplateDir(embeddedTemplateDir);
- cliOptions.add(new CliOption(NULLABLE_FIELDS, "Is the null fields should be in the JSON payload"));
+ cliOptions.add(new CliOption(NULLABLE_FIELDS, "Make all fields nullable in the JSON payload"));
CliOption dateLibrary = new CliOption(DATE_LIBRARY, "Option. Date library to use").defaultValue(this.getDateLibrary());
Map dateOptions = new HashMap<>();
dateOptions.put("core", "Dart core library (DateTime)");
@@ -149,7 +150,7 @@ public class DartDioClientCodegen extends DartClientCodegen {
@Override
public void processOpts() {
- defaultProcessOpts();
+ super.processOpts();
if (StringUtils.isEmpty(System.getenv("DART_POST_PROCESS_FILE"))) {
LOGGER.info("Environment variable DART_POST_PROCESS_FILE not defined so the Dart code may not be properly formatted. To define it, try `export DART_POST_PROCESS_FILE=\"/usr/local/bin/dartfmt -w\"` (Linux/Mac)");
@@ -163,49 +164,10 @@ public class DartDioClientCodegen extends DartClientCodegen {
additionalProperties.put(NULLABLE_FIELDS, nullableFields);
}
- if (additionalProperties.containsKey(PUB_LIBRARY)) {
- this.setPubLibrary((String) additionalProperties.get(PUB_LIBRARY));
- } else {
- //not set, use to be passed to template
- additionalProperties.put(PUB_LIBRARY, pubLibrary);
- }
-
- if (additionalProperties.containsKey(PUB_NAME)) {
- this.setPubName((String) additionalProperties.get(PUB_NAME));
- } else {
- //not set, use to be passed to template
- additionalProperties.put(PUB_NAME, pubName);
- }
-
if (!additionalProperties.containsKey(CLIENT_NAME)) {
additionalProperties.put(CLIENT_NAME, org.openapitools.codegen.utils.StringUtils.camelize(pubName));
}
- if (additionalProperties.containsKey(PUB_VERSION)) {
- this.setPubVersion((String) additionalProperties.get(PUB_VERSION));
- } else {
- //not set, use to be passed to template
- additionalProperties.put(PUB_VERSION, pubVersion);
- }
-
- if (additionalProperties.containsKey(PUB_DESCRIPTION)) {
- this.setPubDescription((String) additionalProperties.get(PUB_DESCRIPTION));
- } else {
- //not set, use to be passed to template
- additionalProperties.put(PUB_DESCRIPTION, pubDescription);
- }
-
- if (additionalProperties.containsKey(USE_ENUM_EXTENSION)) {
- this.setUseEnumExtension(convertPropertyToBooleanAndWriteBack(USE_ENUM_EXTENSION));
- } else {
- // Not set, use to be passed to template.
- additionalProperties.put(USE_ENUM_EXTENSION, useEnumExtension);
- }
-
- if (additionalProperties.containsKey(CodegenConstants.SOURCE_FOLDER)) {
- this.setSourceFolder((String) additionalProperties.get(CodegenConstants.SOURCE_FOLDER));
- }
-
if (additionalProperties.containsKey(DATE_LIBRARY)) {
this.setDateLibrary(additionalProperties.get(DATE_LIBRARY).toString());
}
@@ -284,6 +246,34 @@ public class DartDioClientCodegen extends DartClientCodegen {
// enums are generated with built_value and make use of BuiltSet
model.imports.add("BuiltSet");
}
+
+ property.getVendorExtensions().put("x-built-value-serializer-type", createBuiltValueSerializerType(property));
+ }
+
+ private String createBuiltValueSerializerType(CodegenProperty property) {
+ final StringBuilder sb = new StringBuilder("const FullType(");
+ if (property.isContainer) {
+ appendCollection(sb, property);
+ } else {
+ sb.append(property.datatypeWithEnum);
+ }
+ sb.append(")");
+ return sb.toString();
+ }
+
+ private void appendCollection(StringBuilder sb, CodegenProperty property) {
+ sb.append(property.baseType);
+ sb.append(", [FullType(");
+ if (property.isMap) {
+ // a map always has string keys
+ sb.append("String), FullType(");
+ }
+ if (property.items.isContainer) {
+ appendCollection(sb, property.items);
+ } else {
+ sb.append(property.items.datatypeWithEnum);
+ }
+ sb.append(")]");
}
@Override
diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/DartJaguarClientCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/DartJaguarClientCodegen.java
index d932c346a4..7bcc374d36 100644
--- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/DartJaguarClientCodegen.java
+++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/DartJaguarClientCodegen.java
@@ -32,8 +32,9 @@ import java.util.*;
import static org.openapitools.codegen.utils.StringUtils.underscore;
-public class DartJaguarClientCodegen extends DartClientCodegen {
- private static final Logger LOGGER = LoggerFactory.getLogger(DartJaguarClientCodegen.class);
+public class DartJaguarClientCodegen extends AbstractDartCodegen {
+
+ private final Logger LOGGER = LoggerFactory.getLogger(DartJaguarClientCodegen.class);
private static final String NULLABLE_FIELDS = "nullableFields";
private static final String SERIALIZATION_FORMAT = "serialization";
@@ -41,26 +42,23 @@ public class DartJaguarClientCodegen extends DartClientCodegen {
private static final String IS_FORMAT_PROTO = "protoFormat";
private static final String CLIENT_NAME = "clientName";
- private static Set modelToIgnore = new HashSet<>();
- private HashMap protoTypeMapping = new HashMap<>();
+ private final Set modelToIgnore = new HashSet<>();
+ private final HashMap protoTypeMapping = new HashMap<>();
+
+ private static final String SERIALIZATION_JSON = "json";
+ private static final String SERIALIZATION_PROTO = "proto";
+
+ private boolean nullableFields = true;
+
+ public DartJaguarClientCodegen() {
+ super();
- static {
modelToIgnore.add("datetime");
modelToIgnore.add("map");
modelToIgnore.add("object");
modelToIgnore.add("list");
modelToIgnore.add("file");
modelToIgnore.add("list");
- }
-
- private static final String SERIALIZATION_JSON = "json";
- private static final String SERIALIZATION_PROTO = "proto";
-
- private boolean nullableFields = true;
- private String serialization = SERIALIZATION_JSON;
-
- public DartJaguarClientCodegen() {
- super();
modifyFeatureSet(features -> features
.includeDocumentationFeatures(DocumentationFeature.Readme)
@@ -150,7 +148,8 @@ public class DartJaguarClientCodegen extends DartClientCodegen {
@Override
public void processOpts() {
- defaultProcessOpts();
+ super.processOpts();
+
if (additionalProperties.containsKey(NULLABLE_FIELDS)) {
nullableFields = convertPropertyToBooleanAndWriteBack(NULLABLE_FIELDS);
} else {
@@ -159,7 +158,7 @@ public class DartJaguarClientCodegen extends DartClientCodegen {
}
if (additionalProperties.containsKey(SERIALIZATION_FORMAT)) {
- serialization = ((String) additionalProperties.get(SERIALIZATION_FORMAT));
+ String serialization = ((String) additionalProperties.get(SERIALIZATION_FORMAT));
boolean isProto = serialization.equalsIgnoreCase(SERIALIZATION_PROTO);
additionalProperties.put(IS_FORMAT_JSON, serialization.equalsIgnoreCase(SERIALIZATION_JSON));
additionalProperties.put(IS_FORMAT_PROTO, isProto);
@@ -172,35 +171,8 @@ public class DartJaguarClientCodegen extends DartClientCodegen {
additionalProperties.put(IS_FORMAT_PROTO, false);
}
- if (additionalProperties.containsKey(PUB_LIBRARY)) {
- this.setPubLibrary((String) additionalProperties.get(PUB_LIBRARY));
- } else {
- //not set, use to be passed to template
- additionalProperties.put(PUB_LIBRARY, pubLibrary);
- }
-
- if (additionalProperties.containsKey(PUB_NAME)) {
- this.setPubName((String) additionalProperties.get(PUB_NAME));
- } else {
- //not set, use to be passed to template
- additionalProperties.put(PUB_NAME, pubName);
- }
additionalProperties.put(CLIENT_NAME, org.openapitools.codegen.utils.StringUtils.camelize(pubName));
- if (additionalProperties.containsKey(PUB_VERSION)) {
- this.setPubVersion((String) additionalProperties.get(PUB_VERSION));
- } else {
- //not set, use to be passed to template
- additionalProperties.put(PUB_VERSION, pubVersion);
- }
-
- if (additionalProperties.containsKey(PUB_DESCRIPTION)) {
- this.setPubDescription((String) additionalProperties.get(PUB_DESCRIPTION));
- } else {
- //not set, use to be passed to template
- additionalProperties.put(PUB_DESCRIPTION, pubDescription);
- }
-
if (additionalProperties.containsKey(USE_ENUM_EXTENSION)) {
this.setUseEnumExtension(convertPropertyToBooleanAndWriteBack(USE_ENUM_EXTENSION));
} else {
@@ -208,10 +180,6 @@ public class DartJaguarClientCodegen extends DartClientCodegen {
additionalProperties.put(USE_ENUM_EXTENSION, useEnumExtension);
}
- if (additionalProperties.containsKey(CodegenConstants.SOURCE_FOLDER)) {
- this.setSourceFolder((String) additionalProperties.get(CodegenConstants.SOURCE_FOLDER));
- }
-
// make api and model doc path available in mustache template
additionalProperties.put("apiDocPath", apiDocPath);
additionalProperties.put("modelDocPath", modelDocPath);
diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/EiffelClientCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/EiffelClientCodegen.java
index 5784d25590..9c5b6f0d5a 100644
--- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/EiffelClientCodegen.java
+++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/EiffelClientCodegen.java
@@ -31,7 +31,7 @@ import java.util.Locale;
import java.util.UUID;
public class EiffelClientCodegen extends AbstractEiffelCodegen {
- private static final Logger LOGGER = LoggerFactory.getLogger(EiffelClientCodegen.class);
+ private final Logger LOGGER = LoggerFactory.getLogger(EiffelClientCodegen.class);
protected String libraryTarget = "openapi_eiffel_client";
protected String packageName = "Eiffel";
diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/ElixirClientCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/ElixirClientCodegen.java
index 5d1da61422..51ce18efe4 100644
--- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/ElixirClientCodegen.java
+++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/ElixirClientCodegen.java
@@ -42,7 +42,7 @@ import static org.openapitools.codegen.utils.StringUtils.camelize;
import static org.openapitools.codegen.utils.StringUtils.underscore;
public class ElixirClientCodegen extends DefaultCodegen implements CodegenConfig {
- private static final Logger LOGGER = LoggerFactory.getLogger(ElixirClientCodegen.class);
+ private final Logger LOGGER = LoggerFactory.getLogger(ElixirClientCodegen.class);
protected String apiVersion = "1.0.0";
protected String moduleName;
diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/ElmClientCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/ElmClientCodegen.java
index 191b26445d..0ce23749fd 100644
--- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/ElmClientCodegen.java
+++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/ElmClientCodegen.java
@@ -42,7 +42,7 @@ import java.util.stream.Stream;
import static org.openapitools.codegen.utils.StringUtils.camelize;
public class ElmClientCodegen extends DefaultCodegen implements CodegenConfig {
- private static final Logger LOGGER = LoggerFactory.getLogger(ElmClientCodegen.class);
+ private final Logger LOGGER = LoggerFactory.getLogger(ElmClientCodegen.class);
protected String packageName = "openapi";
protected String packageVersion = "1.0.0";
diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/ErlangClientCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/ErlangClientCodegen.java
index cc88d96344..00013976a9 100644
--- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/ErlangClientCodegen.java
+++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/ErlangClientCodegen.java
@@ -37,7 +37,7 @@ import static org.openapitools.codegen.utils.StringUtils.camelize;
import static org.openapitools.codegen.utils.StringUtils.underscore;
public class ErlangClientCodegen extends DefaultCodegen implements CodegenConfig {
- private static final Logger LOGGER = LoggerFactory.getLogger(ErlangClientCodegen.class);
+ private final Logger LOGGER = LoggerFactory.getLogger(ErlangClientCodegen.class);
protected String packageName = "openapi";
protected String packageVersion = "1.0.0";
@@ -298,7 +298,7 @@ public class ErlangClientCodegen extends DefaultCodegen implements CodegenConfig
@Override
public String toOperationId(String operationId) {
- // method name cannot use reserved keyword, e.g. return
+ // method name cannot use reserved keyword, e.g. if
if (isReservedWord(operationId)) {
LOGGER.warn(operationId + " (reserved word) cannot be used as method name. Renamed to " + underscore(sanitizeName("call_" + operationId)).replaceAll("\\.", "_"));
operationId = "call_" + operationId;
@@ -352,24 +352,33 @@ public class ErlangClientCodegen extends DefaultCodegen implements CodegenConfig
this.packageVersion = packageVersion;
}
+ /**
+ * Returns the number of required parameters plus 1.
+ *
+ * @param os List of Codegen Parameters
+ * @return the string representation of the number of required paramters plus 1
+ */
String length(Object os) {
int l = 1;
for (CodegenParameter o : ((ExtendedCodegenOperation) os).allParams) {
- CodegenParameter q = (CodegenParameter) o;
- if (q.required)
+ if (o.required)
l++;
}
-
return Integer.toString(l);
}
+ /**
+ * Returns the number of required parameters or body parameters.
+ *
+ * @param os List of Codegen Parameters
+ * @return the number of required paramters or body parameters
+ */
int lengthRequired(List allParams) {
int l = 0;
for (CodegenParameter o : allParams) {
if (o.required || o.isBodyParam)
l++;
}
-
return l;
}
diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/ErlangProperCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/ErlangProperCodegen.java
index 5959d6e79a..9e9c1186a2 100644
--- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/ErlangProperCodegen.java
+++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/ErlangProperCodegen.java
@@ -38,7 +38,7 @@ import static org.openapitools.codegen.utils.StringUtils.camelize;
import static org.openapitools.codegen.utils.StringUtils.underscore;
public class ErlangProperCodegen extends DefaultCodegen implements CodegenConfig {
- private static final Logger LOGGER = LoggerFactory.getLogger(ErlangProperCodegen.class);
+ private final Logger LOGGER = LoggerFactory.getLogger(ErlangProperCodegen.class);
protected String packageName = "openapi";
protected String packageVersion = "1.0.0";
diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/ErlangServerCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/ErlangServerCodegen.java
index 99e518ffdf..117a8aed93 100644
--- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/ErlangServerCodegen.java
+++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/ErlangServerCodegen.java
@@ -33,7 +33,7 @@ import static org.openapitools.codegen.utils.StringUtils.underscore;
public class ErlangServerCodegen extends DefaultCodegen implements CodegenConfig {
- private static final Logger LOGGER = LoggerFactory.getLogger(ErlangServerCodegen.class);
+ private final Logger LOGGER = LoggerFactory.getLogger(ErlangServerCodegen.class);
protected String apiVersion = "1.0.0";
protected String apiPath = "src";
diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/FlashClientCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/FlashClientCodegen.java
index 4f41905372..89a5a2ae69 100644
--- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/FlashClientCodegen.java
+++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/FlashClientCodegen.java
@@ -37,7 +37,7 @@ import static org.openapitools.codegen.utils.StringUtils.camelize;
import static org.openapitools.codegen.utils.StringUtils.underscore;
public class FlashClientCodegen extends DefaultCodegen implements CodegenConfig {
- private static final Logger LOGGER = LoggerFactory.getLogger(FlashClientCodegen.class);
+ private final Logger LOGGER = LoggerFactory.getLogger(FlashClientCodegen.class);
protected String packageName = "org.openapitools";
protected String packageVersion;
diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/FsharpFunctionsServerCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/FsharpFunctionsServerCodegen.java
index 4d732dbea8..832282030c 100644
--- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/FsharpFunctionsServerCodegen.java
+++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/FsharpFunctionsServerCodegen.java
@@ -36,7 +36,7 @@ import org.slf4j.LoggerFactory;
public class FsharpFunctionsServerCodegen extends AbstractFSharpCodegen {
public static final String PROJECT_NAME = "projectName";
- static final Logger LOGGER = LoggerFactory.getLogger(FsharpFunctionsServerCodegen.class);
+ final Logger LOGGER = LoggerFactory.getLogger(FsharpFunctionsServerCodegen.class);
public CodegenType getTag() {
return CodegenType.SERVER;
diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/GoClientCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/GoClientCodegen.java
index ca01e4f293..ed5418ab4a 100644
--- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/GoClientCodegen.java
+++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/GoClientCodegen.java
@@ -17,6 +17,7 @@
package org.openapitools.codegen.languages;
+import com.google.common.collect.Iterables;
import io.swagger.v3.oas.models.media.Schema;
import io.swagger.v3.oas.models.security.SecurityScheme;
import org.apache.commons.lang3.StringUtils;
@@ -36,7 +37,7 @@ import static org.openapitools.codegen.utils.StringUtils.camelize;
public class GoClientCodegen extends AbstractGoCodegen {
- private static final Logger LOGGER = LoggerFactory.getLogger(GoClientCodegen.class);
+ private final Logger LOGGER = LoggerFactory.getLogger(GoClientCodegen.class);
protected String packageVersion = "1.0.0";
protected String apiDocPath = "docs/";
protected String modelDocPath = "docs/";
@@ -387,7 +388,7 @@ public class GoClientCodegen extends AbstractGoCodegen {
continue;
}
- for (CodegenProperty param : model.vars) {
+ for (CodegenProperty param : Iterables.concat(model.vars, model.allVars, model.requiredVars, model.optionalVars)) {
param.vendorExtensions.put("x-go-base-type", param.dataType);
if (!param.isNullable || param.isMap || param.isArray ||
param.isFreeFormObject || param.isAnyType) {
diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/GoDeprecatedClientCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/GoDeprecatedClientCodegen.java
index bfedaae35c..0436961b0e 100644
--- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/GoDeprecatedClientCodegen.java
+++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/GoDeprecatedClientCodegen.java
@@ -32,7 +32,7 @@ import java.util.EnumSet;
public class GoDeprecatedClientCodegen extends AbstractGoCodegen {
- private static final Logger LOGGER = LoggerFactory.getLogger(GoDeprecatedClientCodegen.class);
+ private final Logger LOGGER = LoggerFactory.getLogger(GoDeprecatedClientCodegen.class);
protected String packageVersion = "1.0.0";
protected String apiDocPath = "docs/";
diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/GoGinServerCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/GoGinServerCodegen.java
index 404d1c06a0..12fba7abe3 100644
--- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/GoGinServerCodegen.java
+++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/GoGinServerCodegen.java
@@ -33,7 +33,7 @@ import java.util.Map;
public class GoGinServerCodegen extends AbstractGoCodegen {
- private static final Logger LOGGER = LoggerFactory.getLogger(GoGinServerCodegen.class);
+ private final Logger LOGGER = LoggerFactory.getLogger(GoGinServerCodegen.class);
protected String apiVersion = "1.0.0";
protected int serverPort = 8080;
@@ -116,6 +116,8 @@ public class GoGinServerCodegen extends AbstractGoCodegen {
optServerPort.setType("int");
optServerPort.defaultValue(Integer.toString(serverPort));
cliOptions.add(optServerPort);
+
+ cliOptions.add(CliOption.newBoolean(CodegenConstants.ENUM_CLASS_PREFIX, CodegenConstants.ENUM_CLASS_PREFIX_DESC));
}
@Override
@@ -165,6 +167,13 @@ public class GoGinServerCodegen extends AbstractGoCodegen {
additionalProperties.put("apiPath", apiPath);
}
+ if (additionalProperties.containsKey(CodegenConstants.ENUM_CLASS_PREFIX)) {
+ setEnumClassPrefix(Boolean.parseBoolean(additionalProperties.get(CodegenConstants.ENUM_CLASS_PREFIX).toString()));
+ if (enumClassPrefix) {
+ additionalProperties.put(CodegenConstants.ENUM_CLASS_PREFIX, true);
+ }
+ }
+
modelPackage = packageName;
apiPackage = packageName;
diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/GoServerCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/GoServerCodegen.java
index 95dc5e4082..2e08cb6f39 100644
--- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/GoServerCodegen.java
+++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/GoServerCodegen.java
@@ -30,7 +30,7 @@ import java.util.Map;
public class GoServerCodegen extends AbstractGoCodegen {
- private static final Logger LOGGER = LoggerFactory.getLogger(GoServerCodegen.class);
+ private final Logger LOGGER = LoggerFactory.getLogger(GoServerCodegen.class);
protected String packageVersion = "1.0.0";
protected int serverPort = 8080;
diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/GraphQLNodeJSExpressServerCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/GraphQLNodeJSExpressServerCodegen.java
index 736d98d71d..5edc4ae74c 100644
--- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/GraphQLNodeJSExpressServerCodegen.java
+++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/GraphQLNodeJSExpressServerCodegen.java
@@ -30,7 +30,7 @@ import java.util.EnumSet;
public class GraphQLNodeJSExpressServerCodegen extends AbstractGraphQLCodegen implements CodegenConfig {
- private static final Logger LOGGER = LoggerFactory.getLogger(GraphQLNodeJSExpressServerCodegen.class);
+ private final Logger LOGGER = LoggerFactory.getLogger(GraphQLNodeJSExpressServerCodegen.class);
@Override
public CodegenType getTag() {
diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/GraphQLSchemaCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/GraphQLSchemaCodegen.java
index 112bb53c75..9835ee9d0e 100644
--- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/GraphQLSchemaCodegen.java
+++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/GraphQLSchemaCodegen.java
@@ -28,7 +28,7 @@ import java.util.EnumSet;
public class GraphQLSchemaCodegen extends AbstractGraphQLCodegen implements CodegenConfig {
- private static final Logger LOGGER = LoggerFactory.getLogger(GraphQLSchemaCodegen.class);
+ private final Logger LOGGER = LoggerFactory.getLogger(GraphQLSchemaCodegen.class);
@Override
public CodegenType getTag() {
diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/HaskellHttpClientCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/HaskellHttpClientCodegen.java
index 059d85cf2c..0e8eea4c66 100644
--- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/HaskellHttpClientCodegen.java
+++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/HaskellHttpClientCodegen.java
@@ -42,7 +42,7 @@ import static org.openapitools.codegen.utils.StringUtils.camelize;
import static org.openapitools.codegen.utils.StringUtils.underscore;
public class HaskellHttpClientCodegen extends DefaultCodegen implements CodegenConfig {
- private static final Logger LOGGER = LoggerFactory.getLogger(HaskellHttpClientCodegen.class);
+ private final Logger LOGGER = LoggerFactory.getLogger(HaskellHttpClientCodegen.class);
// source folder where to write the files
protected String sourceFolder = "lib";
diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/HaskellServantCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/HaskellServantCodegen.java
index 6181b572f2..c7220c1247 100644
--- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/HaskellServantCodegen.java
+++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/HaskellServantCodegen.java
@@ -38,7 +38,7 @@ import static org.openapitools.codegen.utils.OnceLogger.once;
import static org.openapitools.codegen.utils.StringUtils.camelize;
public class HaskellServantCodegen extends DefaultCodegen implements CodegenConfig {
- private static final Logger LOGGER = LoggerFactory.getLogger(HaskellServantCodegen.class);
+ private final Logger LOGGER = LoggerFactory.getLogger(HaskellServantCodegen.class);
// source folder where to write the files
protected String sourceFolder = "src";
diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/JavaCXFClientCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/JavaCXFClientCodegen.java
index 9f75430551..0c6745e646 100644
--- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/JavaCXFClientCodegen.java
+++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/JavaCXFClientCodegen.java
@@ -33,7 +33,7 @@ import java.util.Map;
public class JavaCXFClientCodegen extends AbstractJavaCodegen
implements BeanValidationFeatures, UseGenericResponseFeatures, GzipTestFeatures, LoggingTestFeatures {
- private static final Logger LOGGER = LoggerFactory.getLogger(JavaCXFClientCodegen.class);
+ private final Logger LOGGER = LoggerFactory.getLogger(JavaCXFClientCodegen.class);
/**
* Name of the sub-directory in "src/main/resource" where to find the
diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/JavaCXFExtServerCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/JavaCXFExtServerCodegen.java
index 01b7293ab9..a02e91ad0f 100644
--- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/JavaCXFExtServerCodegen.java
+++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/JavaCXFExtServerCodegen.java
@@ -258,7 +258,7 @@ public class JavaCXFExtServerCodegen extends JavaCXFServerCodegen implements CXF
}
}
- private static final Logger LOGGER = LoggerFactory.getLogger(JavaCXFExtServerCodegen.class);
+ private final Logger LOGGER = LoggerFactory.getLogger(JavaCXFExtServerCodegen.class);
private static final String INDENT = " ";
@@ -306,7 +306,7 @@ public class JavaCXFExtServerCodegen extends JavaCXFServerCodegen implements CXF
MAX_DATE = maxDate;
}
- private Map REGEX_GENERATORS = new HashMap<>();
+ private final Map REGEX_GENERATORS = new HashMap<>();
protected boolean generateOperationBody = false;
@@ -708,8 +708,8 @@ public class JavaCXFExtServerCodegen extends JavaCXFServerCodegen implements CXF
// NOTE: use double to hold float values, to avoid numeric overflow.
double min = var == null || var.minimum == null ? -Float.MAX_VALUE : Float.parseFloat(var.minimum);
double max = var == null || var.maximum == null ? Float.MAX_VALUE : Float.parseFloat(var.maximum);
- double exclusiveMin = (double) (var != null && var.exclusiveMinimum ? 1 : 0);
- double inclusiveMax = (double) (var == null || !var.exclusiveMaximum ? 1 : 0);
+ double exclusiveMin = var != null && var.exclusiveMinimum ? 1 : 0;
+ double inclusiveMax = var == null || !var.exclusiveMaximum ? 1 : 0;
float randomFloat = (float) (min + exclusiveMin
+ ((max + inclusiveMax - min - exclusiveMin) * Math.random()));
diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/JavaCXFServerCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/JavaCXFServerCodegen.java
index 2ee53cdc76..031fb7272f 100644
--- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/JavaCXFServerCodegen.java
+++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/JavaCXFServerCodegen.java
@@ -32,7 +32,7 @@ import java.util.Map;
public class JavaCXFServerCodegen extends AbstractJavaJAXRSServerCodegen
implements CXFServerFeatures, GzipTestFeatures, LoggingTestFeatures, UseGenericResponseFeatures {
- private static final Logger LOGGER = LoggerFactory.getLogger(JavaCXFServerCodegen.class);
+ private final Logger LOGGER = LoggerFactory.getLogger(JavaCXFServerCodegen.class);
protected boolean addConsumesProducesJson = true;
diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/JavaClientCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/JavaClientCodegen.java
index 687f773f7a..b01b999c3b 100644
--- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/JavaClientCodegen.java
+++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/JavaClientCodegen.java
@@ -47,7 +47,7 @@ public class JavaClientCodegen extends AbstractJavaCodegen
static final String MEDIA_TYPE = "mediaType";
- private static final Logger LOGGER = LoggerFactory.getLogger(JavaClientCodegen.class);
+ private final Logger LOGGER = LoggerFactory.getLogger(JavaClientCodegen.class);
public static final String USE_RX_JAVA = "useRxJava";
public static final String USE_RX_JAVA2 = "useRxJava2";
@@ -87,6 +87,7 @@ public class JavaClientCodegen extends AbstractJavaCodegen
public static final String SERIALIZATION_LIBRARY_GSON = "gson";
public static final String SERIALIZATION_LIBRARY_JACKSON = "jackson";
+ public static final String SERIALIZATION_LIBRARY_JSONB = "jsonb";
protected String gradleWrapperPackage = "gradle.wrapper";
protected boolean useRxJava = false;
@@ -179,6 +180,7 @@ public class JavaClientCodegen extends AbstractJavaCodegen
Map serializationOptions = new HashMap<>();
serializationOptions.put(SERIALIZATION_LIBRARY_GSON, "Use Gson as serialization library");
serializationOptions.put(SERIALIZATION_LIBRARY_JACKSON, "Use Jackson as serialization library");
+ serializationOptions.put(SERIALIZATION_LIBRARY_JSONB, "Use JSON-B as serialization library");
serializationLibrary.setEnum(serializationOptions);
cliOptions.add(serializationLibrary);
@@ -554,21 +556,33 @@ public class JavaClientCodegen extends AbstractJavaCodegen
LOGGER.info("No serializationLibrary configured, using '" + SERIALIZATION_LIBRARY_GSON + "' as fallback");
setSerializationLibrary(SERIALIZATION_LIBRARY_GSON);
}
- if (SERIALIZATION_LIBRARY_JACKSON.equals(getSerializationLibrary())) {
- additionalProperties.put(SERIALIZATION_LIBRARY_JACKSON, "true");
- additionalProperties.remove(SERIALIZATION_LIBRARY_GSON);
- supportingFiles.add(new SupportingFile("RFC3339DateFormat.mustache", invokerFolder, "RFC3339DateFormat.java"));
- if (!NATIVE.equals(getLibrary())) {
- if ("threetenbp".equals(dateLibrary) && !usePlayWS) {
- supportingFiles.add(new SupportingFile("CustomInstantDeserializer.mustache", invokerFolder, "CustomInstantDeserializer.java"));
+ switch (getSerializationLibrary()) {
+ case SERIALIZATION_LIBRARY_JACKSON:
+ additionalProperties.put(SERIALIZATION_LIBRARY_JACKSON, "true");
+ additionalProperties.remove(SERIALIZATION_LIBRARY_GSON);
+ additionalProperties.remove(SERIALIZATION_LIBRARY_JSONB);
+ supportingFiles.add(new SupportingFile("RFC3339DateFormat.mustache", invokerFolder, "RFC3339DateFormat.java"));
+ if (!NATIVE.equals(getLibrary())) {
+ if ("threetenbp".equals(dateLibrary) && !usePlayWS) {
+ supportingFiles.add(new SupportingFile("CustomInstantDeserializer.mustache", invokerFolder, "CustomInstantDeserializer.java"));
+ }
}
- }
- } else if (SERIALIZATION_LIBRARY_GSON.equals(getSerializationLibrary())) {
- additionalProperties.put(SERIALIZATION_LIBRARY_GSON, "true");
- additionalProperties.remove(SERIALIZATION_LIBRARY_JACKSON);
- } else {
- additionalProperties.remove(SERIALIZATION_LIBRARY_JACKSON);
- additionalProperties.remove(SERIALIZATION_LIBRARY_GSON);
+ break;
+ case SERIALIZATION_LIBRARY_GSON:
+ additionalProperties.put(SERIALIZATION_LIBRARY_GSON, "true");
+ additionalProperties.remove(SERIALIZATION_LIBRARY_JACKSON);
+ additionalProperties.remove(SERIALIZATION_LIBRARY_JSONB);
+ break;
+ case SERIALIZATION_LIBRARY_JSONB:
+ additionalProperties.put(SERIALIZATION_LIBRARY_JSONB, "true");
+ additionalProperties.remove(SERIALIZATION_LIBRARY_JACKSON);
+ additionalProperties.remove(SERIALIZATION_LIBRARY_GSON);
+ break;
+ default:
+ additionalProperties.remove(SERIALIZATION_LIBRARY_JACKSON);
+ additionalProperties.remove(SERIALIZATION_LIBRARY_GSON);
+ additionalProperties.remove(SERIALIZATION_LIBRARY_JSONB);
+ break;
}
// authentication related files
@@ -974,6 +988,8 @@ public class JavaClientCodegen extends AbstractJavaCodegen
this.serializationLibrary = SERIALIZATION_LIBRARY_JACKSON;
} else if (SERIALIZATION_LIBRARY_GSON.equalsIgnoreCase(serializationLibrary)) {
this.serializationLibrary = SERIALIZATION_LIBRARY_GSON;
+ } else if (SERIALIZATION_LIBRARY_JSONB.equalsIgnoreCase(serializationLibrary)) {
+ this.serializationLibrary = SERIALIZATION_LIBRARY_JSONB;
} else {
throw new IllegalArgumentException("Unexpected serializationLibrary value: " + serializationLibrary);
}
diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/JavaInflectorServerCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/JavaInflectorServerCodegen.java
index 3311b0d856..297a45d353 100644
--- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/JavaInflectorServerCodegen.java
+++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/JavaInflectorServerCodegen.java
@@ -34,7 +34,7 @@ import static org.openapitools.codegen.utils.StringUtils.camelize;
public class JavaInflectorServerCodegen extends AbstractJavaCodegen {
- private static final Logger LOGGER = LoggerFactory.getLogger(JavaInflectorServerCodegen.class);
+ private final Logger LOGGER = LoggerFactory.getLogger(JavaInflectorServerCodegen.class);
protected String title = "OpenAPI Inflector";
protected String implFolder = "src/main/java";
diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/JavaPlayFrameworkCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/JavaPlayFrameworkCodegen.java
index c81f020190..c6deda5533 100644
--- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/JavaPlayFrameworkCodegen.java
+++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/JavaPlayFrameworkCodegen.java
@@ -35,7 +35,7 @@ import static org.openapitools.codegen.utils.OnceLogger.once;
import static org.openapitools.codegen.utils.StringUtils.camelize;
public class JavaPlayFrameworkCodegen extends AbstractJavaCodegen implements BeanValidationFeatures {
- private static final Logger LOGGER = LoggerFactory.getLogger(JavaPlayFrameworkCodegen.class);
+ private final Logger LOGGER = LoggerFactory.getLogger(JavaPlayFrameworkCodegen.class);
public static final String TITLE = "title";
public static final String CONFIG_PACKAGE = "configPackage";
public static final String BASE_PACKAGE = "basePackage";
diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/JavaUndertowServerCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/JavaUndertowServerCodegen.java
index 92e5d2e1be..06a20ad12a 100644
--- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/JavaUndertowServerCodegen.java
+++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/JavaUndertowServerCodegen.java
@@ -34,7 +34,7 @@ import static org.openapitools.codegen.utils.StringUtils.camelize;
public class JavaUndertowServerCodegen extends AbstractJavaCodegen {
- private static final Logger LOGGER = LoggerFactory.getLogger(JavaUndertowServerCodegen.class);
+ private final Logger LOGGER = LoggerFactory.getLogger(JavaUndertowServerCodegen.class);
protected String title = "OpenAPI Undertow Server";
protected String implFolder = "src/main/java";
diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/JavaVertXServerCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/JavaVertXServerCodegen.java
index d38f05ecfc..231be3622c 100644
--- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/JavaVertXServerCodegen.java
+++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/JavaVertXServerCodegen.java
@@ -42,7 +42,7 @@ import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class JavaVertXServerCodegen extends AbstractJavaCodegen {
- private static final Logger LOGGER = LoggerFactory.getLogger(JavaVertXServerCodegen.class);
+ private final Logger LOGGER = LoggerFactory.getLogger(JavaVertXServerCodegen.class);
protected String resourceFolder = "src/main/resources";
protected String rootPackage = "org.openapitools.server.api";
diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/JavascriptApolloClientCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/JavascriptApolloClientCodegen.java
index 3476192f4c..8d15f61d51 100644
--- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/JavascriptApolloClientCodegen.java
+++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/JavascriptApolloClientCodegen.java
@@ -39,7 +39,7 @@ import static org.openapitools.codegen.utils.StringUtils.*;
public class JavascriptApolloClientCodegen extends DefaultCodegen implements CodegenConfig {
@SuppressWarnings("hiding")
- private static final Logger LOGGER = LoggerFactory.getLogger(JavascriptApolloClientCodegen.class);
+ private final Logger LOGGER = LoggerFactory.getLogger(JavascriptApolloClientCodegen.class);
public static final String PROJECT_NAME = "projectName";
public static final String MODULE_NAME = "moduleName";
diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/JavascriptClientCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/JavascriptClientCodegen.java
index c3fa812bca..26071b4ca6 100644
--- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/JavascriptClientCodegen.java
+++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/JavascriptClientCodegen.java
@@ -38,7 +38,7 @@ import static org.openapitools.codegen.utils.StringUtils.*;
public class JavascriptClientCodegen extends DefaultCodegen implements CodegenConfig {
@SuppressWarnings("hiding")
- private static final Logger LOGGER = LoggerFactory.getLogger(JavascriptClientCodegen.class);
+ private final Logger LOGGER = LoggerFactory.getLogger(JavascriptClientCodegen.class);
public static final String PROJECT_NAME = "projectName";
public static final String MODULE_NAME = "moduleName";
diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/JavascriptClosureAngularClientCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/JavascriptClosureAngularClientCodegen.java
index 877db877e4..751d75e4f2 100644
--- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/JavascriptClosureAngularClientCodegen.java
+++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/JavascriptClosureAngularClientCodegen.java
@@ -32,7 +32,7 @@ import java.util.*;
import static org.openapitools.codegen.utils.StringUtils.camelize;
public class JavascriptClosureAngularClientCodegen extends DefaultCodegen implements CodegenConfig {
- private static final Logger LOGGER = LoggerFactory.getLogger(JavascriptClosureAngularClientCodegen.class);
+ private final Logger LOGGER = LoggerFactory.getLogger(JavascriptClosureAngularClientCodegen.class);
public static final String USE_ES6 = "useEs6";
diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/K6ClientCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/K6ClientCodegen.java
index edd71aeae5..86bfcfa652 100644
--- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/K6ClientCodegen.java
+++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/K6ClientCodegen.java
@@ -71,7 +71,7 @@ public class K6ClientCodegen extends DefaultCodegen implements CodegenConfig {
if (obj == null || getClass() != obj.getClass())
return false;
Parameter p = (Parameter) obj;
- return key.equals(p.key) && value.equals((String) p.value);
+ return key.equals(p.key) && value.equals(p.value);
}
}
@@ -165,7 +165,7 @@ public class K6ClientCodegen extends DefaultCodegen implements CodegenConfig {
}
}
- private static final Logger LOGGER = LoggerFactory.getLogger(JavascriptClientCodegen.class);
+ private final Logger LOGGER = LoggerFactory.getLogger(JavascriptClientCodegen.class);
public static final String PROJECT_NAME = "projectName";
public static final String MODULE_NAME = "moduleName";
diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/KotlinClientCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/KotlinClientCodegen.java
index 1ac723a984..d4ee8e555a 100644
--- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/KotlinClientCodegen.java
+++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/KotlinClientCodegen.java
@@ -40,7 +40,7 @@ import java.util.stream.Stream;
public class KotlinClientCodegen extends AbstractKotlinCodegen {
- private static final Logger LOGGER = LoggerFactory.getLogger(KotlinClientCodegen.class);
+ private final Logger LOGGER = LoggerFactory.getLogger(KotlinClientCodegen.class);
protected static final String JVM = "jvm";
protected static final String JVM_OKHTTP = "jvm-okhttp";
@@ -658,4 +658,16 @@ public class KotlinClientCodegen extends AbstractKotlinCodegen {
}
return false;
}
+
+ @Override
+ public void postProcess() {
+ System.out.println("################################################################################");
+ System.out.println("# Thanks for using OpenAPI Generator. #");
+ System.out.println("# Please consider donation to help us maintain this project \uD83D\uDE4F #");
+ System.out.println("# https://opencollective.com/openapi_generator/donate #");
+ System.out.println("# #");
+ System.out.println("# This generator's contributed by Jim Schubert (https://github.com/jimschubert)#");
+ System.out.println("# Please support his work directly via https://patreon.com/jimschubert \uD83D\uDE4F #");
+ System.out.println("################################################################################");
+ }
}
diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/KotlinServerCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/KotlinServerCodegen.java
index 39f32bb0fc..d4d9902da7 100644
--- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/KotlinServerCodegen.java
+++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/KotlinServerCodegen.java
@@ -36,7 +36,7 @@ import java.util.Map;
public class KotlinServerCodegen extends AbstractKotlinCodegen {
public static final String DEFAULT_LIBRARY = Constants.KTOR;
- private static final Logger LOGGER = LoggerFactory.getLogger(KotlinServerCodegen.class);
+ private final Logger LOGGER = LoggerFactory.getLogger(KotlinServerCodegen.class);
private Boolean autoHeadFeatureEnabled = true;
private Boolean conditionalHeadersFeatureEnabled = false;
private Boolean hstsFeatureEnabled = true;
@@ -248,4 +248,16 @@ public class KotlinServerCodegen extends AbstractKotlinCodegen {
public final static String COMPRESSION = "featureCompression";
public final static String COMPRESSION_DESC = "Adds ability to compress outgoing content using gzip, deflate or custom encoder and thus reduce size of the response.";
}
+
+ @Override
+ public void postProcess() {
+ System.out.println("################################################################################");
+ System.out.println("# Thanks for using OpenAPI Generator. #");
+ System.out.println("# Please consider donation to help us maintain this project \uD83D\uDE4F #");
+ System.out.println("# https://opencollective.com/openapi_generator/donate #");
+ System.out.println("# #");
+ System.out.println("# This generator's contributed by Jim Schubert (https://github.com/jimschubert)#");
+ System.out.println("# Please support his work directly via https://patreon.com/jimschubert \uD83D\uDE4F #");
+ System.out.println("################################################################################");
+ }
}
diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/KotlinVertxServerCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/KotlinVertxServerCodegen.java
index 7938f04b5f..7d50e57b7f 100644
--- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/KotlinVertxServerCodegen.java
+++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/KotlinVertxServerCodegen.java
@@ -37,7 +37,7 @@ public class KotlinVertxServerCodegen extends AbstractKotlinCodegen {
public static final String PROJECT_NAME = "projectName";
- static final Logger LOGGER = LoggerFactory.getLogger(KotlinVertxServerCodegen.class);
+ final Logger LOGGER = LoggerFactory.getLogger(KotlinVertxServerCodegen.class);
public CodegenType getTag() {
return CodegenType.SERVER;
diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/KtormSchemaCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/KtormSchemaCodegen.java
index a21fe433bb..3c013d9160 100644
--- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/KtormSchemaCodegen.java
+++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/KtormSchemaCodegen.java
@@ -1152,7 +1152,7 @@ public class KtormSchemaCodegen extends AbstractKotlinCodegen {
this.identifierNamingConvention = naming;
break;
default:
- LOGGER.warn("\"" + (String) naming + "\" is invalid \"identifierNamingConvention\" argument. Current \"" + (String) this.identifierNamingConvention + "\" used instead.");
+ LOGGER.warn("\"" + naming + "\" is invalid \"identifierNamingConvention\" argument. Current \"" + this.identifierNamingConvention + "\" used instead.");
}
}
diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/LuaClientCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/LuaClientCodegen.java
index e295bf6169..401496bc31 100644
--- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/LuaClientCodegen.java
+++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/LuaClientCodegen.java
@@ -35,7 +35,7 @@ import static org.openapitools.codegen.utils.StringUtils.camelize;
import static org.openapitools.codegen.utils.StringUtils.underscore;
public class LuaClientCodegen extends DefaultCodegen implements CodegenConfig {
- private static final Logger LOGGER = LoggerFactory.getLogger(LuaClientCodegen.class);
+ private final Logger LOGGER = LoggerFactory.getLogger(LuaClientCodegen.class);
protected String specFolder = "spec";
protected String packageName = "openapiclient";
diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/MarkdownDocumentationCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/MarkdownDocumentationCodegen.java
index 463bdb147b..d95f953beb 100644
--- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/MarkdownDocumentationCodegen.java
+++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/MarkdownDocumentationCodegen.java
@@ -16,7 +16,7 @@ import static org.openapitools.codegen.utils.StringUtils.escape;
public class MarkdownDocumentationCodegen extends DefaultCodegen implements CodegenConfig {
public static final String PROJECT_NAME = "projectName";
- private static final Logger LOGGER = LoggerFactory.getLogger(MarkdownDocumentationCodegen.class);
+ private final Logger LOGGER = LoggerFactory.getLogger(MarkdownDocumentationCodegen.class);
public CodegenType getTag() {
return CodegenType.DOCUMENTATION;
diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/MysqlSchemaCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/MysqlSchemaCodegen.java
index aa883ff9d9..abc3b4e657 100644
--- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/MysqlSchemaCodegen.java
+++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/MysqlSchemaCodegen.java
@@ -31,7 +31,7 @@ import static org.openapitools.codegen.utils.StringUtils.underscore;
@SuppressWarnings("unchecked")
public class MysqlSchemaCodegen extends DefaultCodegen implements CodegenConfig {
- private static final Logger LOGGER = LoggerFactory.getLogger(MysqlSchemaCodegen.class);
+ private final Logger LOGGER = LoggerFactory.getLogger(MysqlSchemaCodegen.class);
public static final String VENDOR_EXTENSION_MYSQL_SCHEMA = "x-mysql-schema";
public static final String DEFAULT_DATABASE_NAME = "defaultDatabaseName";
@@ -1196,7 +1196,7 @@ public class MysqlSchemaCodegen extends DefaultCodegen implements CodegenConfig
this.identifierNamingConvention = naming;
break;
default:
- LOGGER.warn("\"" + (String) naming + "\" is invalid \"identifierNamingConvention\" argument. Current \"" + (String) this.identifierNamingConvention + "\" used instead.");
+ LOGGER.warn("\"" + naming + "\" is invalid \"identifierNamingConvention\" argument. Current \"" + this.identifierNamingConvention + "\" used instead.");
}
}
diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/NimClientCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/NimClientCodegen.java
index f9803661b3..93d51b9433 100644
--- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/NimClientCodegen.java
+++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/NimClientCodegen.java
@@ -34,7 +34,7 @@ import java.util.*;
import static org.openapitools.codegen.utils.StringUtils.camelize;
public class NimClientCodegen extends DefaultCodegen implements CodegenConfig {
- static final Logger LOGGER = LoggerFactory.getLogger(NimClientCodegen.class);
+ final Logger LOGGER = LoggerFactory.getLogger(NimClientCodegen.class);
public static final String PROJECT_NAME = "projectName";
diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/NodeJSExpressServerCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/NodeJSExpressServerCodegen.java
index 4141155ff7..367451ff92 100644
--- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/NodeJSExpressServerCodegen.java
+++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/NodeJSExpressServerCodegen.java
@@ -44,7 +44,7 @@ import static org.openapitools.codegen.utils.StringUtils.camelize;
public class NodeJSExpressServerCodegen extends DefaultCodegen implements CodegenConfig {
- private static final Logger LOGGER = LoggerFactory.getLogger(NodeJSExpressServerCodegen.class);
+ private final Logger LOGGER = LoggerFactory.getLogger(NodeJSExpressServerCodegen.class);
public static final String EXPORTED_NAME = "exportedName";
public static final String SERVER_HOST = "serverHost";
public static final String SERVER_PORT = "serverPort";
diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/OCamlClientCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/OCamlClientCodegen.java
index c75c08053a..de67d097b7 100644
--- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/OCamlClientCodegen.java
+++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/OCamlClientCodegen.java
@@ -41,7 +41,7 @@ import static org.openapitools.codegen.utils.StringUtils.escape;
import static org.openapitools.codegen.utils.StringUtils.underscore;
public class OCamlClientCodegen extends DefaultCodegen implements CodegenConfig {
- private static final Logger LOGGER = LoggerFactory.getLogger(OCamlClientCodegen.class);
+ private final Logger LOGGER = LoggerFactory.getLogger(OCamlClientCodegen.class);
public static final String PACKAGE_NAME = "packageName";
public static final String PACKAGE_VERSION = "packageVersion";
@@ -727,6 +727,12 @@ public class OCamlClientCodegen extends DefaultCodegen implements CodegenConfig
if ("Yojson.Safe.t".equals(operation.returnBaseType)) {
operation.vendorExtensions.put("x-return-free-form-object", true);
}
+
+ if (operation.returnType != null && operation.returnType.startsWith("Enums.")) {
+ String returnTypeEnum = operation.returnType.replaceAll(" list$", "");
+ operation.vendorExtensions.put("x-returntype-enum", returnTypeEnum);
+ operation.vendorExtensions.put("x-returntype-is-enum", true);
+ }
}
for (Map.Entry e : enumUniqNames.entrySet()) {
diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/ObjcClientCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/ObjcClientCodegen.java
index 11d68c0771..18417aa777 100644
--- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/ObjcClientCodegen.java
+++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/ObjcClientCodegen.java
@@ -33,7 +33,7 @@ import static org.openapitools.codegen.utils.OnceLogger.once;
import static org.openapitools.codegen.utils.StringUtils.camelize;
public class ObjcClientCodegen extends DefaultCodegen implements CodegenConfig {
- private static final Logger LOGGER = LoggerFactory.getLogger(ObjcClientCodegen.class);
+ private final Logger LOGGER = LoggerFactory.getLogger(ObjcClientCodegen.class);
public static final String CLASS_PREFIX = "classPrefix";
public static final String POD_NAME = "podName";
diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/OpenAPIGenerator.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/OpenAPIGenerator.java
index 04f08dadaa..9902ddb074 100644
--- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/OpenAPIGenerator.java
+++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/OpenAPIGenerator.java
@@ -32,7 +32,7 @@ import java.util.EnumSet;
public class OpenAPIGenerator extends DefaultCodegen implements CodegenConfig {
public static final String OUTPUT_NAME = "outputFileName";
- private static final Logger LOGGER = LoggerFactory.getLogger(OpenAPIGenerator.class);
+ private final Logger LOGGER = LoggerFactory.getLogger(OpenAPIGenerator.class);
protected String outputFileName = "openapi.json";
diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/OpenAPIYamlGenerator.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/OpenAPIYamlGenerator.java
index 4d678a5ad2..37e8472ec4 100644
--- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/OpenAPIYamlGenerator.java
+++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/OpenAPIYamlGenerator.java
@@ -36,7 +36,7 @@ import java.util.Map;
public class OpenAPIYamlGenerator extends DefaultCodegen implements CodegenConfig {
public static final String OUTPUT_NAME = "outputFile";
- private static final Logger LOGGER = LoggerFactory.getLogger(OpenAPIYamlGenerator.class);
+ private final Logger LOGGER = LoggerFactory.getLogger(OpenAPIYamlGenerator.class);
protected String outputFile = "openapi/openapi.yaml";
diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/PerlClientCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/PerlClientCodegen.java
index 16c360a7ba..49ceeb1e22 100644
--- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/PerlClientCodegen.java
+++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/PerlClientCodegen.java
@@ -36,7 +36,7 @@ import static org.openapitools.codegen.utils.StringUtils.camelize;
import static org.openapitools.codegen.utils.StringUtils.underscore;
public class PerlClientCodegen extends DefaultCodegen implements CodegenConfig {
- private static final Logger LOGGER = LoggerFactory.getLogger(PerlClientCodegen.class);
+ private final Logger LOGGER = LoggerFactory.getLogger(PerlClientCodegen.class);
public static final String MODULE_NAME = "moduleName";
public static final String MODULE_VERSION = "moduleVersion";
diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/PhpClientCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/PhpClientCodegen.java
index 5e85b1e0a4..6049bfa394 100644
--- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/PhpClientCodegen.java
+++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/PhpClientCodegen.java
@@ -34,7 +34,7 @@ import java.util.List;
public class PhpClientCodegen extends AbstractPhpCodegen {
@SuppressWarnings("hiding")
- private static final Logger LOGGER = LoggerFactory.getLogger(PhpClientCodegen.class);
+ private final Logger LOGGER = LoggerFactory.getLogger(PhpClientCodegen.class);
public PhpClientCodegen() {
super();
diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/PhpMezzioPathHandlerServerCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/PhpMezzioPathHandlerServerCodegen.java
index 7630de3225..658537e414 100644
--- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/PhpMezzioPathHandlerServerCodegen.java
+++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/PhpMezzioPathHandlerServerCodegen.java
@@ -34,7 +34,7 @@ import java.io.File;
import java.util.*;
public class PhpMezzioPathHandlerServerCodegen extends AbstractPhpCodegen {
- private static final Logger LOGGER = LoggerFactory.getLogger(PhpMezzioPathHandlerServerCodegen.class);
+ private final Logger LOGGER = LoggerFactory.getLogger(PhpMezzioPathHandlerServerCodegen.class);
// TODO: Rename to x- prefixed vendor extensions, per specification.
public static final String VEN_FROM_QUERY = "internal.ze-ph.fromQuery";
diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/PhpSlim4ServerCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/PhpSlim4ServerCodegen.java
index 1c4a9e1295..d45bf289e7 100644
--- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/PhpSlim4ServerCodegen.java
+++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/PhpSlim4ServerCodegen.java
@@ -28,7 +28,7 @@ import org.slf4j.LoggerFactory;
import java.io.File;
public class PhpSlim4ServerCodegen extends PhpSlimServerCodegen {
- private static final Logger LOGGER = LoggerFactory.getLogger(PhpSlim4ServerCodegen.class);
+ private final Logger LOGGER = LoggerFactory.getLogger(PhpSlim4ServerCodegen.class);
public static final String PSR7_IMPLEMENTATION = "psr7Implementation";
@@ -147,7 +147,7 @@ public class PhpSlim4ServerCodegen extends PhpSlimServerCodegen {
break;
default:
this.psr7Implementation = "slim-psr7";
- LOGGER.warn("\"" + (String) psr7Implementation + "\" is invalid \"psr7Implementation\" argument. Default \"slim-psr7\" used instead.");
+ LOGGER.warn("\"" + psr7Implementation + "\" is invalid \"psr7Implementation\" argument. Default \"slim-psr7\" used instead.");
}
}
diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/PhpSlimServerCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/PhpSlimServerCodegen.java
index 02ebea31b0..6fb92a794e 100644
--- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/PhpSlimServerCodegen.java
+++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/PhpSlimServerCodegen.java
@@ -37,7 +37,7 @@ import java.util.*;
import static org.openapitools.codegen.utils.StringUtils.camelize;
public class PhpSlimServerCodegen extends AbstractPhpCodegen {
- private static final Logger LOGGER = LoggerFactory.getLogger(PhpSlimServerCodegen.class);
+ private final Logger LOGGER = LoggerFactory.getLogger(PhpSlimServerCodegen.class);
public static final String USER_CLASSNAME_KEY = "userClassname";
diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/PhpSymfonyServerCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/PhpSymfonyServerCodegen.java
index 30c41f7f29..a019893978 100644
--- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/PhpSymfonyServerCodegen.java
+++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/PhpSymfonyServerCodegen.java
@@ -34,7 +34,7 @@ import static org.openapitools.codegen.utils.StringUtils.camelize;
public class PhpSymfonyServerCodegen extends AbstractPhpCodegen implements CodegenConfig {
@SuppressWarnings("hiding")
- private static final Logger LOGGER = LoggerFactory.getLogger(PhpSymfonyServerCodegen.class);
+ private final Logger LOGGER = LoggerFactory.getLogger(PhpSymfonyServerCodegen.class);
public static final String BUNDLE_NAME = "bundleName";
public static final String BUNDLE_ALIAS = "bundleAlias";
diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/PlantumlDocumentationCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/PlantumlDocumentationCodegen.java
index 23e527eb91..1741ef18b4 100644
--- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/PlantumlDocumentationCodegen.java
+++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/PlantumlDocumentationCodegen.java
@@ -29,7 +29,7 @@ import java.util.stream.Collectors;
public class PlantumlDocumentationCodegen extends DefaultCodegen implements CodegenConfig {
public static final String ALL_OF_SUFFIX = "AllOf";
- static final Logger LOGGER = LoggerFactory.getLogger(PlantumlDocumentationCodegen.class);
+ final Logger LOGGER = LoggerFactory.getLogger(PlantumlDocumentationCodegen.class);
public CodegenType getTag() {
return CodegenType.DOCUMENTATION;
diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/PowerShellClientCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/PowerShellClientCodegen.java
index ccfcf6d55e..20b1b04a39 100644
--- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/PowerShellClientCodegen.java
+++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/PowerShellClientCodegen.java
@@ -37,7 +37,7 @@ import static java.util.UUID.randomUUID;
import static org.openapitools.codegen.utils.StringUtils.camelize;
public class PowerShellClientCodegen extends DefaultCodegen implements CodegenConfig {
- private static final Logger LOGGER = LoggerFactory.getLogger(PowerShellClientCodegen.class);
+ private final Logger LOGGER = LoggerFactory.getLogger(PowerShellClientCodegen.class);
private String packageGuid = "{" + randomUUID().toString().toUpperCase(Locale.ROOT) + "}";
@@ -604,7 +604,7 @@ public class PowerShellClientCodegen extends DefaultCodegen implements CodegenCo
this.iconUri = iconUri;
}
- public void setSkipVerbParsing(boolean skipVerbParsing) { this.skipVerbParsing = skipVerbParsing; };
+ public void setSkipVerbParsing(boolean skipVerbParsing) { this.skipVerbParsing = skipVerbParsing; }
@Override
public void processOpts() {
diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/ProtobufSchemaCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/ProtobufSchemaCodegen.java
index 24548ffbd7..e7bc5b46ef 100644
--- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/ProtobufSchemaCodegen.java
+++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/ProtobufSchemaCodegen.java
@@ -47,7 +47,7 @@ public class ProtobufSchemaCodegen extends DefaultCodegen implements CodegenConf
private static final String IMPORTS = "imports";
- private static final Logger LOGGER = LoggerFactory.getLogger(ProtobufSchemaCodegen.class);
+ private final Logger LOGGER = LoggerFactory.getLogger(ProtobufSchemaCodegen.class);
protected String packageName = "openapitools";
diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/PythonAiohttpConnexionServerCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/PythonAiohttpConnexionServerCodegen.java
index 77fd92ae97..c5474260b6 100644
--- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/PythonAiohttpConnexionServerCodegen.java
+++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/PythonAiohttpConnexionServerCodegen.java
@@ -23,7 +23,7 @@ import org.slf4j.LoggerFactory;
import java.util.EnumSet;
public class PythonAiohttpConnexionServerCodegen extends AbstractPythonConnexionServerCodegen {
- private static final Logger LOGGER = LoggerFactory.getLogger(PythonAiohttpConnexionServerCodegen.class);
+ private final Logger LOGGER = LoggerFactory.getLogger(PythonAiohttpConnexionServerCodegen.class);
public PythonAiohttpConnexionServerCodegen() {
super("python-aiohttp", true);
diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/PythonBluePlanetServerCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/PythonBluePlanetServerCodegen.java
index 3d169dea33..964b942e86 100755
--- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/PythonBluePlanetServerCodegen.java
+++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/PythonBluePlanetServerCodegen.java
@@ -25,7 +25,7 @@ import java.io.File;
import java.util.EnumSet;
public class PythonBluePlanetServerCodegen extends AbstractPythonConnexionServerCodegen {
- private static final Logger LOGGER = LoggerFactory.getLogger(PythonBluePlanetServerCodegen.class);
+ private final Logger LOGGER = LoggerFactory.getLogger(PythonBluePlanetServerCodegen.class);
protected String modelDocPath = "";
protected String modelTestPath = "";
diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/PythonClientCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/PythonClientCodegen.java
index d0d3fd79d4..505640121d 100644
--- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/PythonClientCodegen.java
+++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/PythonClientCodegen.java
@@ -48,7 +48,7 @@ import java.util.regex.Matcher;
import static org.openapitools.codegen.utils.OnceLogger.once;
public class PythonClientCodegen extends PythonLegacyClientCodegen {
- private static final Logger LOGGER = LoggerFactory.getLogger(PythonClientCodegen.class);
+ private final Logger LOGGER = LoggerFactory.getLogger(PythonClientCodegen.class);
// A cache to efficiently lookup a Schema instance based on the return value of `toModelName()`.
private Map modelNameToSchemaCache;
@@ -965,17 +965,17 @@ public class PythonClientCodegen extends PythonLegacyClientCodegen {
example = objExample.toString();
}
// checks if the current schema has already been passed in. If so, breaks the current recursive pass
- if (seenSchemas.contains(schema)){
+ if (seenSchemas.contains(schema)) {
if (modelName != null) {
return fullPrefix + modelName + closeChars;
} else {
// this is a recursive schema
// need to add a reasonable example to avoid
// infinite recursion
- if(ModelUtils.isNullable(schema)) {
+ if (ModelUtils.isNullable(schema)) {
// if the schema is nullable, then 'None' is a valid value
return fullPrefix + "None" + closeChars;
- } else if(ModelUtils.isArraySchema(schema)) {
+ } else if (ModelUtils.isArraySchema(schema)) {
// the schema is an array, add an empty array
return fullPrefix + "[]" + closeChars;
} else {
diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/PythonFlaskConnexionServerCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/PythonFlaskConnexionServerCodegen.java
index a1b9abaa7a..79fa8885b2 100644
--- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/PythonFlaskConnexionServerCodegen.java
+++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/PythonFlaskConnexionServerCodegen.java
@@ -23,7 +23,7 @@ import org.slf4j.LoggerFactory;
import java.io.File;
public class PythonFlaskConnexionServerCodegen extends AbstractPythonConnexionServerCodegen {
- private static final Logger LOGGER = LoggerFactory.getLogger(PythonFlaskConnexionServerCodegen.class);
+ private final Logger LOGGER = LoggerFactory.getLogger(PythonFlaskConnexionServerCodegen.class);
public PythonFlaskConnexionServerCodegen() {
super("python-flask", false);
diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/PythonLegacyClientCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/PythonLegacyClientCodegen.java
index fbefdec425..1a79a3bc03 100644
--- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/PythonLegacyClientCodegen.java
+++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/PythonLegacyClientCodegen.java
@@ -38,8 +38,8 @@ import java.util.regex.Pattern;
import static org.openapitools.codegen.utils.StringUtils.camelize;
import static org.openapitools.codegen.utils.StringUtils.underscore;
-public class PythonLegacyClientCodegen extends DefaultCodegen implements CodegenConfig {
- private static final Logger LOGGER = LoggerFactory.getLogger(PythonLegacyClientCodegen.class);
+public class PythonLegacyClientCodegen extends AbstractPythonCodegen implements CodegenConfig {
+ private final Logger LOGGER = LoggerFactory.getLogger(PythonLegacyClientCodegen.class);
public static final String PACKAGE_URL = "packageUrl";
public static final String DEFAULT_LIBRARY = "urllib3";
@@ -47,9 +47,6 @@ public class PythonLegacyClientCodegen extends DefaultCodegen implements Codegen
public static final String USE_NOSE = "useNose";
public static final String RECURSION_LIMIT = "recursionLimit";
- protected String packageName = "openapi_client";
- protected String packageVersion = "1.0.0";
- protected String projectName; // for setup.py, e.g. petstore-api
protected String packageUrl;
protected String apiDocPath = "docs/";
protected String modelDocPath = "docs/";
@@ -110,45 +107,6 @@ public class PythonLegacyClientCodegen extends DefaultCodegen implements Codegen
// default HIDE_GENERATION_TIMESTAMP to true
hideGenerationTimestamp = Boolean.TRUE;
- languageSpecificPrimitives.clear();
- languageSpecificPrimitives.add("int");
- languageSpecificPrimitives.add("float");
- languageSpecificPrimitives.add("list");
- languageSpecificPrimitives.add("dict");
- languageSpecificPrimitives.add("bool");
- languageSpecificPrimitives.add("str");
- languageSpecificPrimitives.add("datetime");
- languageSpecificPrimitives.add("date");
- languageSpecificPrimitives.add("object");
- // TODO file and binary is mapped as `file`
- languageSpecificPrimitives.add("file");
- languageSpecificPrimitives.add("bytes");
-
- typeMapping.clear();
- typeMapping.put("integer", "int");
- typeMapping.put("float", "float");
- typeMapping.put("number", "float");
- typeMapping.put("long", "int");
- typeMapping.put("double", "float");
- typeMapping.put("array", "list");
- typeMapping.put("set", "list");
- typeMapping.put("map", "dict");
- typeMapping.put("boolean", "bool");
- typeMapping.put("string", "str");
- typeMapping.put("date", "date");
- typeMapping.put("DateTime", "datetime");
- typeMapping.put("object", "object");
- typeMapping.put("AnyType", "object");
- typeMapping.put("file", "file");
- // TODO binary should be mapped to byte array
- // mapped to String as a workaround
- typeMapping.put("binary", "str");
- typeMapping.put("ByteArray", "str");
- // map uuid to string for the time being
- typeMapping.put("UUID", "str");
- typeMapping.put("URI", "str");
- typeMapping.put("null", "none_type");
-
// from https://docs.python.org/3/reference/lexical_analysis.html#keywords
setReservedWordsLowerCase(
Arrays.asList(
@@ -209,10 +167,6 @@ public class PythonLegacyClientCodegen extends DefaultCodegen implements Codegen
Boolean excludeTests = false;
- if (additionalProperties.containsKey(CodegenConstants.EXCLUDE_TESTS)) {
- excludeTests = Boolean.valueOf(additionalProperties.get(CodegenConstants.EXCLUDE_TESTS).toString());
- }
-
if (additionalProperties.containsKey(CodegenConstants.PACKAGE_NAME)) {
setPackageName((String) additionalProperties.get(CodegenConstants.PACKAGE_NAME));
}
@@ -229,15 +183,19 @@ public class PythonLegacyClientCodegen extends DefaultCodegen implements Codegen
setPackageVersion((String) additionalProperties.get(CodegenConstants.PACKAGE_VERSION));
}
+ additionalProperties.put(CodegenConstants.PROJECT_NAME, projectName);
+ additionalProperties.put(CodegenConstants.PACKAGE_NAME, packageName);
+ additionalProperties.put(CodegenConstants.PACKAGE_VERSION, packageVersion);
+
+ if (additionalProperties.containsKey(CodegenConstants.EXCLUDE_TESTS)) {
+ excludeTests = Boolean.valueOf(additionalProperties.get(CodegenConstants.EXCLUDE_TESTS).toString());
+ }
+
Boolean generateSourceCodeOnly = false;
if (additionalProperties.containsKey(CodegenConstants.SOURCECODEONLY_GENERATION)) {
generateSourceCodeOnly = Boolean.valueOf(additionalProperties.get(CodegenConstants.SOURCECODEONLY_GENERATION).toString());
}
- additionalProperties.put(CodegenConstants.PROJECT_NAME, projectName);
- additionalProperties.put(CodegenConstants.PACKAGE_NAME, packageName);
- additionalProperties.put(CodegenConstants.PACKAGE_VERSION, packageVersion);
-
if (generateSourceCodeOnly) {
// tests in /test
testFolder = packagePath() + File.separatorChar + testFolder;
@@ -260,8 +218,8 @@ public class PythonLegacyClientCodegen extends DefaultCodegen implements Codegen
// check to see if setRecursionLimit is set and whether it's an integer
if (additionalProperties.containsKey(RECURSION_LIMIT)) {
try {
- Integer.parseInt((String)additionalProperties.get(RECURSION_LIMIT));
- } catch(NumberFormatException | NullPointerException e) {
+ Integer.parseInt((String) additionalProperties.get(RECURSION_LIMIT));
+ } catch (NumberFormatException | NullPointerException e) {
throw new IllegalArgumentException("recursionLimit must be an integer, e.g. 2000.");
}
}
@@ -320,15 +278,11 @@ public class PythonLegacyClientCodegen extends DefaultCodegen implements Codegen
supportingFiles.add(new SupportingFile("rest.mustache", packagePath(), "rest.py"));
}
- modelPackage = packageName + "." + modelPackage;
- apiPackage = packageName + "." + apiPackage;
+ modelPackage = this.packageName + "." + modelPackage;
+ apiPackage = this.packageName + "." + apiPackage;
}
- protected static String dropDots(String str) {
- return str.replaceAll("\\.", "_");
- }
-
@Override
public String toModelImport(String name) {
String modelImport;
@@ -405,13 +359,6 @@ public class PythonLegacyClientCodegen extends DefaultCodegen implements Codegen
return "Generates a Python client library.";
}
- @Override
- public String escapeReservedWord(String name) {
- if (this.reservedWordsMappings().containsKey(name)) {
- return this.reservedWordsMappings().get(name);
- }
- return "_" + name;
- }
@Override
public String apiDocFileFolder() {
@@ -467,181 +414,11 @@ public class PythonLegacyClientCodegen extends DefaultCodegen implements Codegen
return outputFolder + File.separatorChar + testFolder;
}
- @Override
- public String getTypeDeclaration(Schema p) {
- if (ModelUtils.isArraySchema(p)) {
- ArraySchema ap = (ArraySchema) p;
- Schema inner = ap.getItems();
- return getSchemaType(p) + "[" + getTypeDeclaration(inner) + "]";
- } else if (ModelUtils.isMapSchema(p)) {
- Schema inner = getAdditionalProperties(p);
-
- return getSchemaType(p) + "(str, " + getTypeDeclaration(inner) + ")";
- }
- return super.getTypeDeclaration(p);
- }
-
- @Override
- public String getSchemaType(Schema p) {
- String openAPIType = super.getSchemaType(p);
- String type = null;
- if (typeMapping.containsKey(openAPIType)) {
- type = typeMapping.get(openAPIType);
- if (languageSpecificPrimitives.contains(type)) {
- return type;
- }
- } else {
- type = toModelName(openAPIType);
- }
- return type;
- }
-
- @Override
- public String toVarName(String name) {
- // sanitize name
- name = sanitizeName(name); // FIXME: a parameter should not be assigned. Also declare the methods parameters as 'final'.
-
- // remove dollar sign
- name = name.replaceAll("$", "");
-
- // if it's all uppper case, convert to lower case
- if (name.matches("^[A-Z_]*$")) {
- name = name.toLowerCase(Locale.ROOT);
- }
-
- // underscore the variable name
- // petId => pet_id
- name = underscore(name);
-
- // remove leading underscore
- name = name.replaceAll("^_*", "");
-
- // for reserved word or word starting with number, append _
- if (isReservedWord(name) || name.matches("^\\d.*")) {
- name = escapeReservedWord(name);
- }
-
- return name;
- }
-
- @Override
- public String toParamName(String name) {
- // to avoid conflicts with 'callback' parameter for async call
- if ("callback".equals(name)) {
- return "param_callback";
- }
-
- // should be the same as variable name
- return toVarName(name);
- }
-
- @Override
- public String toModelName(String name) {
- name = sanitizeName(name); // FIXME: a parameter should not be assigned. Also declare the methods parameters as 'final'.
- // remove dollar sign
- name = name.replaceAll("$", "");
-
- // model name cannot use reserved keyword, e.g. return
- if (isReservedWord(name)) {
- LOGGER.warn(name + " (reserved word) cannot be used as model name. Renamed to " + camelize("model_" + name));
- name = "model_" + name; // e.g. return => ModelReturn (after camelize)
- }
-
- // model name starts with number
- if (name.matches("^\\d.*")) {
- LOGGER.warn(name + " (model name starts with number) cannot be used as model name. Renamed to " + camelize("model_" + name));
- name = "model_" + name; // e.g. 200Response => Model200Response (after camelize)
- }
-
- if (!StringUtils.isEmpty(modelNamePrefix)) {
- name = modelNamePrefix + "_" + name;
- }
-
- if (!StringUtils.isEmpty(modelNameSuffix)) {
- name = name + "_" + modelNameSuffix;
- }
-
- // camelize the model name
- // phone_number => PhoneNumber
- return camelize(name);
- }
-
- @Override
- public String toModelFilename(String name) {
- // underscore the model file name
- // PhoneNumber => phone_number
- return underscore(dropDots(toModelName(name)));
- }
-
- @Override
- public String toModelTestFilename(String name) {
- return "test_" + toModelFilename(name);
- }
-
- @Override
- public String toApiFilename(String name) {
- // replace - with _ e.g. created-at => created_at
- name = name.replaceAll("-", "_");
-
- // e.g. PhoneNumberApi.py => phone_number_api.py
- return underscore(name + "_" + apiNameSuffix);
- }
-
- @Override
- public String toApiTestFilename(String name) {
- return "test_" + toApiFilename(name);
- }
-
- @Override
- public String toApiName(String name) {
- return super.toApiName(name);
- }
-
- @Override
- public String toApiVarName(String name) {
- if (name.length() == 0) {
- return "default_api";
- }
- return underscore(name + "_" + apiNameSuffix);
- }
-
- @Override
- public String toOperationId(String operationId) {
- // throw exception if method name is empty (should not occur as an auto-generated method name will be used)
- if (StringUtils.isEmpty(operationId)) {
- throw new RuntimeException("Empty method name (operationId) not allowed");
- }
-
- // method name cannot use reserved keyword, e.g. return
- if (isReservedWord(operationId)) {
- LOGGER.warn(operationId + " (reserved word) cannot be used as method name. Renamed to " + underscore(sanitizeName("call_" + operationId)));
- operationId = "call_" + operationId;
- }
-
- // operationId starts with a number
- if (operationId.matches("^\\d.*")) {
- LOGGER.warn(operationId + " (starting with a number) cannot be used as method name. Renamed to " + underscore(sanitizeName("call_" + operationId)));
- operationId = "call_" + operationId;
- }
-
- return underscore(sanitizeName(operationId));
- }
-
- public void setPackageName(String packageName) {
- this.packageName = packageName;
- }
public void setUseNose(String val) {
this.useNose = Boolean.valueOf(val);
}
- public void setProjectName(String projectName) {
- this.projectName = projectName;
- }
-
- public void setPackageVersion(String packageVersion) {
- this.packageVersion = packageVersion;
- }
public void setPackageUrl(String packageUrl) {
this.packageUrl = packageUrl;
@@ -665,399 +442,4 @@ public class PythonLegacyClientCodegen extends DefaultCodegen implements Codegen
return underscore(packageName.replaceAll("[^\\w]+", ""));
}
- /**
- * Return the default value of the property
- *
- * @param p OpenAPI property object
- * @return string presentation of the default value of the property
- */
- @Override
- public String toDefaultValue(Schema p) {
- if (ModelUtils.isBooleanSchema(p)) {
- if (p.getDefault() != null) {
- if (Boolean.valueOf(p.getDefault().toString()) == false)
- return "False";
- else
- return "True";
- }
- } else if (ModelUtils.isDateSchema(p)) {
- // TODO
- } else if (ModelUtils.isDateTimeSchema(p)) {
- // TODO
- } else if (ModelUtils.isNumberSchema(p)) {
- if (p.getDefault() != null) {
- return p.getDefault().toString();
- }
- } else if (ModelUtils.isIntegerSchema(p)) {
- if (p.getDefault() != null) {
- return p.getDefault().toString();
- }
- } else if (ModelUtils.isStringSchema(p)) {
- if (p.getDefault() != null) {
- if (Pattern.compile("\r\n|\r|\n").matcher((String) p.getDefault()).find())
- return "'''" + p.getDefault() + "'''";
- else
- return "'" + ((String) p.getDefault()).replaceAll("'", "\'") + "'";
- }
- } else if (ModelUtils.isArraySchema(p)) {
- if (p.getDefault() != null) {
- return p.getDefault().toString();
- }
- }
-
- return null;
- }
-
- @Override
- public String toRegularExpression(String pattern) {
- return addRegularExpressionDelimiter(pattern);
- }
-
- @Override
- public String toExampleValue(Schema schema) {
- return toExampleValueRecursive(schema, new ArrayList(), 5);
- }
-
- private String toExampleValueRecursive(Schema schema, List included_schemas, int indentation) {
- String indentation_string = "";
- for (int i=0 ; i< indentation ; i++) indentation_string += " ";
- String example = null;
- if (schema.getExample() != null) {
- example = schema.getExample().toString();
- }
-
- if (ModelUtils.isNullType(schema) && null != example) {
- // The 'null' type is allowed in OAS 3.1 and above. It is not supported by OAS 3.0.x,
- // though this tooling supports it.
- return "None";
- }
- // correct "true"s into "True"s, since super.toExampleValue uses "toString()" on Java booleans
- if (ModelUtils.isBooleanSchema(schema) && null!=example) {
- if ("false".equalsIgnoreCase(example)) example = "False";
- else example = "True";
- }
-
- // correct "'"s into "'"s after toString()
- if (ModelUtils.isStringSchema(schema) && schema.getDefault() != null && !ModelUtils.isDateSchema(schema) && !ModelUtils.isDateTimeSchema(schema)) {
- example = (String) schema.getDefault();
- }
-
- if (StringUtils.isNotBlank(example) && !"null".equals(example)) {
- if (ModelUtils.isStringSchema(schema)) {
- example = "'" + example + "'";
- }
- return example;
- }
-
- if (schema.getEnum() != null && !schema.getEnum().isEmpty()) {
- // Enum case:
- example = schema.getEnum().get(0).toString();
- if (ModelUtils.isStringSchema(schema)) {
- example = "'" + escapeText(example) + "'";
- }
- if (null == example)
- LOGGER.warn("Empty enum. Cannot built an example!");
-
- return example;
- } else if (null != schema.get$ref()) {
- // $ref case:
- Map allDefinitions = ModelUtils.getSchemas(this.openAPI);
- String ref = ModelUtils.getSimpleRef(schema.get$ref());
- if (allDefinitions != null) {
- Schema refSchema = allDefinitions.get(ref);
- if (null == refSchema) {
- return "None";
- } else {
- String refTitle = refSchema.getTitle();
- if (StringUtils.isBlank(refTitle) || "null".equals(refTitle)) {
- refSchema.setTitle(ref);
- }
- if (StringUtils.isNotBlank(schema.getTitle()) && !"null".equals(schema.getTitle())) {
- included_schemas.add(schema.getTitle());
- }
- return toExampleValueRecursive(refSchema, included_schemas, indentation);
- }
- } else {
- LOGGER.warn("allDefinitions not defined in toExampleValue!\n");
- }
- }
- if (ModelUtils.isDateSchema(schema)) {
- example = "datetime.datetime.strptime('1975-12-30', '%Y-%m-%d').date()";
- return example;
- } else if (ModelUtils.isDateTimeSchema(schema)) {
- example = "datetime.datetime.strptime('2013-10-20 19:20:30.00', '%Y-%m-%d %H:%M:%S.%f')";
- return example;
- } else if (ModelUtils.isBinarySchema(schema)) {
- example = "bytes(b'blah')";
- return example;
- } else if (ModelUtils.isByteArraySchema(schema)) {
- example = "YQ==";
- } else if (ModelUtils.isStringSchema(schema)) {
- // a BigDecimal:
- if ("Number".equalsIgnoreCase(schema.getFormat())) {return "1";}
- if (StringUtils.isNotBlank(schema.getPattern())) {
- String pattern = schema.getPattern();
- RgxGen rgxGen = new RgxGen(patternCorrection(pattern));
- // this seed makes it so if we have [a-z] we pick a
- Random random = new Random(18);
- String sample = rgxGen.generate(random);
- // omit leading / and trailing /, omit trailing /i
- Pattern valueExtractor = Pattern.compile("^/\\^?(.+?)\\$?/.?$");
- Matcher m = valueExtractor.matcher(sample);
- if (m.find()) {
- example = m.group(m.groupCount());
- } else {
- example = sample;
- }
- }
- if (example == null) {
- example = "";
- }
- int len = 0;
- if (null != schema.getMinLength()) {
- len = schema.getMinLength().intValue();
- if (len < 1) {
- example = "";
- } else {
- for (int i=0;i reqs = schema.getRequired();
-
- // if required and optionals
- List reqs = new ArrayList<>();
- if (schema.getProperties() != null && !schema.getProperties().isEmpty()) {
- for (Object toAdd : schema.getProperties().keySet()) {
- reqs.add((String) toAdd);
- }
-
- Map properties = schema.getProperties();
- Set propkeys = null;
- if (properties != null) propkeys = properties.keySet();
- if (toExclude != null && reqs.contains(toExclude)) {
- reqs.remove(toExclude);
- }
- for (String toRemove : included_schemas) {
- if (reqs.contains(toRemove)) {
- reqs.remove(toRemove);
- }
- }
- if (StringUtils.isNotBlank(schema.getTitle()) && !"null".equals(schema.getTitle())) {
- included_schemas.add(schema.getTitle());
- }
- if (null != schema.getRequired()) for (Object toAdd : schema.getRequired()) {
- reqs.add((String) toAdd);
- }
- if (null != propkeys) for (String propname : propkeys) {
- Schema schema2 = properties.get(propname);
- if (reqs.contains(propname)) {
- String refTitle = schema2.getTitle();
- if (StringUtils.isBlank(refTitle) || "null".equals(refTitle)) {
- schema2.setTitle(propname);
- }
- example += "\n" + indentation_string + underscore(propname) + " = " +
- toExampleValueRecursive(schema2, included_schemas, indentation + 1) + ", ";
- }
- }
- }
- example +=")";
- } else {
- LOGGER.warn("Type " + schema.getType() + " not handled properly in toExampleValue");
- }
-
- if (ModelUtils.isStringSchema(schema)) {
- example = "'" + escapeText(example) + "'";
- }
-
- return example;
- }
-
- @Override
- public void setParameterExampleValue(CodegenParameter p) {
- String example;
-
- if (p.defaultValue == null) {
- example = p.example;
- } else {
- p.example = p.defaultValue;
- return;
- }
-
- String type = p.baseType;
- if (type == null) {
- type = p.dataType;
- }
-
- if ("String".equalsIgnoreCase(type) || "str".equalsIgnoreCase(type)) {
- if (example == null) {
- example = p.paramName + "_example";
- }
- example = "'" + escapeText(example) + "'";
- } else if ("Integer".equals(type) || "int".equals(type)) {
- if (example == null) {
- example = "56";
- }
- } else if ("Float".equalsIgnoreCase(type) || "Double".equalsIgnoreCase(type)) {
- if (example == null) {
- example = "3.4";
- }
- } else if ("BOOLEAN".equalsIgnoreCase(type) || "bool".equalsIgnoreCase(type)) {
- if (example == null) {
- example = "True";
- }
- } else if ("file".equalsIgnoreCase(type)) {
- if (example == null) {
- example = "/path/to/file";
- }
- example = "'" + escapeText(example) + "'";
- } else if ("Date".equalsIgnoreCase(type)) {
- if (example == null) {
- example = "2013-10-20";
- }
- example = "'" + escapeText(example) + "'";
- } else if ("DateTime".equalsIgnoreCase(type)) {
- if (example == null) {
- example = "2013-10-20T19:20:30+01:00";
- }
- example = "'" + escapeText(example) + "'";
- } else if (!languageSpecificPrimitives.contains(type)) {
- // type is a model class, e.g. User
- example = this.packageName + "." + type + "()";
- } else {
- LOGGER.warn("Type " + type + " not handled properly in setParameterExampleValue");
- }
-
- if (example == null) {
- example = "None";
- } else if (Boolean.TRUE.equals(p.isArray)) {
- example = "[" + example + "]";
- } else if (Boolean.TRUE.equals(p.isMap)) {
- example = "{'key': " + example + "}";
- }
-
- p.example = example;
- }
-
- @Override
- public void setParameterExampleValue(CodegenParameter codegenParameter, Parameter parameter) {
- Schema schema = parameter.getSchema();
-
- if (parameter.getExample() != null) {
- codegenParameter.example = parameter.getExample().toString();
- } else if (parameter.getExamples() != null && !parameter.getExamples().isEmpty()) {
- Example example = parameter.getExamples().values().iterator().next();
- if (example.getValue() != null) {
- codegenParameter.example = example.getValue().toString();
- }
- } else if (schema != null && schema.getExample() != null) {
- codegenParameter.example = schema.getExample().toString();
- }
-
- setParameterExampleValue(codegenParameter);
- }
-
- @Override
- public String sanitizeTag(String tag) {
- return sanitizeName(tag);
- }
-
- @Override
- public String escapeQuotationMark(String input) {
- // remove ' to avoid code injection
- return input.replace("'", "");
- }
-
- @Override
- public String escapeUnsafeCharacters(String input) {
- // remove multiline comment
- return input.replace("'''", "'_'_'");
- }
-
- @Override
- public void postProcessFile(File file, String fileType) {
- if (file == null) {
- return;
- }
- String pythonPostProcessFile = System.getenv("PYTHON_POST_PROCESS_FILE");
- if (StringUtils.isEmpty(pythonPostProcessFile)) {
- return; // skip if PYTHON_POST_PROCESS_FILE env variable is not defined
- }
-
- // only process files with py extension
- if ("py".equals(FilenameUtils.getExtension(file.toString()))) {
- String command = pythonPostProcessFile + " " + file.toString();
- try {
- Process p = Runtime.getRuntime().exec(command);
- int exitValue = p.waitFor();
- if (exitValue != 0) {
- LOGGER.error("Error running the command ({}). Exit value: {}", command, exitValue);
- } else {
- LOGGER.info("Successfully executed: " + command);
- }
- } catch (Exception e) {
- LOGGER.error("Error running the command ({}). Exception: {}", command, e.getMessage());
- }
- }
- }
-
- public String patternCorrection(String pattern){
- // Java does not recognize starting and ending forward slashes and mode modifiers
- // It considers them as characters with no special meaning and tries to find them in the match string
- boolean checkEnding = pattern.endsWith("/i") || pattern.endsWith("/g") || pattern.endsWith("/m");
- if (checkEnding) pattern = pattern.substring(0, pattern.length()-2);
- if (pattern.endsWith("/")) pattern = pattern.substring(0, pattern.length()-1);
- if (pattern.startsWith("/")) pattern = pattern.substring(1);
- return pattern;
- }
}
diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/RClientCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/RClientCodegen.java
index 74cfe07f1f..208f4fc2cd 100644
--- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/RClientCodegen.java
+++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/RClientCodegen.java
@@ -36,7 +36,7 @@ import static org.openapitools.codegen.utils.StringUtils.camelize;
import static org.openapitools.codegen.utils.StringUtils.underscore;
public class RClientCodegen extends DefaultCodegen implements CodegenConfig {
- private static final Logger LOGGER = LoggerFactory.getLogger(RClientCodegen.class);
+ private final Logger LOGGER = LoggerFactory.getLogger(RClientCodegen.class);
protected String packageName = "openapi";
protected String packageVersion = "1.0.0";
diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/RubyClientCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/RubyClientCodegen.java
index 8bfd9097c1..83b020f7b8 100644
--- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/RubyClientCodegen.java
+++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/RubyClientCodegen.java
@@ -41,7 +41,7 @@ public class RubyClientCodegen extends AbstractRubyCodegen {
public static final String GEM_AUTHOR_EMAIL = "gemAuthorEmail";
public static final String FARADAY = "faraday";
public static final String TYPHOEUS = "typhoeus";
- private static final Logger LOGGER = LoggerFactory.getLogger(RubyClientCodegen.class);
+ private final Logger LOGGER = LoggerFactory.getLogger(RubyClientCodegen.class);
private static final String NUMERIC_ENUM_PREFIX = "N";
protected static int emptyMethodNameCounter = 0;
protected String gemName;
diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/RubyOnRailsServerCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/RubyOnRailsServerCodegen.java
index 5dcd18c372..16c4905c89 100644
--- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/RubyOnRailsServerCodegen.java
+++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/RubyOnRailsServerCodegen.java
@@ -37,7 +37,7 @@ import static org.openapitools.codegen.utils.StringUtils.underscore;
public class RubyOnRailsServerCodegen extends AbstractRubyCodegen {
- private static final Logger LOGGER = LoggerFactory.getLogger(RubyOnRailsServerCodegen.class);
+ private final Logger LOGGER = LoggerFactory.getLogger(RubyOnRailsServerCodegen.class);
protected String gemName;
protected String moduleName;
diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/RubySinatraServerCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/RubySinatraServerCodegen.java
index 23126e3b4a..12f8f9a2a7 100644
--- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/RubySinatraServerCodegen.java
+++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/RubySinatraServerCodegen.java
@@ -33,7 +33,7 @@ import static org.openapitools.codegen.utils.StringUtils.underscore;
public class RubySinatraServerCodegen extends AbstractRubyCodegen {
- private static final Logger LOGGER = LoggerFactory.getLogger(RubySinatraServerCodegen.class);
+ private final Logger LOGGER = LoggerFactory.getLogger(RubySinatraServerCodegen.class);
protected String gemName;
protected String moduleName;
diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/RustClientCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/RustClientCodegen.java
index 0922289612..61a9cc2c0d 100644
--- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/RustClientCodegen.java
+++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/RustClientCodegen.java
@@ -37,7 +37,7 @@ import static org.openapitools.codegen.utils.StringUtils.camelize;
import static org.openapitools.codegen.utils.StringUtils.underscore;
public class RustClientCodegen extends DefaultCodegen implements CodegenConfig {
- private static final Logger LOGGER = LoggerFactory.getLogger(RustClientCodegen.class);
+ private final Logger LOGGER = LoggerFactory.getLogger(RustClientCodegen.class);
private boolean useSingleRequestParameter = false;
private boolean supportAsync = true;
private boolean supportMultipleResponses = false;
diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/RustServerCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/RustServerCodegen.java
index 7a1b22b20c..8a490e8c88 100644
--- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/RustServerCodegen.java
+++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/RustServerCodegen.java
@@ -50,7 +50,7 @@ import static org.openapitools.codegen.utils.StringUtils.underscore;
public class RustServerCodegen extends DefaultCodegen implements CodegenConfig {
- private static final Logger LOGGER = LoggerFactory.getLogger(RustServerCodegen.class);
+ private final Logger LOGGER = LoggerFactory.getLogger(RustServerCodegen.class);
private HashMap modelXmlNames = new HashMap();
diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/ScalaFinchServerCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/ScalaFinchServerCodegen.java
index b899a00390..2c33062f94 100644
--- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/ScalaFinchServerCodegen.java
+++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/ScalaFinchServerCodegen.java
@@ -31,7 +31,7 @@ import java.util.*;
import static org.openapitools.codegen.utils.OnceLogger.once;
public class ScalaFinchServerCodegen extends DefaultCodegen implements CodegenConfig {
- private static final Logger LOGGER = LoggerFactory.getLogger(ScalaFinchServerCodegen.class);
+ private final Logger LOGGER = LoggerFactory.getLogger(ScalaFinchServerCodegen.class);
protected String invokerPackage = "org.openapitools.client";
protected String groupId = "org.openapitools";
protected String artifactId = "finch-server";
@@ -472,7 +472,18 @@ public class ScalaFinchServerCodegen extends DefaultCodegen implements CodegenCo
// The input parameters for functions
op.vendorExtensions.put("x-codegen-input-params", inputParams);
op.vendorExtensions.put("x-codegen-typed-input-params", typedInputParams);
+ }
+ @Override
+ public void postProcess() {
+ System.out.println("################################################################################");
+ System.out.println("# Thanks for using OpenAPI Generator. #");
+ System.out.println("# Please consider donation to help us maintain this project \uD83D\uDE4F #");
+ System.out.println("# https://opencollective.com/openapi_generator/donate #");
+ System.out.println("# #");
+ System.out.println("# This generator's contributed by Jim Schubert (https://github.com/jimschubert)#");
+ System.out.println("# Please support his work directly via https://patreon.com/jimschubert \uD83D\uDE4F #");
+ System.out.println("################################################################################");
}
}
diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/ScalaGatlingCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/ScalaGatlingCodegen.java
index 30d8c83d13..00f6f75f66 100644
--- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/ScalaGatlingCodegen.java
+++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/ScalaGatlingCodegen.java
@@ -39,7 +39,7 @@ import java.nio.charset.StandardCharsets;
import java.util.*;
public class ScalaGatlingCodegen extends AbstractScalaCodegen implements CodegenConfig {
- private static final Logger LOGGER = LoggerFactory.getLogger(ScalaGatlingCodegen.class);
+ private final Logger LOGGER = LoggerFactory.getLogger(ScalaGatlingCodegen.class);
// source folder where to write the files
protected String resourceFolder = "src" + File.separator + "gatling" + File.separator + "resources";
diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/ScalaHttpClientCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/ScalaHttpClientCodegen.java
index 27f0991bf7..ddd2aa168e 100644
--- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/ScalaHttpClientCodegen.java
+++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/ScalaHttpClientCodegen.java
@@ -37,7 +37,7 @@ import static org.openapitools.codegen.utils.StringUtils.underscore;
* This generator has been deprecated. Please use scala-akka instead.
*/
public class ScalaHttpClientCodegen extends AbstractScalaCodegen implements CodegenConfig {
- private static final Logger LOGGER = LoggerFactory.getLogger(ScalaHttpClientCodegen.class);
+ private final Logger LOGGER = LoggerFactory.getLogger(ScalaHttpClientCodegen.class);
protected String authScheme = "";
protected String gradleWrapperPackage = "gradle.wrapper";
diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/ScalaLagomServerCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/ScalaLagomServerCodegen.java
index 1585c8383b..3188d3889a 100644
--- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/ScalaLagomServerCodegen.java
+++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/ScalaLagomServerCodegen.java
@@ -29,7 +29,7 @@ import static org.openapitools.codegen.utils.StringUtils.camelize;
import static org.openapitools.codegen.utils.StringUtils.underscore;
public class ScalaLagomServerCodegen extends AbstractScalaCodegen implements CodegenConfig {
- private static final Logger LOGGER = LoggerFactory.getLogger(ScalaLagomServerCodegen.class);
+ private final Logger LOGGER = LoggerFactory.getLogger(ScalaLagomServerCodegen.class);
private String authScheme = "";
private boolean authPreemptive = false;
diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/ScalaPlayFrameworkServerCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/ScalaPlayFrameworkServerCodegen.java
index cb5f63bf55..b1313a713d 100644
--- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/ScalaPlayFrameworkServerCodegen.java
+++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/ScalaPlayFrameworkServerCodegen.java
@@ -48,7 +48,7 @@ public class ScalaPlayFrameworkServerCodegen extends AbstractScalaCodegen implem
public static final String ROUTES_FILE_NAME = "routesFileName";
public static final String BASE_PACKAGE = "basePackage";
- static final Logger LOGGER = LoggerFactory.getLogger(ScalaPlayFrameworkServerCodegen.class);
+ final Logger LOGGER = LoggerFactory.getLogger(ScalaPlayFrameworkServerCodegen.class);
protected boolean skipStubs = false;
protected boolean supportAsync = false;
diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/ScalazClientCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/ScalazClientCodegen.java
index 8ba9e1f8c4..a58deedc64 100644
--- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/ScalazClientCodegen.java
+++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/ScalazClientCodegen.java
@@ -40,7 +40,7 @@ import static org.openapitools.codegen.utils.StringUtils.camelize;
import static org.openapitools.codegen.utils.StringUtils.underscore;
public class ScalazClientCodegen extends AbstractScalaCodegen implements CodegenConfig {
- private static final Logger LOGGER = LoggerFactory.getLogger(ScalazClientCodegen.class);
+ private final Logger LOGGER = LoggerFactory.getLogger(ScalazClientCodegen.class);
public ScalazClientCodegen() {
super();
diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/SpringCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/SpringCodegen.java
index 409267e319..07f69dd984 100644
--- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/SpringCodegen.java
+++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/SpringCodegen.java
@@ -45,7 +45,7 @@ import static org.openapitools.codegen.utils.StringUtils.camelize;
public class SpringCodegen extends AbstractJavaCodegen
implements BeanValidationFeatures, PerformBeanValidationFeatures,
OptionalFeatures {
- private static final Logger LOGGER = LoggerFactory.getLogger(SpringCodegen.class);
+ private final Logger LOGGER = LoggerFactory.getLogger(SpringCodegen.class);
public static final String TITLE = "title";
public static final String SERVER_PORT = "serverPort";
diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/StaticHtml2Generator.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/StaticHtml2Generator.java
index 055b29417d..1436772691 100644
--- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/StaticHtml2Generator.java
+++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/StaticHtml2Generator.java
@@ -39,7 +39,7 @@ import static org.openapitools.codegen.utils.OnceLogger.once;
import static org.openapitools.codegen.utils.StringUtils.*;
public class StaticHtml2Generator extends DefaultCodegen implements CodegenConfig {
- private static final Logger LOGGER = LoggerFactory.getLogger(StaticHtml2Generator.class);
+ private final Logger LOGGER = LoggerFactory.getLogger(StaticHtml2Generator.class);
protected String invokerPackage = "org.openapitools.client"; // default for Java and Android
protected String phpInvokerPackage = "OpenAPITools\\Client"; // default for PHP
diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/Swift4Codegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/Swift4Codegen.java
index 59b214a549..e45af92535 100644
--- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/Swift4Codegen.java
+++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/Swift4Codegen.java
@@ -39,7 +39,7 @@ import java.util.regex.Pattern;
import static org.openapitools.codegen.utils.StringUtils.camelize;
public class Swift4Codegen extends DefaultCodegen implements CodegenConfig {
- private static final Logger LOGGER = LoggerFactory.getLogger(Swift4Codegen.class);
+ private final Logger LOGGER = LoggerFactory.getLogger(Swift4Codegen.class);
public static final String PROJECT_NAME = "projectName";
public static final String RESPONSE_AS = "responseAs";
diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/Swift5ClientCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/Swift5ClientCodegen.java
index a596757831..bf7a33d7b0 100644
--- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/Swift5ClientCodegen.java
+++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/Swift5ClientCodegen.java
@@ -43,7 +43,7 @@ import static org.openapitools.codegen.utils.StringUtils.camelize;
public class Swift5ClientCodegen extends DefaultCodegen implements CodegenConfig {
- private static final Logger LOGGER = LoggerFactory.getLogger(Swift5ClientCodegen.class);
+ private final Logger LOGGER = LoggerFactory.getLogger(Swift5ClientCodegen.class);
public static final String PROJECT_NAME = "projectName";
public static final String RESPONSE_AS = "responseAs";
@@ -628,7 +628,7 @@ public class Swift5ClientCodegen extends DefaultCodegen implements CodegenConfig
// Datetime time stamps in Swift are expressed as Seconds with Microsecond precision.
// In Java, we need to be creative to get the Timestamp in Microseconds as a long.
Instant instant = ((OffsetDateTime) p.getDefault()).toInstant();
- long epochMicro = TimeUnit.SECONDS.toMicros(instant.getEpochSecond()) + ((long) instant.get(ChronoField.MICRO_OF_SECOND));
+ long epochMicro = TimeUnit.SECONDS.toMicros(instant.getEpochSecond()) + (instant.get(ChronoField.MICRO_OF_SECOND));
return "Date(timeIntervalSince1970: " + String.valueOf(epochMicro) + ".0 / 1_000_000)";
} else if (ModelUtils.isStringSchema(p)) {
return "\"" + escapeText((String) p.getDefault()) + "\"";
diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/TypeScriptAngularClientCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/TypeScriptAngularClientCodegen.java
index 636091c620..a64323ee4c 100644
--- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/TypeScriptAngularClientCodegen.java
+++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/TypeScriptAngularClientCodegen.java
@@ -34,14 +34,14 @@ import static org.apache.commons.lang3.StringUtils.capitalize;
import static org.openapitools.codegen.utils.StringUtils.*;
public class TypeScriptAngularClientCodegen extends AbstractTypeScriptClientCodegen {
- private static final Logger LOGGER = LoggerFactory.getLogger(TypeScriptAngularClientCodegen.class);
+ private final Logger LOGGER = LoggerFactory.getLogger(TypeScriptAngularClientCodegen.class);
private static String CLASS_NAME_PREFIX_PATTERN = "^[a-zA-Z0-9]*$";
private static String CLASS_NAME_SUFFIX_PATTERN = "^[a-zA-Z0-9]*$";
private static String FILE_NAME_SUFFIX_PATTERN = "^[a-zA-Z0-9.-]*$";
- public static enum QUERY_PARAM_OBJECT_FORMAT_TYPE {dot, json, key};
- public static enum PROVIDED_IN_LEVEL {none, root, any, platform};
+ public static enum QUERY_PARAM_OBJECT_FORMAT_TYPE {dot, json, key}
+ public static enum PROVIDED_IN_LEVEL {none, root, any, platform}
private static final String DEFAULT_IMPORT_PREFIX = "./";
diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/TypeScriptClientCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/TypeScriptClientCodegen.java
index 9e6d5264c8..a49d14110a 100644
--- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/TypeScriptClientCodegen.java
+++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/TypeScriptClientCodegen.java
@@ -41,7 +41,7 @@ import static org.openapitools.codegen.utils.StringUtils.underscore;
public class TypeScriptClientCodegen extends DefaultCodegen implements CodegenConfig {
- private static final Logger LOGGER = LoggerFactory.getLogger(TypeScriptClientCodegen.class);
+ private final Logger LOGGER = LoggerFactory.getLogger(TypeScriptClientCodegen.class);
private static final String X_DISCRIMINATOR_TYPE = "x-discriminator-value";
private static final String UNDEFINED_VALUE = "undefined";
diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/TypeScriptJqueryClientCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/TypeScriptJqueryClientCodegen.java
index 6e4e2fad7b..6b4999be10 100644
--- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/TypeScriptJqueryClientCodegen.java
+++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/TypeScriptJqueryClientCodegen.java
@@ -30,7 +30,7 @@ import org.slf4j.LoggerFactory;
import java.io.File;
public class TypeScriptJqueryClientCodegen extends AbstractTypeScriptClientCodegen {
- private static final Logger LOGGER = LoggerFactory.getLogger(TypeScriptJqueryClientCodegen.class);
+ private final Logger LOGGER = LoggerFactory.getLogger(TypeScriptJqueryClientCodegen.class);
public static final String NPM_REPOSITORY = "npmRepository";
public static final String JQUERY_ALREADY_IMPORTED = "jqueryAlreadyImported";
diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/TypeScriptNestjsClientCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/TypeScriptNestjsClientCodegen.java
index f8749f7269..be90439e85 100644
--- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/TypeScriptNestjsClientCodegen.java
+++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/TypeScriptNestjsClientCodegen.java
@@ -33,7 +33,7 @@ import static org.apache.commons.lang3.StringUtils.capitalize;
import static org.openapitools.codegen.utils.StringUtils.*;
public class TypeScriptNestjsClientCodegen extends AbstractTypeScriptClientCodegen {
- private static final Logger LOGGER = LoggerFactory.getLogger(TypeScriptNestjsClientCodegen.class);
+ private final Logger LOGGER = LoggerFactory.getLogger(TypeScriptNestjsClientCodegen.class);
private static String CLASS_NAME_SUFFIX_PATTERN = "^[a-zA-Z0-9]*$";
private static String FILE_NAME_SUFFIX_PATTERN = "^[a-zA-Z0-9.-]*$";
diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/TypeScriptNodeClientCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/TypeScriptNodeClientCodegen.java
index 0016d23595..ab719e8990 100644
--- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/TypeScriptNodeClientCodegen.java
+++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/TypeScriptNodeClientCodegen.java
@@ -33,7 +33,7 @@ import java.util.*;
import static org.openapitools.codegen.utils.StringUtils.camelize;
public class TypeScriptNodeClientCodegen extends AbstractTypeScriptClientCodegen {
- private static final Logger LOGGER = LoggerFactory.getLogger(TypeScriptNodeClientCodegen.class);
+ private final Logger LOGGER = LoggerFactory.getLogger(TypeScriptNodeClientCodegen.class);
public static final String NPM_REPOSITORY = "npmRepository";
private static final String DEFAULT_MODEL_FILENAME_DIRECTORY_PREFIX = "./";
diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/TypeScriptRxjsClientCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/TypeScriptRxjsClientCodegen.java
index 2561e1b76f..cb6e1659e1 100644
--- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/TypeScriptRxjsClientCodegen.java
+++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/TypeScriptRxjsClientCodegen.java
@@ -34,7 +34,7 @@ import java.util.*;
import static org.openapitools.codegen.utils.OnceLogger.once;
public class TypeScriptRxjsClientCodegen extends AbstractTypeScriptClientCodegen {
- private static final Logger LOGGER = LoggerFactory.getLogger(AbstractTypeScriptClientCodegen.class);
+ private final Logger LOGGER = LoggerFactory.getLogger(AbstractTypeScriptClientCodegen.class);
public static final String NPM_REPOSITORY = "npmRepository";
public static final String WITH_PROGRESS_SUBSCRIBER = "withProgressSubscriber";
diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/templating/HandlebarsEngineAdapter.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/templating/HandlebarsEngineAdapter.java
index e161d85f0c..54d27dc47a 100644
--- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/templating/HandlebarsEngineAdapter.java
+++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/templating/HandlebarsEngineAdapter.java
@@ -40,7 +40,7 @@ import java.util.Locale;
import java.util.Map;
public class HandlebarsEngineAdapter extends AbstractTemplatingEngineAdapter {
- static final Logger LOGGER = LoggerFactory.getLogger(HandlebarsEngineAdapter.class);
+ final Logger LOGGER = LoggerFactory.getLogger(HandlebarsEngineAdapter.class);
private final String[] extensions = new String[]{"handlebars", "hbs"};
// We use this as a simple lookup for valid file name extensions. This adapter will inspect .mustache (built-in) and infer the relevant handlebars filename
diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/templating/MustacheEngineAdapter.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/templating/MustacheEngineAdapter.java
index 5d17dbb2a7..12ae4345b9 100644
--- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/templating/MustacheEngineAdapter.java
+++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/templating/MustacheEngineAdapter.java
@@ -31,7 +31,7 @@ import java.util.Map;
public class MustacheEngineAdapter implements TemplatingEngineAdapter {
- private static final Logger LOGGER = LoggerFactory.getLogger(TemplatingEngineAdapter.class);
+ private final Logger LOGGER = LoggerFactory.getLogger(TemplatingEngineAdapter.class);
/**
* Provides an identifier used to load the adapter. This could be a name, uuid, or any other string.
diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/templating/mustache/OnChangeLambda.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/templating/mustache/OnChangeLambda.java
index 11efbfae5b..b40840f366 100644
--- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/templating/mustache/OnChangeLambda.java
+++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/templating/mustache/OnChangeLambda.java
@@ -24,7 +24,7 @@ import com.samskivert.mustache.Template;
*
*/
public class OnChangeLambda implements Mustache.Lambda {
- private static final Logger LOGGER = LoggerFactory.getLogger(OnChangeLambda.class);
+ private final Logger LOGGER = LoggerFactory.getLogger(OnChangeLambda.class);
private String lastVal = null;
@@ -37,4 +37,4 @@ public class OnChangeLambda implements Mustache.Lambda {
lastVal = curVal;
}
}
-}
\ No newline at end of file
+}
diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/utils/JsonCache.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/utils/JsonCache.java
index df68513a95..8ea5c548c9 100644
--- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/utils/JsonCache.java
+++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/utils/JsonCache.java
@@ -122,8 +122,6 @@ public interface JsonCache {
OVERWRITE_EXISTING
}
- ;
-
/**
* If the cache is dirty, saves the object graph in JSON format to the specified file.
*
diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/utils/OneOfImplementorAdditionalData.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/utils/OneOfImplementorAdditionalData.java
index c3083a25b8..4b850eb6c6 100644
--- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/utils/OneOfImplementorAdditionalData.java
+++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/utils/OneOfImplementorAdditionalData.java
@@ -48,7 +48,7 @@ public class OneOfImplementorAdditionalData {
private List additionalInterfaces = new ArrayList();
private List additionalProps = new ArrayList();
private List> additionalImports = new ArrayList>();
- private static final Logger LOGGER = LoggerFactory.getLogger(OneOfImplementorAdditionalData.class);
+ private final Logger LOGGER = LoggerFactory.getLogger(OneOfImplementorAdditionalData.class);
public OneOfImplementorAdditionalData(String implementorName) {
this.implementorName = implementorName;
diff --git a/modules/openapi-generator/src/main/resources/Groovy/build.gradle.mustache b/modules/openapi-generator/src/main/resources/Groovy/build.gradle.mustache
index 5e753cd618..d7d5a175c9 100644
--- a/modules/openapi-generator/src/main/resources/Groovy/build.gradle.mustache
+++ b/modules/openapi-generator/src/main/resources/Groovy/build.gradle.mustache
@@ -29,11 +29,11 @@ repositories {
ext {
swagger_annotations_version = "1.5.22"
jackson_version = "2.9.10"
- jackson_databind_version = "2.9.10.4"
+ jackson_databind_version = "2.9.10.8"
}
dependencies {
- compile 'org.codehaus.groovy:groovy-all:2.5.7'
+ compile 'org.codehaus.groovy:groovy-all:2.5.14'
compile "io.swagger:swagger-annotations:$swagger_annotations_version"
compile "com.fasterxml.jackson.core:jackson-core:$jackson_version"
compile "com.fasterxml.jackson.core:jackson-annotations:$jackson_version"
diff --git a/modules/openapi-generator/src/main/resources/Java/build.gradle.mustache b/modules/openapi-generator/src/main/resources/Java/build.gradle.mustache
index a14862d3a8..95fc41cbf4 100644
--- a/modules/openapi-generator/src/main/resources/Java/build.gradle.mustache
+++ b/modules/openapi-generator/src/main/resources/Java/build.gradle.mustache
@@ -124,8 +124,8 @@ if(hasProperty('target') && target == 'android') {
ext {
swagger_annotations_version = "1.5.22"
- jackson_version = "2.10.3"
- jackson_databind_version = "2.10.4"
+ jackson_version = "2.12.1"
+ jackson_databind_version = "2.10.5.1"
{{#openApiNullable}}
jackson_databind_nullable_version = "0.2.1"
{{/openApiNullable}}
diff --git a/modules/openapi-generator/src/main/resources/Java/libraries/feign/api.mustache b/modules/openapi-generator/src/main/resources/Java/libraries/feign/api.mustache
index f6319c5da5..df70b71273 100644
--- a/modules/openapi-generator/src/main/resources/Java/libraries/feign/api.mustache
+++ b/modules/openapi-generator/src/main/resources/Java/libraries/feign/api.mustache
@@ -42,7 +42,7 @@ public interface {{classname}} extends ApiClient.Api {
"{{baseName}}: {{=<% %>=}}{<%paramName%>}<%={{ }}=%>"{{^-last}},
{{/-last}}{{/headerParams}}
})
- {{#returnType}}{{{returnType}}} {{/returnType}}{{^returnType}}void {{/returnType}}{{nickname}}({{#allParams}}{{^isBodyParam}}{{^legacyDates}}@Param("{{paramName}}") {{/legacyDates}}{{#legacyDates}}@Param(value="{{baseName}}", expander=ParamExpander.class) {{/legacyDates}}{{/isBodyParam}}{{{dataType}}} {{paramName}}{{^-last}}, {{/-last}}{{/allParams}});
+ {{#returnType}}{{{returnType}}} {{/returnType}}{{^returnType}}void {{/returnType}}{{nickname}}({{#allParams}}{{^isBodyParam}}{{^legacyDates}}@Param("{{paramName}}") {{/legacyDates}}{{#legacyDates}}@Param(value="{{paramName}}", expander=ParamExpander.class) {{/legacyDates}}{{/isBodyParam}}{{{dataType}}} {{paramName}}{{^-last}}, {{/-last}}{{/allParams}});
{{#hasQueryParams}}
/**
@@ -80,7 +80,7 @@ public interface {{classname}} extends ApiClient.Api {
"{{baseName}}: {{=<% %>=}}{<%paramName%>}<%={{ }}=%>"{{^-last}},
{{/-last}}{{/headerParams}}
})
- {{#returnType}}{{{returnType}}} {{/returnType}}{{^returnType}}void {{/returnType}}{{nickname}}({{#allParams}}{{^isQueryParam}}{{^isBodyParam}}{{^legacyDates}}@Param("{{paramName}}") {{/legacyDates}}{{#legacyDates}}@Param(value="{{baseName}}", expander=ParamExpander.class) {{/legacyDates}}{{/isBodyParam}}{{{dataType}}} {{paramName}}, {{/isQueryParam}}{{/allParams}}@QueryMap(encoded=true) Map queryParams);
+ {{#returnType}}{{{returnType}}} {{/returnType}}{{^returnType}}void {{/returnType}}{{nickname}}({{#allParams}}{{^isQueryParam}}{{^isBodyParam}}{{^legacyDates}}@Param("{{paramName}}") {{/legacyDates}}{{#legacyDates}}@Param(value="{{paramName}}", expander=ParamExpander.class) {{/legacyDates}}{{/isBodyParam}}{{{dataType}}} {{paramName}}, {{/isQueryParam}}{{/allParams}}@QueryMap(encoded=true) Map queryParams);
/**
* A convenience class for generating query parameters for the
diff --git a/modules/openapi-generator/src/main/resources/Java/libraries/google-api-client/build.gradle.mustache b/modules/openapi-generator/src/main/resources/Java/libraries/google-api-client/build.gradle.mustache
index 14d93d588d..6be8600c7d 100644
--- a/modules/openapi-generator/src/main/resources/Java/libraries/google-api-client/build.gradle.mustache
+++ b/modules/openapi-generator/src/main/resources/Java/libraries/google-api-client/build.gradle.mustache
@@ -108,8 +108,8 @@ if(hasProperty('target') && target == 'android') {
ext {
swagger_annotations_version = "1.5.22"
- jackson_version = "2.10.1"
- jackson_databind_version = "2.10.4"
+ jackson_version = "2.12.1"
+ jackson_databind_version = "2.10.5.1"
{{#openApiNullable}}
jackson_databind_nullable_version = "0.2.1"
{{/openApiNullable}}
diff --git a/modules/openapi-generator/src/main/resources/Java/libraries/google-api-client/build.sbt.mustache b/modules/openapi-generator/src/main/resources/Java/libraries/google-api-client/build.sbt.mustache
index f22448cb04..be30ae48ca 100644
--- a/modules/openapi-generator/src/main/resources/Java/libraries/google-api-client/build.sbt.mustache
+++ b/modules/openapi-generator/src/main/resources/Java/libraries/google-api-client/build.sbt.mustache
@@ -12,9 +12,9 @@ lazy val root = (project in file(".")).
"io.swagger" % "swagger-annotations" % "1.5.22",
"com.google.api-client" % "google-api-client" % "1.23.0",
"org.glassfish.jersey.core" % "jersey-common" % "2.25.1",
- "com.fasterxml.jackson.core" % "jackson-core" % "2.10.1" % "compile",
+ "com.fasterxml.jackson.core" % "jackson-core" % "2.12.1" % "compile",
"com.fasterxml.jackson.core" % "jackson-annotations" % "2.10.1" % "compile",
- "com.fasterxml.jackson.core" % "jackson-databind" % "2.10.4" % "compile",
+ "com.fasterxml.jackson.core" % "jackson-databind" % "2.10.5.1" % "compile",
{{#withXml}}
"com.fasterxml.jackson.dataformat" % "jackson-dataformat-xml" % "2.9.10" % "compile",
{{/withXml}}
diff --git a/modules/openapi-generator/src/main/resources/Java/libraries/google-api-client/pom.mustache b/modules/openapi-generator/src/main/resources/Java/libraries/google-api-client/pom.mustache
index 3a4b62e203..fdcb6953fa 100644
--- a/modules/openapi-generator/src/main/resources/Java/libraries/google-api-client/pom.mustache
+++ b/modules/openapi-generator/src/main/resources/Java/libraries/google-api-client/pom.mustache
@@ -317,7 +317,7 @@
1.5.22
1.30.2
2.25.1
- 2.10.4
+ 2.12.1
2.10.4
{{#openApiNullable}}
0.2.1
diff --git a/modules/openapi-generator/src/main/resources/Java/libraries/jersey2/ApiClient.mustache b/modules/openapi-generator/src/main/resources/Java/libraries/jersey2/ApiClient.mustache
index 294949c6c7..d12dec1bbd 100644
--- a/modules/openapi-generator/src/main/resources/Java/libraries/jersey2/ApiClient.mustache
+++ b/modules/openapi-generator/src/main/resources/Java/libraries/jersey2/ApiClient.mustache
@@ -35,6 +35,7 @@ import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.nio.file.Files;
+import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import org.glassfish.jersey.logging.LoggingFeature;
import java.util.logging.Level;
@@ -1027,15 +1028,15 @@ public class ApiClient{{#jsr310}} extends JavaTimeFormatter{{/jsr310}} {
prefix = filename.substring(0, pos) + "-";
suffix = filename.substring(pos);
}
- // File.createTempFile requires the prefix to be at least three characters long
+ // Files.createTempFile requires the prefix to be at least three characters long
if (prefix.length() < 3)
prefix = "download-";
}
if (tempFolderPath == null)
- return File.createTempFile(prefix, suffix);
+ return Files.createTempFile(prefix, suffix).toFile();
else
- return File.createTempFile(prefix, suffix, new File(tempFolderPath));
+ return Files.createTempFile(Paths.get(tempFolderPath), prefix, suffix).toFile();
}
/**
diff --git a/modules/openapi-generator/src/main/resources/Java/libraries/jersey2/build.gradle.mustache b/modules/openapi-generator/src/main/resources/Java/libraries/jersey2/build.gradle.mustache
index a15919fb9b..378de9fb1e 100644
--- a/modules/openapi-generator/src/main/resources/Java/libraries/jersey2/build.gradle.mustache
+++ b/modules/openapi-generator/src/main/resources/Java/libraries/jersey2/build.gradle.mustache
@@ -107,8 +107,8 @@ if(hasProperty('target') && target == 'android') {
ext {
swagger_annotations_version = "1.5.22"
- jackson_version = "2.10.3"
- jackson_databind_version = "2.10.4"
+ jackson_version = "2.10.5"
+ jackson_databind_version = "2.10.5.1"
{{#openApiNullable}}
jackson_databind_nullable_version = "0.2.1"
{{/openApiNullable}}
diff --git a/modules/openapi-generator/src/main/resources/Java/libraries/jersey2/build.sbt.mustache b/modules/openapi-generator/src/main/resources/Java/libraries/jersey2/build.sbt.mustache
index 52f17959a6..9823c3c657 100644
--- a/modules/openapi-generator/src/main/resources/Java/libraries/jersey2/build.sbt.mustache
+++ b/modules/openapi-generator/src/main/resources/Java/libraries/jersey2/build.sbt.mustache
@@ -15,9 +15,9 @@ lazy val root = (project in file(".")).
"org.glassfish.jersey.media" % "jersey-media-multipart" % "2.27",
"org.glassfish.jersey.media" % "jersey-media-json-jackson" % "2.27",
"org.glassfish.jersey.connectors" % "jersey-apache-connector" % "2.27",
- "com.fasterxml.jackson.core" % "jackson-core" % "2.10.4" % "compile",
- "com.fasterxml.jackson.core" % "jackson-annotations" % "2.10.4" % "compile",
- "com.fasterxml.jackson.core" % "jackson-databind" % "2.10.4" % "compile",
+ "com.fasterxml.jackson.core" % "jackson-core" % "2.10.5" % "compile",
+ "com.fasterxml.jackson.core" % "jackson-annotations" % "2.10.5.1" % "compile",
+ "com.fasterxml.jackson.core" % "jackson-databind" % "2.10.5.1" % "compile",
{{#joda}}
"com.fasterxml.jackson.datatype" % "jackson-datatype-joda" % "2.9.10" % "compile",
{{/joda}}
diff --git a/modules/openapi-generator/src/main/resources/Java/libraries/jersey2/pom.mustache b/modules/openapi-generator/src/main/resources/Java/libraries/jersey2/pom.mustache
index e7765a50d1..f36f0cd881 100644
--- a/modules/openapi-generator/src/main/resources/Java/libraries/jersey2/pom.mustache
+++ b/modules/openapi-generator/src/main/resources/Java/libraries/jersey2/pom.mustache
@@ -373,8 +373,8 @@
UTF-8
1.6.1
2.30.1
- 2.10.4
- 2.10.4
+ 2.10.5
+ 2.10.5.1
0.2.1
{{#threetenbp}}
2.9.10
diff --git a/modules/openapi-generator/src/main/resources/Java/libraries/native/ApiClient.mustache b/modules/openapi-generator/src/main/resources/Java/libraries/native/ApiClient.mustache
index abdea5d8f2..4c915fb3f3 100644
--- a/modules/openapi-generator/src/main/resources/Java/libraries/native/ApiClient.mustache
+++ b/modules/openapi-generator/src/main/resources/Java/libraries/native/ApiClient.mustache
@@ -157,8 +157,28 @@ public class ApiClient {
* Ctor.
*/
public ApiClient() {
- builder = HttpClient.newBuilder();
- mapper = new ObjectMapper();
+ this.builder = createDefaultHttpClientBuilder();
+ this.mapper = createDefaultObjectMapper();
+ updateBaseUri(getDefaultBaseUri());
+ interceptor = null;
+ readTimeout = null;
+ responseInterceptor = null;
+ }
+
+ /**
+ * Ctor.
+ */
+ public ApiClient(HttpClient.Builder builder, ObjectMapper mapper, String baseUri) {
+ this.builder = builder;
+ this.mapper = mapper;
+ updateBaseUri(baseUri);
+ interceptor = null;
+ readTimeout = null;
+ responseInterceptor = null;
+ }
+
+ protected ObjectMapper createDefaultObjectMapper() {
+ ObjectMapper mapper = new ObjectMapper();
mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
mapper.configure(DeserializationFeature.FAIL_ON_INVALID_SUBTYPE, false);
@@ -168,17 +188,25 @@ public class ApiClient {
mapper.disable(DeserializationFeature.ADJUST_DATES_TO_CONTEXT_TIME_ZONE);
mapper.registerModule(new JavaTimeModule());
{{#openApiNullable}}
- JsonNullableModule jnm = new JsonNullableModule();
- mapper.registerModule(jnm);
+ mapper.registerModule(new JsonNullableModule());
{{/openApiNullable}}
- URI baseURI = URI.create("{{{basePath}}}");
- scheme = baseURI.getScheme();
- host = baseURI.getHost();
- port = baseURI.getPort();
- basePath = baseURI.getRawPath();
- interceptor = null;
- readTimeout = null;
- responseInterceptor = null;
+ return mapper;
+ }
+
+ protected String getDefaultBaseUri() {
+ return "{{{basePath}}}";
+ }
+
+ protected HttpClient.Builder createDefaultHttpClientBuilder() {
+ return HttpClient.newBuilder();
+ }
+
+ public void updateBaseUri(String baseUri) {
+ URI uri = URI.create(baseUri);
+ scheme = uri.getScheme();
+ host = uri.getHost();
+ port = uri.getPort();
+ basePath = uri.getRawPath();
}
/**
diff --git a/modules/openapi-generator/src/main/resources/Java/libraries/native/api.mustache b/modules/openapi-generator/src/main/resources/Java/libraries/native/api.mustache
index b974f790ee..2adef3a6b0 100644
--- a/modules/openapi-generator/src/main/resources/Java/libraries/native/api.mustache
+++ b/modules/openapi-generator/src/main/resources/Java/libraries/native/api.mustache
@@ -283,7 +283,16 @@ public class {{classname}} {
localVarQueryParams.addAll(ApiClient.parameterToPairs("{{{collectionFormat}}}", "{{baseName}}", {{paramName}}));
{{/collectionFormat}}
{{^collectionFormat}}
+ {{#isDeepObject}}
+ if ({{paramName}} != null) {
+ {{#items.vars}}
+ localVarQueryParams.addAll(ApiClient.parameterToPairs("{{baseName}}", {{paramName}}.{{getter}}()));
+ {{/items.vars}}
+ }
+ {{/isDeepObject}}
+ {{^isDeepObject}}
localVarQueryParams.addAll(ApiClient.parameterToPairs("{{baseName}}", {{paramName}}));
+ {{/isDeepObject}}
{{/collectionFormat}}
{{/queryParams}}
diff --git a/modules/openapi-generator/src/main/resources/Java/libraries/native/model.mustache b/modules/openapi-generator/src/main/resources/Java/libraries/native/model.mustache
index 18ee121178..db4fbfd9fb 100644
--- a/modules/openapi-generator/src/main/resources/Java/libraries/native/model.mustache
+++ b/modules/openapi-generator/src/main/resources/Java/libraries/native/model.mustache
@@ -46,7 +46,6 @@ import javax.validation.Valid;
{{#performBeanValidation}}
import org.hibernate.validator.constraints.*;
{{/performBeanValidation}}
-import {{invokerPackage}}.JSON;
{{#models}}
{{#model}}
diff --git a/modules/openapi-generator/src/main/resources/Java/libraries/native/pojo.mustache b/modules/openapi-generator/src/main/resources/Java/libraries/native/pojo.mustache
index e7053dcc39..b2a919dea3 100644
--- a/modules/openapi-generator/src/main/resources/Java/libraries/native/pojo.mustache
+++ b/modules/openapi-generator/src/main/resources/Java/libraries/native/pojo.mustache
@@ -1,3 +1,6 @@
+{{#discriminator}}
+import {{invokerPackage}}.JSON;
+{{/discriminator}}
/**
* {{#description}}{{.}}{{/description}}{{^description}}{{classname}}{{/description}}
*/{{#description}}
diff --git a/modules/openapi-generator/src/main/resources/Java/libraries/okhttp-gson/ApiClient.mustache b/modules/openapi-generator/src/main/resources/Java/libraries/okhttp-gson/ApiClient.mustache
index f12320b3e4..e3eceebf93 100644
--- a/modules/openapi-generator/src/main/resources/Java/libraries/okhttp-gson/ApiClient.mustache
+++ b/modules/openapi-generator/src/main/resources/Java/libraries/okhttp-gson/ApiClient.mustache
@@ -41,6 +41,8 @@ import java.lang.reflect.Type;
import java.net.URI;
import java.net.URLConnection;
import java.net.URLEncoder;
+import java.nio.file.Files;
+import java.nio.file.Paths;
import java.security.GeneralSecurityException;
import java.security.KeyStore;
import java.security.SecureRandom;
@@ -578,7 +580,7 @@ public class ApiClient {
* with file response. The default value is null, i.e. using
* the system's default tempopary folder.
*
- * @see createTempFile
+ * @see createTempFile
* @return Temporary folder path
*/
public String getTempFolderPath() {
@@ -1077,15 +1079,15 @@ public class ApiClient {
prefix = filename.substring(0, pos) + "-";
suffix = filename.substring(pos);
}
- // File.createTempFile requires the prefix to be at least three characters long
+ // Files.createTempFile requires the prefix to be at least three characters long
if (prefix.length() < 3)
prefix = "download-";
}
if (tempFolderPath == null)
- return File.createTempFile(prefix, suffix);
+ return Files.createTempFile(prefix, suffix).toFile();
else
- return File.createTempFile(prefix, suffix, new File(tempFolderPath));
+ return Files.createTempFile(Paths.get(tempFolderPath), prefix, suffix).toFile();
}
/**
diff --git a/modules/openapi-generator/src/main/resources/Java/libraries/resteasy/ApiClient.mustache b/modules/openapi-generator/src/main/resources/Java/libraries/resteasy/ApiClient.mustache
index f361ff551c..775e0efea4 100644
--- a/modules/openapi-generator/src/main/resources/Java/libraries/resteasy/ApiClient.mustache
+++ b/modules/openapi-generator/src/main/resources/Java/libraries/resteasy/ApiClient.mustache
@@ -8,6 +8,7 @@ import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.nio.file.Files;
+import java.nio.file.Paths;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
@@ -278,7 +279,7 @@ public class ApiClient{{#jsr310}} extends JavaTimeFormatter{{/jsr310}} {
* the system's default tempopary folder.
*
* @return the temporary folder path
- * @see
+ * @see createTempFile
*/
public String getTempFolderPath() {
return tempFolderPath;
@@ -596,15 +597,15 @@ public class ApiClient{{#jsr310}} extends JavaTimeFormatter{{/jsr310}} {
prefix = filename.substring(0, pos) + "-";
suffix = filename.substring(pos);
}
- // File.createTempFile requires the prefix to be at least three characters long
+ // Files.createTempFile requires the prefix to be at least three characters long
if (prefix.length() < 3)
prefix = "download-";
}
if (tempFolderPath == null)
- return File.createTempFile(prefix, suffix);
+ return Files.createTempFile(prefix, suffix).toFile();
else
- return File.createTempFile(prefix, suffix, new File(tempFolderPath));
+ return Files.createTempFile(Paths.get(tempFolderPath), prefix, suffix).toFile();
}
/**
diff --git a/modules/openapi-generator/src/main/resources/Java/libraries/resteasy/build.gradle.mustache b/modules/openapi-generator/src/main/resources/Java/libraries/resteasy/build.gradle.mustache
index 3823153acc..fe6c7b1f8d 100644
--- a/modules/openapi-generator/src/main/resources/Java/libraries/resteasy/build.gradle.mustache
+++ b/modules/openapi-generator/src/main/resources/Java/libraries/resteasy/build.gradle.mustache
@@ -107,8 +107,8 @@ if(hasProperty('target') && target == 'android') {
ext {
swagger_annotations_version = "1.5.22"
- jackson_version = "2.10.4"
- jackson_databind_version = "2.10.4"
+ jackson_version = "2.10.5"
+ jackson_databind_version = "2.10.5.1"
{{#openApiNullable}}
jackson_databind_nullable_version = "0.2.1"
{{/openApiNullable}}
diff --git a/modules/openapi-generator/src/main/resources/Java/libraries/resteasy/build.sbt.mustache b/modules/openapi-generator/src/main/resources/Java/libraries/resteasy/build.sbt.mustache
index 79600b7754..c2dfff284b 100644
--- a/modules/openapi-generator/src/main/resources/Java/libraries/resteasy/build.sbt.mustache
+++ b/modules/openapi-generator/src/main/resources/Java/libraries/resteasy/build.sbt.mustache
@@ -13,9 +13,9 @@ lazy val root = (project in file(".")).
"org.jboss.resteasy" % "resteasy-client" % "3.1.3.Final" % "compile",
"org.jboss.resteasy" % "resteasy-multipart-provider" % "3.1.3.Final" % "compile",
"org.jboss.resteasy" % "resteasy-jackson2-provider" % "3.1.3.Final" % "compile",
- "com.fasterxml.jackson.core" % "jackson-core" % "2.10.4" % "compile",
- "com.fasterxml.jackson.core" % "jackson-annotations" % "2.10.4" % "compile",
- "com.fasterxml.jackson.core" % "jackson-databind" % "2.10.4" % "compile",
+ "com.fasterxml.jackson.core" % "jackson-core" % "2.10.5" % "compile",
+ "com.fasterxml.jackson.core" % "jackson-annotations" % "2.10.5" % "compile",
+ "com.fasterxml.jackson.core" % "jackson-databind" % "2.10.5.1" % "compile",
"com.github.joschi.jackson" % "jackson-datatype-threetenbp" % "2.9.10" % "compile",
{{#java8}}
"com.fasterxml.jackson.datatype" % "jackson-datatype-jsr310" % "2.9.10" % "compile",
diff --git a/modules/openapi-generator/src/main/resources/Java/libraries/resteasy/pom.mustache b/modules/openapi-generator/src/main/resources/Java/libraries/resteasy/pom.mustache
index 82c5a03608..084f42df9b 100644
--- a/modules/openapi-generator/src/main/resources/Java/libraries/resteasy/pom.mustache
+++ b/modules/openapi-generator/src/main/resources/Java/libraries/resteasy/pom.mustache
@@ -285,8 +285,8 @@
UTF-8
1.5.22
3.1.3.Final
- 2.10.4
- 2.10.4
+ 2.10.5
+ 2.10.5.1
0.2.1
1.3.2
2.9.10
diff --git a/modules/openapi-generator/src/main/resources/Java/libraries/resttemplate/build.gradle.mustache b/modules/openapi-generator/src/main/resources/Java/libraries/resttemplate/build.gradle.mustache
index 11235a89bb..433d396baf 100644
--- a/modules/openapi-generator/src/main/resources/Java/libraries/resttemplate/build.gradle.mustache
+++ b/modules/openapi-generator/src/main/resources/Java/libraries/resttemplate/build.gradle.mustache
@@ -108,8 +108,8 @@ if(hasProperty('target') && target == 'android') {
ext {
swagger_annotations_version = "1.5.22"
- jackson_version = "2.10.4"
- jackson_databind_version = "2.10.4"
+ jackson_version = "2.10.5"
+ jackson_databind_version = "2.10.5.1"
{{#openApiNullable}}
jackson_databind_nullable_version = "0.2.1"
{{/openApiNullable}}
diff --git a/modules/openapi-generator/src/main/resources/Java/libraries/resttemplate/pom.mustache b/modules/openapi-generator/src/main/resources/Java/libraries/resttemplate/pom.mustache
index ca27309347..17dd7024ed 100644
--- a/modules/openapi-generator/src/main/resources/Java/libraries/resttemplate/pom.mustache
+++ b/modules/openapi-generator/src/main/resources/Java/libraries/resttemplate/pom.mustache
@@ -317,8 +317,8 @@
UTF-8
1.5.22
5.2.5.RELEASE
- 2.10.4
- 2.10.4
+ 2.10.5
+ 2.10.5.1
0.2.1
1.3.2
{{#joda}}
diff --git a/modules/openapi-generator/src/main/resources/Java/libraries/retrofit2/build.gradle.mustache b/modules/openapi-generator/src/main/resources/Java/libraries/retrofit2/build.gradle.mustache
index 2bb2fb3561..090eefa338 100644
--- a/modules/openapi-generator/src/main/resources/Java/libraries/retrofit2/build.gradle.mustache
+++ b/modules/openapi-generator/src/main/resources/Java/libraries/retrofit2/build.gradle.mustache
@@ -110,8 +110,8 @@ ext {
oltu_version = "1.0.1"
retrofit_version = "2.3.0"
{{#usePlayWS}}
- jackson_version = "2.10.4"
- jackson_databind_version = "2.10.4"
+ jackson_version = "2.10.5"
+ jackson_databind_version = "2.10.5.1"
{{#openApiNullable}}
jackson_databind_nullable_version = "0.2.1"
{{/openApiNullable}}
diff --git a/modules/openapi-generator/src/main/resources/Java/libraries/retrofit2/build.sbt.mustache b/modules/openapi-generator/src/main/resources/Java/libraries/retrofit2/build.sbt.mustache
index 8d386e34d8..a9301f736a 100644
--- a/modules/openapi-generator/src/main/resources/Java/libraries/retrofit2/build.sbt.mustache
+++ b/modules/openapi-generator/src/main/resources/Java/libraries/retrofit2/build.sbt.mustache
@@ -26,9 +26,9 @@ lazy val root = (project in file(".")).
"javax.validation" % "validation-api" % "1.1.0.Final" % "compile",
{{/play26}}
"com.squareup.retrofit2" % "converter-jackson" % "2.3.0" % "compile",
- "com.fasterxml.jackson.core" % "jackson-core" % "2.10.4" % "compile",
- "com.fasterxml.jackson.core" % "jackson-annotations" % "2.10.4" % "compile",
- "com.fasterxml.jackson.core" % "jackson-databind" % "2.10.4" % "compile",
+ "com.fasterxml.jackson.core" % "jackson-core" % "2.10.5" % "compile",
+ "com.fasterxml.jackson.core" % "jackson-annotations" % "2.10.5" % "compile",
+ "com.fasterxml.jackson.core" % "jackson-databind" % "2.10.5.1" % "compile",
{{/usePlayWS}}
{{#useRxJava}}
"com.squareup.retrofit2" % "adapter-rxjava" % "2.3.0" % "compile",
diff --git a/modules/openapi-generator/src/main/resources/Java/libraries/retrofit2/play26/ApiClient.mustache b/modules/openapi-generator/src/main/resources/Java/libraries/retrofit2/play26/ApiClient.mustache
index 55db072944..b752b433d0 100644
--- a/modules/openapi-generator/src/main/resources/Java/libraries/retrofit2/play26/ApiClient.mustache
+++ b/modules/openapi-generator/src/main/resources/Java/libraries/retrofit2/play26/ApiClient.mustache
@@ -5,6 +5,7 @@ import java.io.IOException;
import java.lang.annotation.Annotation;
import java.lang.reflect.Type;
import java.nio.file.Files;
+import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.*;
@@ -202,9 +203,9 @@ public class ApiClient {
@Override
public File convert(ResponseBody value) throws IOException {
- File file = File.createTempFile("retrofit-file", ".tmp");
- Files.write(Paths.get(file.getPath()), value.bytes());
- return file;
+ Path path = Files.createTempFile("retrofit-file", ".tmp");
+ Files.write(path, value.bytes());
+ return path.toFile();
}
};
}
diff --git a/modules/openapi-generator/src/main/resources/Java/libraries/retrofit2/pom.mustache b/modules/openapi-generator/src/main/resources/Java/libraries/retrofit2/pom.mustache
index 32d395bf02..b8b3d5dcb2 100644
--- a/modules/openapi-generator/src/main/resources/Java/libraries/retrofit2/pom.mustache
+++ b/modules/openapi-generator/src/main/resources/Java/libraries/retrofit2/pom.mustache
@@ -409,7 +409,7 @@
1.8.3
1.5.22
{{#usePlayWS}}
- 2.10.4
+ 2.12.1
{{#play24}}
2.4.11
{{/play24}}
diff --git a/modules/openapi-generator/src/main/resources/Java/libraries/vertx/build.gradle.mustache b/modules/openapi-generator/src/main/resources/Java/libraries/vertx/build.gradle.mustache
index cb2910c843..143a193621 100644
--- a/modules/openapi-generator/src/main/resources/Java/libraries/vertx/build.gradle.mustache
+++ b/modules/openapi-generator/src/main/resources/Java/libraries/vertx/build.gradle.mustache
@@ -28,8 +28,8 @@ task execute(type:JavaExec) {
ext {
swagger_annotations_version = "1.5.21"
- jackson_version = "2.10.4"
- jackson_databind_version = "2.10.4"
+ jackson_version = "2.10.5"
+ jackson_databind_version = "2.10.5.1"
vertx_version = "3.4.2"
junit_version = "4.13.1"
{{#openApiNullable}}
diff --git a/modules/openapi-generator/src/main/resources/Java/libraries/vertx/pom.mustache b/modules/openapi-generator/src/main/resources/Java/libraries/vertx/pom.mustache
index b4064662a9..cbd5d580b1 100644
--- a/modules/openapi-generator/src/main/resources/Java/libraries/vertx/pom.mustache
+++ b/modules/openapi-generator/src/main/resources/Java/libraries/vertx/pom.mustache
@@ -306,8 +306,8 @@
UTF-8
3.4.2
1.5.22
- 2.10.4
- 2.10.4
+ 2.10.5
+ 2.10.5.1
0.2.1
1.3.2
4.13.1
diff --git a/modules/openapi-generator/src/main/resources/Java/model.mustache b/modules/openapi-generator/src/main/resources/Java/model.mustache
index dec0b7dc8a..8fd078eb3d 100644
--- a/modules/openapi-generator/src/main/resources/Java/model.mustache
+++ b/modules/openapi-generator/src/main/resources/Java/model.mustache
@@ -23,6 +23,18 @@ import com.fasterxml.jackson.dataformat.xml.annotation.*;
{{#withXml}}
import javax.xml.bind.annotation.*;
{{/withXml}}
+{{#jsonb}}
+import java.lang.reflect.Type;
+import javax.json.bind.annotation.JsonbTypeDeserializer;
+import javax.json.bind.annotation.JsonbTypeSerializer;
+import javax.json.bind.serializer.DeserializationContext;
+import javax.json.bind.serializer.JsonbDeserializer;
+import javax.json.bind.serializer.JsonbSerializer;
+import javax.json.bind.serializer.SerializationContext;
+import javax.json.stream.JsonGenerator;
+import javax.json.stream.JsonParser;
+import javax.json.bind.annotation.JsonbProperty;
+{{/jsonb}}
{{#parcelableModel}}
import android.os.Parcelable;
import android.os.Parcel;
diff --git a/modules/openapi-generator/src/main/resources/Java/modelEnum.mustache b/modules/openapi-generator/src/main/resources/Java/modelEnum.mustache
index 9428bc70f9..10ad58e443 100644
--- a/modules/openapi-generator/src/main/resources/Java/modelEnum.mustache
+++ b/modules/openapi-generator/src/main/resources/Java/modelEnum.mustache
@@ -16,6 +16,10 @@ import com.google.gson.stream.JsonWriter;
{{#gson}}
@JsonAdapter({{#datatypeWithEnum}}{{{.}}}{{/datatypeWithEnum}}{{^datatypeWithEnum}}{{{classname}}}{{/datatypeWithEnum}}.Adapter.class)
{{/gson}}
+{{#jsonb}}
+@JsonbTypeSerializer({{datatypeWithEnum}}.Serializer.class)
+@JsonbTypeDeserializer({{datatypeWithEnum}}.Deserializer.class)
+{{/jsonb}}
public enum {{#datatypeWithEnum}}{{{.}}}{{/datatypeWithEnum}}{{^datatypeWithEnum}}{{{classname}}}{{/datatypeWithEnum}} {
{{#allowableValues}}{{#enumVars}}
{{#enumDescription}}
@@ -23,6 +27,9 @@ public enum {{#datatypeWithEnum}}{{{.}}}{{/datatypeWithEnum}}{{^datatypeWithEnum
* {{enumDescription}}
*/
{{/enumDescription}}
+ {{#withXml}}
+ @XmlEnumValue({{#isInteger}}"{{/isInteger}}{{#isDouble}}"{{/isDouble}}{{#isLong}}"{{/isLong}}{{#isFloat}}"{{/isFloat}}{{{value}}}{{#isInteger}}"{{/isInteger}}{{#isDouble}}"{{/isDouble}}{{#isLong}}"{{/isLong}}{{#isFloat}}"{{/isFloat}})
+ {{/withXml}}
{{{name}}}({{{value}}}){{^-last}},
{{/-last}}{{#-last}};{{/-last}}{{/enumVars}}{{/allowableValues}}
@@ -70,4 +77,24 @@ public enum {{#datatypeWithEnum}}{{{.}}}{{/datatypeWithEnum}}{{^datatypeWithEnum
}
}
{{/gson}}
+{{#jsonb}}
+ public static final class Deserializer implements JsonbDeserializer<{{datatypeWithEnum}}> {
+ @Override
+ public {{datatypeWithEnum}} deserialize(JsonParser parser, DeserializationContext ctx, Type rtType) {
+ for ({{#datatypeWithEnum}}{{{.}}}{{/datatypeWithEnum}}{{^datatypeWithEnum}}{{{classname}}}{{/datatypeWithEnum}} b : {{#datatypeWithEnum}}{{{.}}}{{/datatypeWithEnum}}{{^datatypeWithEnum}}{{{classname}}}{{/datatypeWithEnum}}.values()) {
+ if (String.valueOf(b.value).equals(parser.getString())) {
+ return b;
+ }
+ }
+ {{#useNullForUnknownEnumValue}}return null;{{/useNullForUnknownEnumValue}}{{^useNullForUnknownEnumValue}}throw new IllegalArgumentException("Unexpected value '" + parser.getString() + "'");{{/useNullForUnknownEnumValue}}
+ }
+ }
+
+ public static final class Serializer implements JsonbSerializer<{{datatypeWithEnum}}> {
+ @Override
+ public void serialize({{datatypeWithEnum}} obj, JsonGenerator generator, SerializationContext ctx) {
+ generator.write(obj.value);
+ }
+ }
+{{/jsonb}}
}
diff --git a/modules/openapi-generator/src/main/resources/Java/modelInnerEnum.mustache b/modules/openapi-generator/src/main/resources/Java/modelInnerEnum.mustache
index 101870341f..942be42b51 100644
--- a/modules/openapi-generator/src/main/resources/Java/modelInnerEnum.mustache
+++ b/modules/openapi-generator/src/main/resources/Java/modelInnerEnum.mustache
@@ -4,6 +4,14 @@
{{#gson}}
@JsonAdapter({{#datatypeWithEnum}}{{{.}}}{{/datatypeWithEnum}}{{^datatypeWithEnum}}{{classname}}{{/datatypeWithEnum}}.Adapter.class)
{{/gson}}
+{{#jsonb}}
+ @JsonbTypeSerializer({{datatypeWithEnum}}.Serializer.class)
+ @JsonbTypeDeserializer({{datatypeWithEnum}}.Deserializer.class)
+{{/jsonb}}
+{{#withXml}}
+ @XmlType(name="{{datatypeWithEnum}}")
+ @XmlEnum({{dataType}}.class)
+{{/withXml}}
public enum {{#datatypeWithEnum}}{{{.}}}{{/datatypeWithEnum}}{{^datatypeWithEnum}}{{classname}}{{/datatypeWithEnum}} {
{{#allowableValues}}
{{#enumVars}}
@@ -12,6 +20,9 @@
* {{enumDescription}}
*/
{{/enumDescription}}
+ {{#withXml}}
+ @XmlEnumValue({{#isInteger}}"{{/isInteger}}{{#isDouble}}"{{/isDouble}}{{#isLong}}"{{/isLong}}{{#isFloat}}"{{/isFloat}}{{{value}}}{{#isInteger}}"{{/isInteger}}{{#isDouble}}"{{/isDouble}}{{#isLong}}"{{/isLong}}{{#isFloat}}"{{/isFloat}})
+ {{/withXml}}
{{{name}}}({{{value}}}){{^-last}},
{{/-last}}{{#-last}};{{/-last}}
{{/enumVars}}
@@ -61,4 +72,24 @@
}
}
{{/gson}}
+{{#jsonb}}
+ public static final class Deserializer implements JsonbDeserializer<{{datatypeWithEnum}}> {
+ @Override
+ public {{datatypeWithEnum}} deserialize(JsonParser parser, DeserializationContext ctx, Type rtType) {
+ for ({{#datatypeWithEnum}}{{{.}}}{{/datatypeWithEnum}}{{^datatypeWithEnum}}{{{classname}}}{{/datatypeWithEnum}} b : {{#datatypeWithEnum}}{{{.}}}{{/datatypeWithEnum}}{{^datatypeWithEnum}}{{{classname}}}{{/datatypeWithEnum}}.values()) {
+ if (String.valueOf(b.value).equals(parser.getString())) {
+ return b;
+ }
+ }
+ {{#useNullForUnknownEnumValue}}return null;{{/useNullForUnknownEnumValue}}{{^useNullForUnknownEnumValue}}throw new IllegalArgumentException("Unexpected value '" + parser.getString() + "'");{{/useNullForUnknownEnumValue}}
+ }
+ }
+
+ public static final class Serializer implements JsonbSerializer<{{datatypeWithEnum}}> {
+ @Override
+ public void serialize({{datatypeWithEnum}} obj, JsonGenerator generator, SerializationContext ctx) {
+ generator.write(obj.value);
+ }
+ }
+{{/jsonb}}
}
diff --git a/modules/openapi-generator/src/main/resources/Java/pojo.mustache b/modules/openapi-generator/src/main/resources/Java/pojo.mustache
index 81eeb24af0..30454970ac 100644
--- a/modules/openapi-generator/src/main/resources/Java/pojo.mustache
+++ b/modules/openapi-generator/src/main/resources/Java/pojo.mustache
@@ -179,6 +179,9 @@ public class {{classname}} {{#parent}}extends {{{parent}}} {{/parent}}{{#vendorE
{{^required}}
@javax.annotation.Nullable
{{/required}}
+{{#jsonb}}
+ @JsonbProperty("{{baseName}}")
+{{/jsonb}}
{{#useBeanValidation}}{{>beanValidation}}{{/useBeanValidation}} @ApiModelProperty({{#example}}example = "{{{example}}}", {{/example}}{{#required}}required = {{required}}, {{/required}}value = "{{{description}}}")
{{#vendorExtensions.x-extra-annotation}}
{{{vendorExtensions.x-extra-annotation}}}
@@ -276,7 +279,7 @@ public class {{classname}} {{#parent}}extends {{{parent}}} {{/parent}}{{#vendorE
* Convert the given object to string with each line indented by 4 spaces
* (except the first line).
*/
- private String toIndentedString(Object o) {
+ private{{#jsonb}} static{{/jsonb}} String toIndentedString(Object o) {
if (o == null) {
return "null";
}
diff --git a/modules/openapi-generator/src/main/resources/Java/pom.mustache b/modules/openapi-generator/src/main/resources/Java/pom.mustache
index efe442bef7..20b602c542 100644
--- a/modules/openapi-generator/src/main/resources/Java/pom.mustache
+++ b/modules/openapi-generator/src/main/resources/Java/pom.mustache
@@ -362,7 +362,7 @@
UTF-8
1.5.21
1.19.4
- 2.10.3
+ 2.12.1
{{#threetenbp}}
2.9.10
{{/threetenbp}}
diff --git a/modules/openapi-generator/src/main/resources/JavaVertXWebServer/apiHandler.mustache b/modules/openapi-generator/src/main/resources/JavaVertXWebServer/apiHandler.mustache
index e9a6bbf066..807f60e5b4 100644
--- a/modules/openapi-generator/src/main/resources/JavaVertXWebServer/apiHandler.mustache
+++ b/modules/openapi-generator/src/main/resources/JavaVertXWebServer/apiHandler.mustache
@@ -21,10 +21,15 @@ public class {{classname}}Handler {
private static final Logger logger = LoggerFactory.getLogger({{classname}}Handler.class);
- private final {{classname}} apiImpl;
+ private final {{classname}} api;
+ public {{classname}}Handler({{classname}} api) {
+ this.api = api;
+ }
+
+ @Deprecated
public {{classname}}Handler() {
- this.apiImpl = new {{classname}}Impl();
+ this(new {{classname}}Impl());
}
public void mount(RouterBuilder builder) {
@@ -48,7 +53,7 @@ public class {{classname}}Handler {
logger.debug("Parameter {{paramName}} is {}", {{paramName}});
{{/allParams}}
- apiImpl.{{operationId}}({{#allParams}}{{paramName}}{{^-last}}, {{/-last}}{{/allParams}})
+ api.{{operationId}}({{#allParams}}{{paramName}}{{^-last}}, {{/-last}}{{/allParams}})
.onSuccess(apiResponse -> {
routingContext.response().setStatusCode(apiResponse.getStatusCode());
if (apiResponse.hasData()) {
diff --git a/modules/openapi-generator/src/main/resources/JavaVertXWebServer/supportFiles/HttpServerVerticle.mustache b/modules/openapi-generator/src/main/resources/JavaVertXWebServer/supportFiles/HttpServerVerticle.mustache
index 03001005bc..90d2dd3edd 100644
--- a/modules/openapi-generator/src/main/resources/JavaVertXWebServer/supportFiles/HttpServerVerticle.mustache
+++ b/modules/openapi-generator/src/main/resources/JavaVertXWebServer/supportFiles/HttpServerVerticle.mustache
@@ -10,7 +10,8 @@ import io.vertx.ext.web.openapi.RouterBuilderOptions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
{{#apiInfo}}{{#apis}}
-import {{apiPackage}}.{{classname}}Handler;{{/apis}}{{/apiInfo}}
+import {{apiPackage}}.{{classname}}Handler;
+import {{apiPackage}}.{{classname}}Impl;{{/apis}}{{/apiInfo}}
public class HttpServerVerticle extends AbstractVerticle {
@@ -18,7 +19,7 @@ public class HttpServerVerticle extends AbstractVerticle {
private static final String specFile = "src/main/resources/openapi.yaml";
{{#apiInfo}}{{#apis}}
- private final {{classname}}Handler {{classVarName}}Handler = new {{classname}}Handler();{{/apis}}{{/apiInfo}}
+ private final {{classname}}Handler {{classVarName}}Handler = new {{classname}}Handler(new {{classname}}Impl());{{/apis}}{{/apiInfo}}
@Override
public void start(Promise startPromise) {
diff --git a/modules/openapi-generator/src/main/resources/aspnetcore/2.0/formParam.mustache b/modules/openapi-generator/src/main/resources/aspnetcore/2.0/formParam.mustache
index 2d42dc2916..80eb9f630b 100644
--- a/modules/openapi-generator/src/main/resources/aspnetcore/2.0/formParam.mustache
+++ b/modules/openapi-generator/src/main/resources/aspnetcore/2.0/formParam.mustache
@@ -1 +1 @@
-{{#isFormParam}}[FromForm]{{#required}}[Required()]{{/required}}{{#pattern}}[RegularExpression("{{{pattern}}}")]{{/pattern}}{{#minLength}}{{#maxLength}}[StringLength({{maxLength}}, MinimumLength={{minLength}}){{/maxLength}}{{/minLength}}{{#minLength}}{{^maxLength}} [MinLength({{minLength}})]{{/maxLength}}{{/minLength}}{{^minLength}}{{#maxLength}} [MaxLength({{maxLength}})]{{/maxLength}}{{/minLength}}{{#minimum}}{{#maximum}}[Range({{minimum}}, {{maximum}})]{{/maximum}}{{/minimum}}{{&dataType}} {{paramName}}{{/isFormParam}}
\ No newline at end of file
+{{#isFormParam}}[FromForm (Name = "{{baseName}}")]{{#required}}[Required()]{{/required}}{{#pattern}}[RegularExpression("{{{pattern}}}")]{{/pattern}}{{#minLength}}{{#maxLength}}[StringLength({{maxLength}}, MinimumLength={{minLength}}){{/maxLength}}{{/minLength}}{{#minLength}}{{^maxLength}} [MinLength({{minLength}})]{{/maxLength}}{{/minLength}}{{^minLength}}{{#maxLength}} [MaxLength({{maxLength}})]{{/maxLength}}{{/minLength}}{{#minimum}}{{#maximum}}[Range({{minimum}}, {{maximum}})]{{/maximum}}{{/minimum}}{{&dataType}} {{paramName}}{{/isFormParam}}
\ No newline at end of file
diff --git a/modules/openapi-generator/src/main/resources/aspnetcore/2.0/pathParam.mustache b/modules/openapi-generator/src/main/resources/aspnetcore/2.0/pathParam.mustache
index 70303432d4..e2a3015053 100644
--- a/modules/openapi-generator/src/main/resources/aspnetcore/2.0/pathParam.mustache
+++ b/modules/openapi-generator/src/main/resources/aspnetcore/2.0/pathParam.mustache
@@ -1 +1 @@
-{{#isPathParam}}[FromRoute]{{#required}}[Required]{{/required}}{{#pattern}}[RegularExpression("{{{pattern}}}")]{{/pattern}}{{#minLength}}{{#maxLength}}[StringLength({{maxLength}}, MinimumLength={{minLength}}){{/maxLength}}{{/minLength}}{{#minLength}}{{^maxLength}} [MinLength({{minLength}})]{{/maxLength}}{{/minLength}}{{^minLength}}{{#maxLength}} [MaxLength({{maxLength}})]{{/maxLength}}{{/minLength}}{{#minimum}}{{#maximum}}[Range({{minimum}}, {{maximum}})]{{/maximum}}{{/minimum}}{{&dataType}} {{paramName}}{{/isPathParam}}
\ No newline at end of file
+{{#isPathParam}}[FromRoute (Name = "{{baseName}}")]{{#required}}[Required]{{/required}}{{#pattern}}[RegularExpression("{{{pattern}}}")]{{/pattern}}{{#minLength}}{{#maxLength}}[StringLength({{maxLength}}, MinimumLength={{minLength}}){{/maxLength}}{{/minLength}}{{#minLength}}{{^maxLength}} [MinLength({{minLength}})]{{/maxLength}}{{/minLength}}{{^minLength}}{{#maxLength}} [MaxLength({{maxLength}})]{{/maxLength}}{{/minLength}}{{#minimum}}{{#maximum}}[Range({{minimum}}, {{maximum}})]{{/maximum}}{{/minimum}}{{&dataType}} {{paramName}}{{/isPathParam}}
\ No newline at end of file
diff --git a/modules/openapi-generator/src/main/resources/aspnetcore/2.0/queryParam.mustache b/modules/openapi-generator/src/main/resources/aspnetcore/2.0/queryParam.mustache
index e9fa09b005..cafc0ccf86 100644
--- a/modules/openapi-generator/src/main/resources/aspnetcore/2.0/queryParam.mustache
+++ b/modules/openapi-generator/src/main/resources/aspnetcore/2.0/queryParam.mustache
@@ -1 +1 @@
-{{#isQueryParam}}[FromQuery]{{#required}}[Required()]{{/required}}{{#pattern}}[RegularExpression("{{{pattern}}}")]{{/pattern}}{{#minLength}}{{#maxLength}}[StringLength({{maxLength}}, MinimumLength={{minLength}}){{/maxLength}}{{/minLength}}{{#minLength}}{{^maxLength}} [MinLength({{minLength}})]{{/maxLength}}{{/minLength}}{{^minLength}}{{#maxLength}} [MaxLength({{maxLength}})]{{/maxLength}}{{/minLength}}{{#minimum}}{{#maximum}}[Range({{minimum}}, {{maximum}})]{{/maximum}}{{/minimum}}{{&dataType}} {{paramName}}{{/isQueryParam}}
\ No newline at end of file
+{{#isQueryParam}}[FromQuery (Name = "{{baseName}}")]{{#required}}[Required()]{{/required}}{{#pattern}}[RegularExpression("{{{pattern}}}")]{{/pattern}}{{#minLength}}{{#maxLength}}[StringLength({{maxLength}}, MinimumLength={{minLength}}){{/maxLength}}{{/minLength}}{{#minLength}}{{^maxLength}} [MinLength({{minLength}})]{{/maxLength}}{{/minLength}}{{^minLength}}{{#maxLength}} [MaxLength({{maxLength}})]{{/maxLength}}{{/minLength}}{{#minimum}}{{#maximum}}[Range({{minimum}}, {{maximum}})]{{/maximum}}{{/minimum}}{{&dataType}} {{paramName}}{{/isQueryParam}}
\ No newline at end of file
diff --git a/modules/openapi-generator/src/main/resources/aspnetcore/2.1/Startup.mustache b/modules/openapi-generator/src/main/resources/aspnetcore/2.1/Startup.mustache
index e3701048a2..d2f6997dd7 100644
--- a/modules/openapi-generator/src/main/resources/aspnetcore/2.1/Startup.mustache
+++ b/modules/openapi-generator/src/main/resources/aspnetcore/2.1/Startup.mustache
@@ -123,12 +123,14 @@ namespace {{packageName}}
//TODO: Or alternatively use the original Swagger contract that's included in the static files
// c.SwaggerEndpoint("/openapi-original.json", "{{#appName}}{{{appName}}}{{/appName}}{{^appName}}{{packageName}}{{/appName}} Original");
- }){{/useSwashbuckle}};{{^useDefaultRouting}}
+ }){{/useSwashbuckle}};
+ {{^useDefaultRouting}}
app.UseRouting();
app.UseEndpoints(endpoints =>
- {
- endpoints.MapControllers();
- });{{/useDefaultRouting}}
+ {
+ endpoints.MapControllers();
+ });
+ {{/useDefaultRouting}}
if (env.IsDevelopment())
{
diff --git a/modules/openapi-generator/src/main/resources/aspnetcore/2.1/controller.mustache b/modules/openapi-generator/src/main/resources/aspnetcore/2.1/controller.mustache
index a936378d65..47e36aa25b 100644
--- a/modules/openapi-generator/src/main/resources/aspnetcore/2.1/controller.mustache
+++ b/modules/openapi-generator/src/main/resources/aspnetcore/2.1/controller.mustache
@@ -49,7 +49,7 @@ namespace {{apiPackage}}
public {{operationModifier}} {{#operationResultTask}}{{#operationIsAsync}}async {{/operationIsAsync}}Task<{{/operationResultTask}}IActionResult{{#operationResultTask}}>{{/operationResultTask}} {{operationId}}({{#allParams}}{{>pathParam}}{{>queryParam}}{{>bodyParam}}{{>formParam}}{{>headerParam}}{{^-last}}{{^isCookieParam}}, {{/isCookieParam}}{{/-last}}{{/allParams}}){{^generateBody}};{{/generateBody}}
{{#generateBody}}
{
- {{#cookieParams}}
+ {{#cookieParams}}
var {{paramName}} = Request.Cookies["{{paramName}}"];
{{/cookieParams}}
diff --git a/modules/openapi-generator/src/main/resources/aspnetcore/2.1/formParam.mustache b/modules/openapi-generator/src/main/resources/aspnetcore/2.1/formParam.mustache
index fbd2d815d5..e71c9619d8 100644
--- a/modules/openapi-generator/src/main/resources/aspnetcore/2.1/formParam.mustache
+++ b/modules/openapi-generator/src/main/resources/aspnetcore/2.1/formParam.mustache
@@ -1 +1 @@
-{{#isFormParam}}[FromForm]{{#required}}[Required()]{{/required}}{{#pattern}}[RegularExpression("{{{pattern}}}")]{{/pattern}}{{#minLength}}{{#maxLength}}[StringLength({{maxLength}}, MinimumLength={{minLength}})]{{/maxLength}}{{/minLength}}{{#minLength}}{{^maxLength}} [MinLength({{minLength}})]{{/maxLength}}{{/minLength}}{{^minLength}}{{#maxLength}} [MaxLength({{maxLength}})]{{/maxLength}}{{/minLength}}{{#minimum}}{{#maximum}}[Range({{minimum}}, {{maximum}})]{{/maximum}}{{/minimum}}{{&dataType}} {{paramName}}{{/isFormParam}}
\ No newline at end of file
+{{#isFormParam}}[FromForm (Name = "{{baseName}}")]{{#required}}[Required()]{{/required}}{{#pattern}}[RegularExpression("{{{pattern}}}")]{{/pattern}}{{#minLength}}{{#maxLength}}[StringLength({{maxLength}}, MinimumLength={{minLength}})]{{/maxLength}}{{/minLength}}{{#minLength}}{{^maxLength}} [MinLength({{minLength}})]{{/maxLength}}{{/minLength}}{{^minLength}}{{#maxLength}} [MaxLength({{maxLength}})]{{/maxLength}}{{/minLength}}{{#minimum}}{{#maximum}}[Range({{minimum}}, {{maximum}})]{{/maximum}}{{/minimum}}{{&dataType}} {{paramName}}{{/isFormParam}}
\ No newline at end of file
diff --git a/modules/openapi-generator/src/main/resources/aspnetcore/2.1/pathParam.mustache b/modules/openapi-generator/src/main/resources/aspnetcore/2.1/pathParam.mustache
index 7a7ffd3ab1..3447b8005d 100644
--- a/modules/openapi-generator/src/main/resources/aspnetcore/2.1/pathParam.mustache
+++ b/modules/openapi-generator/src/main/resources/aspnetcore/2.1/pathParam.mustache
@@ -1 +1 @@
-{{#isPathParam}}[FromRoute]{{#required}}[Required]{{/required}}{{#pattern}}[RegularExpression("{{{pattern}}}")]{{/pattern}}{{#minLength}}{{#maxLength}}[StringLength({{maxLength}}, MinimumLength={{minLength}})]{{/maxLength}}{{/minLength}}{{#minLength}}{{^maxLength}} [MinLength({{minLength}})]{{/maxLength}}{{/minLength}}{{^minLength}}{{#maxLength}} [MaxLength({{maxLength}})]{{/maxLength}}{{/minLength}}{{#minimum}}{{#maximum}}[Range({{minimum}}, {{maximum}})]{{/maximum}}{{/minimum}}{{&dataType}} {{paramName}}{{/isPathParam}}
\ No newline at end of file
+{{#isPathParam}}[FromRoute (Name = "{{baseName}}")]{{#required}}[Required]{{/required}}{{#pattern}}[RegularExpression("{{{pattern}}}")]{{/pattern}}{{#minLength}}{{#maxLength}}[StringLength({{maxLength}}, MinimumLength={{minLength}})]{{/maxLength}}{{/minLength}}{{#minLength}}{{^maxLength}} [MinLength({{minLength}})]{{/maxLength}}{{/minLength}}{{^minLength}}{{#maxLength}} [MaxLength({{maxLength}})]{{/maxLength}}{{/minLength}}{{#minimum}}{{#maximum}}[Range({{minimum}}, {{maximum}})]{{/maximum}}{{/minimum}}{{&dataType}} {{paramName}}{{/isPathParam}}
\ No newline at end of file
diff --git a/modules/openapi-generator/src/main/resources/aspnetcore/2.1/queryParam.mustache b/modules/openapi-generator/src/main/resources/aspnetcore/2.1/queryParam.mustache
index c454950bd1..3a052802fc 100644
--- a/modules/openapi-generator/src/main/resources/aspnetcore/2.1/queryParam.mustache
+++ b/modules/openapi-generator/src/main/resources/aspnetcore/2.1/queryParam.mustache
@@ -1 +1 @@
-{{#isQueryParam}}[FromQuery]{{#required}}[Required()]{{/required}}{{#pattern}}[RegularExpression("{{{pattern}}}")]{{/pattern}}{{#minLength}}{{#maxLength}}[StringLength({{maxLength}}, MinimumLength={{minLength}})]{{/maxLength}}{{/minLength}}{{#minLength}}{{^maxLength}} [MinLength({{minLength}})]{{/maxLength}}{{/minLength}}{{^minLength}}{{#maxLength}} [MaxLength({{maxLength}})]{{/maxLength}}{{/minLength}}{{#minimum}}{{#maximum}}[Range({{minimum}}, {{maximum}})]{{/maximum}}{{/minimum}}{{&dataType}} {{paramName}}{{/isQueryParam}}
\ No newline at end of file
+{{#isQueryParam}}[FromQuery (Name = "{{baseName}}")]{{#required}}[Required()]{{/required}}{{#pattern}}[RegularExpression("{{{pattern}}}")]{{/pattern}}{{#minLength}}{{#maxLength}}[StringLength({{maxLength}}, MinimumLength={{minLength}})]{{/maxLength}}{{/minLength}}{{#minLength}}{{^maxLength}} [MinLength({{minLength}})]{{/maxLength}}{{/minLength}}{{^minLength}}{{#maxLength}} [MaxLength({{maxLength}})]{{/maxLength}}{{/minLength}}{{#minimum}}{{#maximum}}[Range({{minimum}}, {{maximum}})]{{/maximum}}{{/minimum}}{{&dataType}} {{paramName}}{{/isQueryParam}}
\ No newline at end of file
diff --git a/modules/openapi-generator/src/main/resources/aspnetcore/3.0/Project.csproj.mustache b/modules/openapi-generator/src/main/resources/aspnetcore/3.0/Project.csproj.mustache
index 83036fc53a..eaf943b952 100644
--- a/modules/openapi-generator/src/main/resources/aspnetcore/3.0/Project.csproj.mustache
+++ b/modules/openapi-generator/src/main/resources/aspnetcore/3.0/Project.csproj.mustache
@@ -2,7 +2,7 @@
{{packageName}}
{{packageName}}
- netcoreapp{{aspnetCoreVersion}}
+ {{targetFramework}}
true
true
{{#isLibrary}}
@@ -40,6 +40,7 @@
{{/useNewtonsoft}}
{{/useSwashbuckle}}
+
diff --git a/modules/openapi-generator/src/main/resources/aspnetcore/3.0/Startup.mustache b/modules/openapi-generator/src/main/resources/aspnetcore/3.0/Startup.mustache
index 88f7535009..6b8fd56ff9 100644
--- a/modules/openapi-generator/src/main/resources/aspnetcore/3.0/Startup.mustache
+++ b/modules/openapi-generator/src/main/resources/aspnetcore/3.0/Startup.mustache
@@ -155,9 +155,9 @@ namespace {{packageName}}
}){{/useSwashbuckle}};
app.UseRouting();
app.UseEndpoints(endpoints =>
- {
- endpoints.MapControllers();
- });
+ {
+ endpoints.MapControllers();
+ });
}
}
}
diff --git a/modules/openapi-generator/src/main/resources/aspnetcore/3.0/controller.mustache b/modules/openapi-generator/src/main/resources/aspnetcore/3.0/controller.mustache
index 089e415671..73e6e4fa9a 100644
--- a/modules/openapi-generator/src/main/resources/aspnetcore/3.0/controller.mustache
+++ b/modules/openapi-generator/src/main/resources/aspnetcore/3.0/controller.mustache
@@ -49,7 +49,7 @@ namespace {{apiPackage}}
public {{operationModifier}} {{#operationResultTask}}{{#operationIsAsync}}async {{/operationIsAsync}}Task<{{/operationResultTask}}IActionResult{{#operationResultTask}}>{{/operationResultTask}} {{operationId}}({{#allParams}}{{>pathParam}}{{>queryParam}}{{>bodyParam}}{{>formParam}}{{>headerParam}}{{^-last}}{{^isCookieParam}}, {{/isCookieParam}}{{/-last}}{{/allParams}}){{^generateBody}};{{/generateBody}}
{{#generateBody}}
{
- {{#cookieParams}}
+ {{#cookieParams}}
var {{paramName}} = Request.Cookies["{{paramName}}"];
{{/cookieParams}}
diff --git a/modules/openapi-generator/src/main/resources/aspnetcore/3.0/formParam.mustache b/modules/openapi-generator/src/main/resources/aspnetcore/3.0/formParam.mustache
index fbd2d815d5..e71c9619d8 100644
--- a/modules/openapi-generator/src/main/resources/aspnetcore/3.0/formParam.mustache
+++ b/modules/openapi-generator/src/main/resources/aspnetcore/3.0/formParam.mustache
@@ -1 +1 @@
-{{#isFormParam}}[FromForm]{{#required}}[Required()]{{/required}}{{#pattern}}[RegularExpression("{{{pattern}}}")]{{/pattern}}{{#minLength}}{{#maxLength}}[StringLength({{maxLength}}, MinimumLength={{minLength}})]{{/maxLength}}{{/minLength}}{{#minLength}}{{^maxLength}} [MinLength({{minLength}})]{{/maxLength}}{{/minLength}}{{^minLength}}{{#maxLength}} [MaxLength({{maxLength}})]{{/maxLength}}{{/minLength}}{{#minimum}}{{#maximum}}[Range({{minimum}}, {{maximum}})]{{/maximum}}{{/minimum}}{{&dataType}} {{paramName}}{{/isFormParam}}
\ No newline at end of file
+{{#isFormParam}}[FromForm (Name = "{{baseName}}")]{{#required}}[Required()]{{/required}}{{#pattern}}[RegularExpression("{{{pattern}}}")]{{/pattern}}{{#minLength}}{{#maxLength}}[StringLength({{maxLength}}, MinimumLength={{minLength}})]{{/maxLength}}{{/minLength}}{{#minLength}}{{^maxLength}} [MinLength({{minLength}})]{{/maxLength}}{{/minLength}}{{^minLength}}{{#maxLength}} [MaxLength({{maxLength}})]{{/maxLength}}{{/minLength}}{{#minimum}}{{#maximum}}[Range({{minimum}}, {{maximum}})]{{/maximum}}{{/minimum}}{{&dataType}} {{paramName}}{{/isFormParam}}
\ No newline at end of file
diff --git a/modules/openapi-generator/src/main/resources/aspnetcore/3.0/model.mustache b/modules/openapi-generator/src/main/resources/aspnetcore/3.0/model.mustache
index 491b39e54a..5bd13ab905 100644
--- a/modules/openapi-generator/src/main/resources/aspnetcore/3.0/model.mustache
+++ b/modules/openapi-generator/src/main/resources/aspnetcore/3.0/model.mustache
@@ -7,6 +7,13 @@ using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.Runtime.Serialization;
using Newtonsoft.Json;
+{{#models}}
+{{#model}}
+{{#discriminator}}
+using JsonSubTypes;
+{{/discriminator}}
+{{/model}}
+{{/models}}
using {{packageName}}.Converters;
{{#models}}
@@ -17,6 +24,12 @@ namespace {{modelPackage}}
/// {{description}}
///
[DataContract]
+ {{#discriminator}}
+ [JsonConverter(typeof(JsonSubtypes), "{{{discriminatorName}}}")]
+ {{#mappedModels}}
+ [JsonSubtypes.KnownSubType(typeof({{{modelName}}}), "{{^vendorExtensions.x-discriminator-value}}{{{mappingName}}}{{/vendorExtensions.x-discriminator-value}}{{#vendorExtensions.x-discriminator-value}}{{{.}}}{{/vendorExtensions.x-discriminator-value}}")]
+ {{/mappedModels}}
+ {{/discriminator}}
public {{#modelClassModifier}}{{modelClassModifier}} {{/modelClassModifier}}class {{classname}} : {{#parent}}{{{parent}}}, {{/parent}}IEquatable<{{classname}}>
{
{{#vars}}
diff --git a/modules/openapi-generator/src/main/resources/aspnetcore/3.0/pathParam.mustache b/modules/openapi-generator/src/main/resources/aspnetcore/3.0/pathParam.mustache
index 7a7ffd3ab1..3447b8005d 100644
--- a/modules/openapi-generator/src/main/resources/aspnetcore/3.0/pathParam.mustache
+++ b/modules/openapi-generator/src/main/resources/aspnetcore/3.0/pathParam.mustache
@@ -1 +1 @@
-{{#isPathParam}}[FromRoute]{{#required}}[Required]{{/required}}{{#pattern}}[RegularExpression("{{{pattern}}}")]{{/pattern}}{{#minLength}}{{#maxLength}}[StringLength({{maxLength}}, MinimumLength={{minLength}})]{{/maxLength}}{{/minLength}}{{#minLength}}{{^maxLength}} [MinLength({{minLength}})]{{/maxLength}}{{/minLength}}{{^minLength}}{{#maxLength}} [MaxLength({{maxLength}})]{{/maxLength}}{{/minLength}}{{#minimum}}{{#maximum}}[Range({{minimum}}, {{maximum}})]{{/maximum}}{{/minimum}}{{&dataType}} {{paramName}}{{/isPathParam}}
\ No newline at end of file
+{{#isPathParam}}[FromRoute (Name = "{{baseName}}")]{{#required}}[Required]{{/required}}{{#pattern}}[RegularExpression("{{{pattern}}}")]{{/pattern}}{{#minLength}}{{#maxLength}}[StringLength({{maxLength}}, MinimumLength={{minLength}})]{{/maxLength}}{{/minLength}}{{#minLength}}{{^maxLength}} [MinLength({{minLength}})]{{/maxLength}}{{/minLength}}{{^minLength}}{{#maxLength}} [MaxLength({{maxLength}})]{{/maxLength}}{{/minLength}}{{#minimum}}{{#maximum}}[Range({{minimum}}, {{maximum}})]{{/maximum}}{{/minimum}}{{&dataType}} {{paramName}}{{/isPathParam}}
\ No newline at end of file
diff --git a/modules/openapi-generator/src/main/resources/aspnetcore/3.0/queryParam.mustache b/modules/openapi-generator/src/main/resources/aspnetcore/3.0/queryParam.mustache
index c454950bd1..3a052802fc 100644
--- a/modules/openapi-generator/src/main/resources/aspnetcore/3.0/queryParam.mustache
+++ b/modules/openapi-generator/src/main/resources/aspnetcore/3.0/queryParam.mustache
@@ -1 +1 @@
-{{#isQueryParam}}[FromQuery]{{#required}}[Required()]{{/required}}{{#pattern}}[RegularExpression("{{{pattern}}}")]{{/pattern}}{{#minLength}}{{#maxLength}}[StringLength({{maxLength}}, MinimumLength={{minLength}})]{{/maxLength}}{{/minLength}}{{#minLength}}{{^maxLength}} [MinLength({{minLength}})]{{/maxLength}}{{/minLength}}{{^minLength}}{{#maxLength}} [MaxLength({{maxLength}})]{{/maxLength}}{{/minLength}}{{#minimum}}{{#maximum}}[Range({{minimum}}, {{maximum}})]{{/maximum}}{{/minimum}}{{&dataType}} {{paramName}}{{/isQueryParam}}
\ No newline at end of file
+{{#isQueryParam}}[FromQuery (Name = "{{baseName}}")]{{#required}}[Required()]{{/required}}{{#pattern}}[RegularExpression("{{{pattern}}}")]{{/pattern}}{{#minLength}}{{#maxLength}}[StringLength({{maxLength}}, MinimumLength={{minLength}})]{{/maxLength}}{{/minLength}}{{#minLength}}{{^maxLength}} [MinLength({{minLength}})]{{/maxLength}}{{/minLength}}{{^minLength}}{{#maxLength}} [MaxLength({{maxLength}})]{{/maxLength}}{{/minLength}}{{#minimum}}{{#maximum}}[Range({{minimum}}, {{maximum}})]{{/maximum}}{{/minimum}}{{&dataType}} {{paramName}}{{/isQueryParam}}
\ No newline at end of file
diff --git a/modules/openapi-generator/src/main/resources/cpp-qt5-client/CMakeLists.txt.mustache b/modules/openapi-generator/src/main/resources/cpp-qt5-client/CMakeLists.txt.mustache
index 0283656007..b78e15fb97 100644
--- a/modules/openapi-generator/src/main/resources/cpp-qt5-client/CMakeLists.txt.mustache
+++ b/modules/openapi-generator/src/main/resources/cpp-qt5-client/CMakeLists.txt.mustache
@@ -15,12 +15,28 @@ find_package(Qt5Core REQUIRED)
find_package(Qt5Network REQUIRED){{#contentCompression}}
find_package(ZLIB REQUIRED){{/contentCompression}}
-file(GLOB SRCS
- ${CMAKE_CURRENT_SOURCE_DIR}/*.cpp
+add_library(${PROJECT_NAME}
+{{#models}}
+{{#model}}
+ {{classname}}.cpp
+{{/model}}
+{{/models}}
+{{#apiInfo}}
+{{#apis}}
+{{#operations}}
+ {{classname}}.cpp
+{{/operations}}
+{{/apis}}
+{{/apiInfo}}
+ {{prefix}}Helpers.cpp
+ {{prefix}}HttpRequest.cpp
+ {{prefix}}HttpFileElement.cpp
)
+target_link_libraries(${PROJECT_NAME} PRIVATE Qt5::Core Qt5::Network {{#contentCompression}} ${ZLIB_LIBRARIES}{{/contentCompression}})
-add_library(${PROJECT_NAME} ${SRCS})
-target_link_libraries(${PROJECT_NAME} PRIVATE Qt5::Core Qt5::Network ssl crypto{{#contentCompression}} ${ZLIB_LIBRARIES}{{/contentCompression}})
+if(NOT APPLE)
+ target_link_libraries(${PROJECT_NAME} PRIVATE ssl crypto)
+endif()
set_property(TARGET ${PROJECT_NAME} PROPERTY CXX_STANDARD 14)
set_property(TARGET ${PROJECT_NAME} PROPERTY CXX_STANDARD_REQUIRED ON)
diff --git a/modules/openapi-generator/src/main/resources/cpp-qt5-client/HttpFileElement.cpp.mustache b/modules/openapi-generator/src/main/resources/cpp-qt5-client/HttpFileElement.cpp.mustache
index 4163b8be31..a1348541e9 100644
--- a/modules/openapi-generator/src/main/resources/cpp-qt5-client/HttpFileElement.cpp.mustache
+++ b/modules/openapi-generator/src/main/resources/cpp-qt5-client/HttpFileElement.cpp.mustache
@@ -57,13 +57,13 @@ QJsonValue {{prefix}}HttpFileElement::asJsonValue() const {
if (!result) {
qDebug() << "Error opening file " << local_filename;
}
-#if QT_VERSION >= 0x051500
+#if QT_VERSION >= QT_VERSION_CHECK(5, 15, 0)
return QJsonDocument::fromJson(bArray.data()).object();
#else
- return QJsonDocument::fromBinaryData(bArray.data()).object();
+ return QJsonDocument::fromBinaryData(bArray.data()).object();
#endif
}
-
+
bool {{prefix}}HttpFileElement::fromStringValue(const QString &instr) {
QFile file(local_filename);
bool result = false;
@@ -86,7 +86,7 @@ bool {{prefix}}HttpFileElement::fromJsonValue(const QJsonValue &jval) {
file.remove();
}
result = file.open(QIODevice::WriteOnly);
-#if QT_VERSION >= 0x051500
+#if QT_VERSION >= QT_VERSION_CHECK(5, 15, 0)
file.write(QJsonDocument(jval.toObject()).toJson());
#else
file.write(QJsonDocument(jval.toObject()).toBinaryData());
diff --git a/modules/openapi-generator/src/main/resources/cpp-qt5-client/HttpRequest.cpp.mustache b/modules/openapi-generator/src/main/resources/cpp-qt5-client/HttpRequest.cpp.mustache
index 4ce0cfb2d6..4c4cbbb664 100644
--- a/modules/openapi-generator/src/main/resources/cpp-qt5-client/HttpRequest.cpp.mustache
+++ b/modules/openapi-generator/src/main/resources/cpp-qt5-client/HttpRequest.cpp.mustache
@@ -7,7 +7,7 @@
#include
#include
#include
-#if QT_VERSION >= 0x051500
+#if QT_VERSION >= QT_VERSION_CHECK(5, 15, 0)
#define SKIP_EMPTY_PARTS Qt::SkipEmptyParts
#else
#define SKIP_EMPTY_PARTS QString::SkipEmptyParts
@@ -52,7 +52,7 @@ void {{prefix}}HttpRequestInput::add_file(QString variable_name, QString local_f
{{prefix}}HttpRequestWorker::{{prefix}}HttpRequestWorker(QObject *parent, QNetworkAccessManager *_manager)
: QObject(parent), manager(_manager), timeOutTimer(this), isResponseCompressionEnabled(false), isRequestCompressionEnabled(false), httpResponseCode(-1) {
-#if QT_VERSION >= 0x051500
+#if QT_VERSION >= QT_VERSION_CHECK(5, 15, 0)
randomGenerator = QRandomGenerator(QDateTime::currentDateTime().toSecsSinceEpoch());
#else
qsrand(QDateTime::currentDateTime().toTime_t());
@@ -216,7 +216,7 @@ void {{prefix}}HttpRequestWorker::execute({{prefix}}HttpRequestInput *input) {
// variable layout is MULTIPART
boundary = QString("__-----------------------%1%2")
- #if QT_VERSION >= 0x051500
+ #if QT_VERSION >= QT_VERSION_CHECK(5, 15, 0)
.arg(QDateTime::currentDateTime().toSecsSinceEpoch())
.arg(randomGenerator.generate());
#else
@@ -546,7 +546,7 @@ QByteArray {{prefix}}HttpRequestWorker::compress(const QByteArray& input, int le
return output;{{/contentCompression}}{{^contentCompression}}
Q_UNUSED(input);
Q_UNUSED(level);
- Q_UNUSED(compressType);
+ Q_UNUSED(compressType);
return QByteArray();{{/contentCompression}}
}
diff --git a/modules/openapi-generator/src/main/resources/cpp-qt5-client/HttpRequest.h.mustache b/modules/openapi-generator/src/main/resources/cpp-qt5-client/HttpRequest.h.mustache
index a853306225..b9dec34915 100644
--- a/modules/openapi-generator/src/main/resources/cpp-qt5-client/HttpRequest.h.mustache
+++ b/modules/openapi-generator/src/main/resources/cpp-qt5-client/HttpRequest.h.mustache
@@ -14,7 +14,7 @@
#include
#include
#include
-#if QT_VERSION >= 0x051500
+#if QT_VERSION >= QT_VERSION_CHECK(5, 15, 0)
#include
#endif
@@ -89,7 +89,7 @@ private:
bool isResponseCompressionEnabled;
bool isRequestCompressionEnabled;
int httpResponseCode;
-#if QT_VERSION >= 0x051500
+#if QT_VERSION >= QT_VERSION_CHECK(5, 15, 0)
QRandomGenerator randomGenerator;
#endif
diff --git a/modules/openapi-generator/src/main/resources/cpp-qt5-client/Project.mustache b/modules/openapi-generator/src/main/resources/cpp-qt5-client/Project.mustache
index 5a601d0978..a815942bc7 100644
--- a/modules/openapi-generator/src/main/resources/cpp-qt5-client/Project.mustache
+++ b/modules/openapi-generator/src/main/resources/cpp-qt5-client/Project.mustache
@@ -22,8 +22,8 @@ HEADERS += \
$${PWD}/{{prefix}}Enum.h \
$${PWD}/{{prefix}}HttpFileElement.h \
$${PWD}/{{prefix}}ServerConfiguration.h \
- $${PWD}/{{prefix}}ServerVariable.h
-
+ $${PWD}/{{prefix}}ServerVariable.h
+
SOURCES += \
# Models
{{#models}}
diff --git a/modules/openapi-generator/src/main/resources/cpp-qt5-client/ServerConfiguration.mustache b/modules/openapi-generator/src/main/resources/cpp-qt5-client/ServerConfiguration.mustache
index d4bd352631..7c2beff520 100644
--- a/modules/openapi-generator/src/main/resources/cpp-qt5-client/ServerConfiguration.mustache
+++ b/modules/openapi-generator/src/main/resources/cpp-qt5-client/ServerConfiguration.mustache
@@ -17,14 +17,14 @@ namespace {{this}} {
class {{prefix}}ServerConfiguration {
public:
/**
- * @param URL A URL to the target host.
+ * @param url A URL to the target host.
* @param description A description of the host designated by the URL.
* @param variables A map between a variable name and its value. The value is used for substitution in the server's URL template.
*/
- {{prefix}}ServerConfiguration(const QString& URL, const QString& description, const QMap& variables)
+ {{prefix}}ServerConfiguration(const QUrl &url, const QString &description, const QMap &variables)
: _description(description),
_variables(variables),
- _URL(URL){}
+ _url(url){}
{{prefix}}ServerConfiguration(){}
~{{prefix}}ServerConfiguration(){}
@@ -35,7 +35,7 @@ public:
* @return Formatted URL.
*/
QString URL() {
- QString url = _URL;
+ QString url = _url.toString();
if(!_variables.empty()){
// go through variables and replace placeholders
for (auto const& v : _variables.keys()) {
@@ -55,7 +55,7 @@ public:
return url;
}
- int setDefaultValue(const QString& variable,const QString& value){
+ int setDefaultValue(const QString &variable,const QString &value){
if(_variables.contains(variable))
return _variables[variable].setDefaultValue(value);
return -1;
@@ -63,7 +63,7 @@ public:
QString _description;
QMap _variables;
- QString _URL;
+ QUrl _url;
};
diff --git a/modules/openapi-generator/src/main/resources/cpp-qt5-client/api-body.mustache b/modules/openapi-generator/src/main/resources/cpp-qt5-client/api-body.mustache
index 42c30bfba3..855560a0b0 100644
--- a/modules/openapi-generator/src/main/resources/cpp-qt5-client/api-body.mustache
+++ b/modules/openapi-generator/src/main/resources/cpp-qt5-client/api-body.mustache
@@ -9,12 +9,8 @@
namespace {{this}} {
{{/cppNamespaceDeclarations}}
-{{classname}}::{{classname}}(const QString &scheme, const QString &host, int port, const QString &basePath, const int timeOut)
- : _scheme(scheme),
- _host(host),
- _port(port),
- _basePath(basePath),
- _timeOut(timeOut),
+{{classname}}::{{classname}}(const int timeOut)
+ : _timeOut(timeOut),
_manager(nullptr),
isResponseCompressionEnabled(false),
isRequestCompressionEnabled(false) {
@@ -32,7 +28,7 @@ QList<{{prefix}}ServerConfiguration> defaultConf = QList<{{prefix}}ServerConfigu
QList<{{prefix}}ServerConfiguration> serverConf = QList<{{prefix}}ServerConfiguration>();
{{#vendorExtensions.x-cpp-global-server-list}}
defaultConf.append({{prefix}}ServerConfiguration(
- "{{{url}}}",
+ QUrl("{{{url}}}"),
"{{{description}}}{{^description}}No description provided{{/description}}",
{{#variables}}{{#-first}}QMap{ {{/-first}}
{"{{{name}}}", {{prefix}}ServerVariable("{{{description}}}{{^description}}No description provided{{/description}}","{{{defaultValue}}}",
@@ -48,7 +44,7 @@ _serverIndices.insert("{{nickname}}",0);
{{/servers}}
{{#servers}}
serverConf.append({{prefix}}ServerConfiguration(
- "{{{url}}}",
+ QUrl("{{{url}}}"),
"{{{description}}}{{^description}}No description provided{{/description}}",
{{#variables}}{{#-first}}QMap{ {{/-first}}
{"{{{name}}}", {{prefix}}ServerVariable("{{{description}}}{{^description}}No description provided{{/description}}","{{{defaultValue}}}",
@@ -79,18 +75,6 @@ void {{classname}}::setServerIndex(const QString &operation, int serverIndex){
_serverIndices[operation] = serverIndex;
}
-void {{classname}}::setScheme(const QString &scheme) {
- _scheme = scheme;
-}
-
-void {{classname}}::setHost(const QString &host) {
- _host = host;
-}
-
-void {{classname}}::setPort(int port) {
- _port = port;
-}
-
void {{classname}}::setApiKey(const QString &apiKeyName, const QString &apiKey){
_apiKeys.insert(apiKeyName,apiKey);
}
@@ -107,9 +91,6 @@ void {{classname}}::setPassword(const QString &password) {
_password = password;
}
-void {{classname}}::setBasePath(const QString &basePath) {
- _basePath = basePath;
-}
void {{classname}}::setTimeOut(const int timeOut) {
_timeOut = timeOut;
@@ -123,6 +104,49 @@ void {{classname}}::setNetworkAccessManager(QNetworkAccessManager* manager) {
_manager = manager;
}
+ /**
+ * Appends a new ServerConfiguration to the config map for a specific operation.
+ * @param operation The id to the target operation.
+ * @param url A string that contains the URL of the server
+ * @param description A String that describes the server
+ * @param variables A map between a variable name and its value. The value is used for substitution in the server's URL template.
+ * returns the index of the new server config on success and -1 if the operation is not found
+ */
+int {{classname}}::addServerConfiguration(const QString &operation, const QUrl &url, const QString &description, const QMap &variables){
+ if(_serverConfigs.contains(operation)){
+ _serverConfigs[operation].append({{prefix}}ServerConfiguration(
+ url,
+ description,
+ variables));
+ return _serverConfigs[operation].size()-1;
+ }else{
+ return -1;
+ }
+}
+
+ /**
+ * Appends a new ServerConfiguration to the config map for a all operations and sets the index to that server.
+ * @param url A string that contains the URL of the server
+ * @param description A String that describes the server
+ * @param variables A map between a variable name and its value. The value is used for substitution in the server's URL template.
+ */
+void {{classname}}::setNewServerForAllOperations(const QUrl &url, const QString &description, const QMap &variables){
+ for(auto e : _serverIndices.keys()){
+ setServerIndex(e, addServerConfiguration(e, url, description, variables));
+ }
+}
+ /**
+ * Appends a new ServerConfiguration to the config map for an operations and sets the index to that server.
+ * @param URL A string that contains the URL of the server
+ * @param description A String that describes the server
+ * @param variables A map between a variable name and its value. The value is used for substitution in the server's URL template.
+ */
+void {{classname}}::setNewServer(const QString &operation, const QUrl &url, const QString &description, const QMap &variables){
+
+ setServerIndex(operation, addServerConfiguration(operation, url, description, variables));
+
+}
+
void {{classname}}::addHeaders(const QString &key, const QString &value) {
defaultHeaders.insert(key, value);
}
@@ -203,7 +227,7 @@ QString {{classname}}::getParamStyleDelimiter(QString style, QString name, bool
{{#operations}}
{{#operation}}
-void {{classname}}::{{nickname}}({{#allParams}}const {{{dataType}}} &{{paramName}}{{^-last}}, {{/-last}}{{/allParams}}) {
+void {{classname}}::{{nickname}}({{#allParams}}{{#required}}const {{{dataType}}} &{{/required}}{{^required}}const QVariant &{{/required}}{{paramName}}{{^-last}}, {{/-last}}{{/allParams}}) {
QString fullPath = QString(_serverConfigs["{{nickname}}"][_serverIndices.value("{{nickname}}")].URL()+"{{{path}}}");
{{#authMethods}}{{#isApiKey}}{{#isKeyInHeader}}
if(_apiKeys.contains("{{name}}")){
@@ -226,220 +250,235 @@ void {{classname}}::{{nickname}}({{#allParams}}const {{{dataType}}} &{{paramName
b64.append(_username.toUtf8() + ":" + _password.toUtf8());
addHeaders("Authorization","Basic " + b64.toBase64());
}{{/isBasicBasic}}{{/authMethods}}
+
{{#pathParams}}
- QString {{paramName}}PathParam("{");
- {{paramName}}PathParam.append("{{baseName}}").append("}");
- QString pathPrefix, pathSuffix, pathDelimiter;
- QString pathStyle = "{{style}}";
- if(pathStyle == "")
- pathStyle = "simple";
- pathPrefix = getParamStylePrefix(pathStyle);
- pathSuffix = getParamStyleSuffix(pathStyle);
- pathDelimiter = getParamStyleDelimiter(pathStyle, "{{baseName}}", {{isExplode}});
+ {{^required}}if(!{{paramName}}.isNull()){{/required}}
+ {
+ QString {{paramName}}PathParam("{");
+ {{paramName}}PathParam.append("{{baseName}}").append("}");
+ QString pathPrefix, pathSuffix, pathDelimiter;
+ QString pathStyle = "{{style}}";
+ if(pathStyle == "")
+ pathStyle = "simple";
+ pathPrefix = getParamStylePrefix(pathStyle);
+ pathSuffix = getParamStyleSuffix(pathStyle);
+ pathDelimiter = getParamStyleDelimiter(pathStyle, "{{baseName}}", {{isExplode}});
{{^collectionFormat}}
- {{^isPrimitiveType}}
- QString paramString = (pathStyle == "matrix" && {{isExplode}}) ? pathPrefix : pathPrefix+"{{baseName}}"+pathSuffix;
- QJsonObject parameter = {{paramName}}.asJsonObject();
- qint32 count = 0;
- foreach(const QString& key, parameter.keys()) {
- if (count > 0) {
- pathDelimiter = (pathStyle == "matrix" && {{isExplode}}) ? ";" : getParamStyleDelimiter(pathStyle, key, {{isExplode}});
- paramString.append(pathDelimiter);
+ {{^isPrimitiveType}}
+ QString paramString = (pathStyle == "matrix" && {{isExplode}}) ? pathPrefix : pathPrefix+"{{baseName}}"+pathSuffix;
+ QJsonObject parameter = {{paramName}}{{^required}}.value<{{{dataType}}}>(){{/required}}.asJsonObject();
+ qint32 count = 0;
+ foreach(const QString& key, parameter.keys()) {
+ if (count > 0) {
+ pathDelimiter = (pathStyle == "matrix" && {{isExplode}}) ? ";" : getParamStyleDelimiter(pathStyle, key, {{isExplode}});
+ paramString.append(pathDelimiter);
+ }
+ QString assignOperator = ({{isExplode}}) ? "=" : ",";
+ switch(parameter.value(key).type()) {
+ case QJsonValue::String:
+ {
+ paramString.append(key+assignOperator+parameter.value(key).toString());
+ break;
+ }
+ case QJsonValue::Double:
+ {
+ paramString.append(key+assignOperator+QString::number(parameter.value(key).toDouble()));
+ break;
+ }
+ case QJsonValue::Bool:
+ {
+ paramString.append(key+assignOperator+QVariant(parameter.value(key).toBool()).toString());
+ break;
+ }
+ case QJsonValue::Array:
+ {
+ paramString.append(key+assignOperator+QVariant(parameter.value(key).toArray()).toString());
+ break;
+ }
+ case QJsonValue::Object:
+ {
+ paramString.append(key+assignOperator+QVariant(parameter.value(key).toObject()).toString());
+ break;
+ }
+ case QJsonValue::Null:
+ case QJsonValue::Undefined:
+ break;
+ }
+ count++;
}
- QString assignOperator = ({{isExplode}}) ? "=" : ",";
- switch(parameter.value(key).type()) {
- case QJsonValue::String:
- {
- paramString.append(key+assignOperator+parameter.value(key).toString());
- break;
- }
- case QJsonValue::Double:
- {
- paramString.append(key+assignOperator+QString::number(parameter.value(key).toDouble()));
- break;
- }
- case QJsonValue::Bool:
- {
- paramString.append(key+assignOperator+QVariant(parameter.value(key).toBool()).toString());
- break;
- }
- case QJsonValue::Array:
- {
- paramString.append(key+assignOperator+QVariant(parameter.value(key).toArray()).toString());
- break;
- }
- case QJsonValue::Object:
- {
- paramString.append(key+assignOperator+QVariant(parameter.value(key).toObject()).toString());
- break;
- }
- case QJsonValue::Null:
- case QJsonValue::Undefined:
- break;
- }
- count++;
- }
- fullPath.replace({{paramName}}PathParam, QUrl::toPercentEncoding(paramString));
- {{/isPrimitiveType}}
- {{#isPrimitiveType}}
- QString paramString = (pathStyle == "matrix") ? pathPrefix+"{{baseName}}"+pathSuffix : pathPrefix;
- fullPath.replace({{paramName}}PathParam, paramString+QUrl::toPercentEncoding(::{{cppNamespace}}::toStringValue({{paramName}})));
-{{/isPrimitiveType}}{{/collectionFormat}}{{#collectionFormat}}
- if ({{{paramName}}}.size() > 0) {
+ fullPath.replace({{paramName}}PathParam, QUrl::toPercentEncoding(paramString));
+ {{/isPrimitiveType}}
+ {{#isPrimitiveType}}
+ QString paramString = (pathStyle == "matrix") ? pathPrefix+"{{baseName}}"+pathSuffix : pathPrefix;
+ fullPath.replace({{paramName}}PathParam, paramString+QUrl::toPercentEncoding(::{{cppNamespace}}::toStringValue({{paramName}}{{^required}}.value<{{{dataType}}}>(){{/required}})));
+ {{/isPrimitiveType}}
+ {{/collectionFormat}}
+ {{#collectionFormat}}
+ if ({{{paramName}}}{{^required}}.value<{{{dataType}}}>(){{/required}}.size() > 0) {
QString paramString = (pathStyle == "matrix") ? pathPrefix+"{{baseName}}"+pathSuffix : pathPrefix;
qint32 count = 0;
- foreach ({{{baseType}}} t, {{paramName}}) {
+ foreach ({{{baseType}}} t, {{paramName}}{{^required}}.value<{{{dataType}}}>(){{/required}}) {
if (count > 0) {
fullPath.append(pathDelimiter);
}
fullPath.append(QUrl::toPercentEncoding(::{{cppNamespace}}::toStringValue(t)));
count++;
}
- fullPath.replace({{paramName}}PathParam, paramString);
+ fullPath.replace({{paramName}}PathParam, paramString);
+ }
+ {{/collectionFormat}}
}
-{{/collectionFormat}}{{/pathParams}}
+
+ {{/pathParams}}
{{#hasQueryParams}}
QString queryPrefix, querySuffix, queryDelimiter, queryStyle;
{{/hasQueryParams}}
-{{#queryParams}}
- queryStyle = "{{style}}";
- if(queryStyle == "")
- queryStyle = "form";
- queryPrefix = getParamStylePrefix(queryStyle);
- querySuffix = getParamStyleSuffix(queryStyle);
- queryDelimiter = getParamStyleDelimiter(queryStyle, "{{baseName}}", {{isExplode}});
-{{^collectionFormat}}
- if (fullPath.indexOf("?") > 0)
- fullPath.append(queryPrefix);
- else
- fullPath.append("?");
- {{^isPrimitiveType}}
- QString paramString = (queryStyle == "form" && {{isExplode}}) ? "" : (queryStyle == "form" && !({{isExplode}})) ? "{{baseName}}"+querySuffix : "";
- QJsonObject parameter = {{paramName}}.asJsonObject();
- qint32 count = 0;
- foreach(const QString& key, parameter.keys()) {
- if (count > 0) {
- queryDelimiter = ((queryStyle == "form" || queryStyle == "deepObject") && {{isExplode}}) ? "&" : getParamStyleDelimiter(queryStyle, key, {{isExplode}});
- paramString.append(queryDelimiter);
+ {{#queryParams}}
+ {{^required}}if(!{{paramName}}.isNull()){{/required}}
+ {
+ queryStyle = "{{style}}";
+ if(queryStyle == "")
+ queryStyle = "form";
+ queryPrefix = getParamStylePrefix(queryStyle);
+ querySuffix = getParamStyleSuffix(queryStyle);
+ queryDelimiter = getParamStyleDelimiter(queryStyle, "{{baseName}}", {{isExplode}});
+ {{^collectionFormat}}
+ if (fullPath.indexOf("?") > 0)
+ fullPath.append(queryPrefix);
+ else
+ fullPath.append("?");
+ {{^isPrimitiveType}}
+ QString paramString = (queryStyle == "form" && {{isExplode}}) ? "" : (queryStyle == "form" && !({{isExplode}})) ? "{{baseName}}"+querySuffix : "";
+ QJsonObject parameter = {{paramName}}{{^required}}.value<{{{dataType}}}>(){{/required}}.asJsonObject();
+ qint32 count = 0;
+ foreach(const QString& key, parameter.keys()) {
+ if (count > 0) {
+ queryDelimiter = ((queryStyle == "form" || queryStyle == "deepObject") && {{isExplode}}) ? "&" : getParamStyleDelimiter(queryStyle, key, {{isExplode}});
+ paramString.append(queryDelimiter);
+ }
+ QString assignOperator;
+ if (queryStyle == "form")
+ assignOperator = ({{isExplode}}) ? "=" : ",";
+ else if (queryStyle == "deepObject")
+ assignOperator = ({{isExplode}}) ? "=" : "none";
+ switch(parameter.value(key).type()) {
+ case QJsonValue::String:
+ {
+ paramString.append(((queryStyle == "form") ? key : QString("{{baseName}}").append("[").append(key).append("]"))+assignOperator+parameter.value(key).toString());
+ break;
+ }
+ case QJsonValue::Double:
+ {
+ paramString.append(((queryStyle == "form") ? key : QString("{{baseName}}").append("[").append(key).append("]"))+assignOperator+QString::number(parameter.value(key).toDouble()));
+ break;
+ }
+ case QJsonValue::Bool:
+ {
+ paramString.append(((queryStyle == "form") ? key : QString("{{baseName}}").append("[").append(key).append("]"))+assignOperator+QVariant(parameter.value(key).toBool()).toString());
+ break;
+ }
+ case QJsonValue::Array:
+ {
+ paramString.append(((queryStyle == "form") ? key : QString("{{baseName}}").append("[").append(key).append("]"))+assignOperator+QVariant(parameter.value(key).toArray()).toString());
+ break;
+ }
+ case QJsonValue::Object:
+ {
+ paramString.append(((queryStyle == "form") ? key : QString("{{baseName}}").append("[").append(key).append("]"))+assignOperator+QVariant(parameter.value(key).toObject()).toString());
+ break;
+ }
+ case QJsonValue::Null:
+ case QJsonValue::Undefined:
+ break;
+ }
+ count++;
}
- QString assignOperator;
- if (queryStyle == "form")
- assignOperator = ({{isExplode}}) ? "=" : ",";
- else if (queryStyle == "deepObject")
- assignOperator = ({{isExplode}}) ? "=" : "none";
- switch(parameter.value(key).type()) {
- case QJsonValue::String:
- {
- paramString.append(((queryStyle == "form") ? key : QString("{{baseName}}").append("[").append(key).append("]"))+assignOperator+parameter.value(key).toString());
- break;
- }
- case QJsonValue::Double:
- {
- paramString.append(((queryStyle == "form") ? key : QString("{{baseName}}").append("[").append(key).append("]"))+assignOperator+QString::number(parameter.value(key).toDouble()));
- break;
- }
- case QJsonValue::Bool:
- {
- paramString.append(((queryStyle == "form") ? key : QString("{{baseName}}").append("[").append(key).append("]"))+assignOperator+QVariant(parameter.value(key).toBool()).toString());
- break;
- }
- case QJsonValue::Array:
- {
- paramString.append(((queryStyle == "form") ? key : QString("{{baseName}}").append("[").append(key).append("]"))+assignOperator+QVariant(parameter.value(key).toArray()).toString());
- break;
- }
- case QJsonValue::Object:
- {
- paramString.append(((queryStyle == "form") ? key : QString("{{baseName}}").append("[").append(key).append("]"))+assignOperator+QVariant(parameter.value(key).toObject()).toString());
- break;
- }
- case QJsonValue::Null:
- case QJsonValue::Undefined:
- break;
- }
- count++;
- }
- fullPath.append(paramString);
- {{/isPrimitiveType}}{{#isPrimitiveType}}
- fullPath.append(QUrl::toPercentEncoding("{{baseName}}")).append(querySuffix).append(QUrl::toPercentEncoding(::{{cppNamespace}}::toStringValue({{paramName}})));
-{{/isPrimitiveType}}{{/collectionFormat}}{{#collectionFormat}}
- if ({{{paramName}}}.size() > 0) {
- if (QString("{{collectionFormat}}").indexOf("multi") == 0) {
- foreach ({{{baseType}}} t, {{paramName}}) {
+ fullPath.append(paramString);
+ {{/isPrimitiveType}}{{#isPrimitiveType}}
+ fullPath.append(QUrl::toPercentEncoding("{{baseName}}")).append(querySuffix).append(QUrl::toPercentEncoding(::{{cppNamespace}}::toStringValue({{paramName}}{{^required}}.value<{{{dataType}}}>(){{/required}})));
+ {{/isPrimitiveType}}
+ {{/collectionFormat}}
+ {{#collectionFormat}}
+ if ({{{paramName}}}{{^required}}.value<{{{dataType}}}>(){{/required}}.size() > 0) {
+ if (QString("{{collectionFormat}}").indexOf("multi") == 0) {
+ foreach ({{{baseType}}} t, {{paramName}}{{^required}}.value<{{{dataType}}}>(){{/required}}) {
+ if (fullPath.indexOf("?") > 0)
+ fullPath.append(queryPrefix);
+ else
+ fullPath.append("?");
+ fullPath.append("{{{baseName}}}=").append(::{{cppNamespace}}::toStringValue(t));
+ }
+ } else if (QString("{{collectionFormat}}").indexOf("ssv") == 0) {
if (fullPath.indexOf("?") > 0)
- fullPath.append(queryPrefix);
+ fullPath.append("&");
else
- fullPath.append("?");
- fullPath.append("{{{baseName}}}=").append(::{{cppNamespace}}::toStringValue(t));
- }
- } else if (QString("{{collectionFormat}}").indexOf("ssv") == 0) {
- if (fullPath.indexOf("?") > 0)
- fullPath.append("&");
- else
- fullPath.append("?").append(queryPrefix).append("{{baseName}}").append(querySuffix);
- qint32 count = 0;
- foreach ({{{baseType}}} t, {{paramName}}) {
- if (count > 0) {
- fullPath.append(({{isExplode}})? queryDelimiter : QUrl::toPercentEncoding(queryDelimiter));
+ fullPath.append("?").append(queryPrefix).append("{{baseName}}").append(querySuffix);
+ qint32 count = 0;
+ foreach ({{{baseType}}} t, {{paramName}}{{^required}}.value<{{{dataType}}}>(){{/required}}) {
+ if (count > 0) {
+ fullPath.append(({{isExplode}})? queryDelimiter : QUrl::toPercentEncoding(queryDelimiter));
+ }
+ fullPath.append(::{{cppNamespace}}::toStringValue(t));
+ count++;
}
- fullPath.append(::{{cppNamespace}}::toStringValue(t));
- count++;
- }
- } else if (QString("{{collectionFormat}}").indexOf("tsv") == 0) {
- if (fullPath.indexOf("?") > 0)
- fullPath.append("&");
- else
- fullPath.append("?").append(queryPrefix).append("{{baseName}}").append(querySuffix);
- qint32 count = 0;
- foreach ({{{baseType}}} t, {{paramName}}) {
- if (count > 0) {
- fullPath.append("\t");
+ } else if (QString("{{collectionFormat}}").indexOf("tsv") == 0) {
+ if (fullPath.indexOf("?") > 0)
+ fullPath.append("&");
+ else
+ fullPath.append("?").append(queryPrefix).append("{{baseName}}").append(querySuffix);
+ qint32 count = 0;
+ foreach ({{{baseType}}} t, {{paramName}}{{^required}}.value<{{{dataType}}}>(){{/required}}) {
+ if (count > 0) {
+ fullPath.append("\t");
+ }
+ fullPath.append(::{{cppNamespace}}::toStringValue(t));
+ count++;
}
- fullPath.append(::{{cppNamespace}}::toStringValue(t));
- count++;
- }
- } else if (QString("{{collectionFormat}}").indexOf("csv") == 0) {
- if (fullPath.indexOf("?") > 0)
- fullPath.append("&");
- else
- fullPath.append("?").append(queryPrefix).append("{{baseName}}").append(querySuffix);
- qint32 count = 0;
- foreach ({{{baseType}}} t, {{paramName}}) {
- if (count > 0) {
- fullPath.append(queryDelimiter);
+ } else if (QString("{{collectionFormat}}").indexOf("csv") == 0) {
+ if (fullPath.indexOf("?") > 0)
+ fullPath.append("&");
+ else
+ fullPath.append("?").append(queryPrefix).append("{{baseName}}").append(querySuffix);
+ qint32 count = 0;
+ foreach ({{{baseType}}} t, {{paramName}}{{^required}}.value<{{{dataType}}}>(){{/required}}) {
+ if (count > 0) {
+ fullPath.append(queryDelimiter);
+ }
+ fullPath.append(::{{cppNamespace}}::toStringValue(t));
+ count++;
}
- fullPath.append(::{{cppNamespace}}::toStringValue(t));
- count++;
- }
- } else if (QString("{{collectionFormat}}").indexOf("pipes") == 0) {
- if (fullPath.indexOf("?") > 0)
- fullPath.append("&");
- else
- fullPath.append("?").append(queryPrefix).append("{{baseName}}").append(querySuffix);
- qint32 count = 0;
- foreach ({{{baseType}}} t, {{paramName}}) {
- if (count > 0) {
- fullPath.append(queryDelimiter);
+ } else if (QString("{{collectionFormat}}").indexOf("pipes") == 0) {
+ if (fullPath.indexOf("?") > 0)
+ fullPath.append("&");
+ else
+ fullPath.append("?").append(queryPrefix).append("{{baseName}}").append(querySuffix);
+ qint32 count = 0;
+ foreach ({{{baseType}}} t, {{paramName}}{{^required}}.value<{{{dataType}}}>(){{/required}}) {
+ if (count > 0) {
+ fullPath.append(queryDelimiter);
+ }
+ fullPath.append(::{{cppNamespace}}::toStringValue(t));
+ count++;
}
- fullPath.append(::{{cppNamespace}}::toStringValue(t));
- count++;
+ } else if (QString("{{collectionFormat}}").indexOf("deepObject") == 0) {
+ if (fullPath.indexOf("?") > 0)
+ fullPath.append("&");
+ else
+ fullPath.append("?").append(queryPrefix).append("{{baseName}}").append(querySuffix);
+ qint32 count = 0;
+ foreach ({{{baseType}}} t, {{paramName}}{{^required}}.value<{{{dataType}}}>(){{/required}}) {
+ if (count > 0) {
+ fullPath.append(queryDelimiter);
+ }
+ fullPath.append(::{{cppNamespace}}::toStringValue(t));
+ count++;
+ }
}
- } else if (QString("{{collectionFormat}}").indexOf("deepObject") == 0) {
- if (fullPath.indexOf("?") > 0)
- fullPath.append("&");
- else
- fullPath.append("?").append(queryPrefix).append("{{baseName}}").append(querySuffix);
- qint32 count = 0;
- foreach ({{{baseType}}} t, {{paramName}}) {
- if (count > 0) {
- fullPath.append(queryDelimiter);
- }
- fullPath.append(::{{cppNamespace}}::toStringValue(t));
- count++;
- }
}
+ {{/collectionFormat}}
}
-{{/collectionFormat}}{{/queryParams}}
+
+{{/queryParams}}
{{prefix}}HttpRequestWorker *worker = new {{prefix}}HttpRequestWorker(this, _manager);
worker->setTimeOut(_timeOut);
worker->setWorkingDirectory(_workingDirectory);{{#contentCompression}}
@@ -457,142 +496,171 @@ void {{classname}}::{{nickname}}({{#allParams}}const {{{dataType}}} &{{paramName
formSuffix = getParamStyleSuffix(formStyle);
formDelimiter = getParamStyleDelimiter(formStyle, "{{baseName}}", {{isExplode}});
{{/first}}
+
+ {{^required}}if(!{{paramName}}.isNull()){{/required}}
+ {
{{^isFile}}
- input.add_var("{{baseName}}", ::{{cppNamespace}}::toStringValue({{paramName}}));{{/isFile}}{{#isFile}}
- input.add_file("{{baseName}}", {{paramName}}.local_filename, {{paramName}}.request_filename, {{paramName}}.mime_type);{{/isFile}}{{/formParams}}{{#bodyParams}}{{#isContainer}}{{#isArray}}
- QJsonDocument doc(::{{cppNamespace}}::toJsonValue({{paramName}}).toArray());{{/isArray}}{{#isMap}}
- QJsonDocument doc(::{{cppNamespace}}::toJsonValue({{paramName}}).toObject());{{/isMap}}
+ input.add_var("{{baseName}}", ::{{cppNamespace}}::toStringValue({{paramName}}{{^required}}.value<{{{dataType}}}>(){{/required}}));
+{{/isFile}}
+{{#isFile}}
+ input.add_file("{{baseName}}", {{paramName}}{{^required}}.value<{{{dataType}}}>(){{/required}}.local_filename, {{paramName}}{{^required}}.value<{{{dataType}}}>(){{/required}}.request_filename, {{paramName}}{{^required}}.value<{{{dataType}}}>(){{/required}}.mime_type);
+{{/isFile}}
+ }
+
+{{/formParams}}
+{{#bodyParams}}
+{{#isContainer}}
+{{#isArray}}
+ QJsonDocument doc(::{{cppNamespace}}::toJsonValue({{paramName}}{{^required}}.value<{{{dataType}}}>(){{/required}}).toArray());{{/isArray}}{{#isMap}}
+ QJsonDocument doc(::{{cppNamespace}}::toJsonValue({{paramName}}{{^required}}.value<{{{dataType}}}>(){{/required}}).toObject());{{/isMap}}
QByteArray bytes = doc.toJson();
input.request_body.append(bytes);
{{/isContainer}}{{^isContainer}}{{#isString}}
- QByteArray output = {{paramName}}.toUtf8();{{/isString}}{{#isByteArray}}QByteArray output({{paramName}});{{/isByteArray}}{{^isString}}{{^isByteArray}}{{^isFile}}
- QByteArray output = {{paramName}}.asJson().toUtf8();{{/isFile}}{{/isByteArray}}{{/isString}}{{#isFile}}{{#hasConsumes}}input.headers.insert("Content-Type", {{#consumes}}{{^-first}}, {{/-first}}"{{mediaType}}"{{/consumes}});{{/hasConsumes}}
- QByteArray output = {{paramName}}.asByteArray();{{/isFile}}
+ QByteArray output = {{paramName}}{{^required}}.value<{{{dataType}}}>(){{/required}}.toUtf8();{{/isString}}{{#isByteArray}}QByteArray output({{paramName}}{{^required}}.value<{{{dataType}}}>(){{/required}});{{/isByteArray}}{{^isString}}{{^isByteArray}}{{^isFile}}
+ QByteArray output = {{paramName}}{{^required}}.value<{{{dataType}}}>(){{/required}}.asJson().toUtf8();{{/isFile}}{{/isByteArray}}{{/isString}}{{#isFile}}{{#hasConsumes}}input.headers.insert("Content-Type", {{#consumes}}{{^-first}}, {{/-first}}"{{mediaType}}"{{/consumes}});{{/hasConsumes}}
+ QByteArray output = {{paramName}}{{^required}}.value<{{{dataType}}}>(){{/required}}.asByteArray();{{/isFile}}
input.request_body.append(output);
-{{/isContainer}}{{/bodyParams}}{{#headerParams}}
-{{^collectionFormat}}{{^isPrimitiveType}}
- QString headerString;
- QJsonObject parameter = {{paramName}}.asJsonObject();
- qint32 count = 0;
- foreach(const QString& key, parameter.keys()) {
- if (count > 0) {
- headerString.append(",");
+{{/isContainer}}
+{{/bodyParams}}
+{{#headerParams}}
+ {{^required}}if(!{{paramName}}.isNull()){{/required}}
+ {
+ {{^collectionFormat}}
+ {{^isPrimitiveType}}
+ QString headerString;
+ QJsonObject parameter = {{paramName}}{{^required}}.value<{{{dataType}}}>(){{/required}}.asJsonObject();
+ qint32 count = 0;
+ foreach(const QString& key, parameter.keys()) {
+ if (count > 0) {
+ headerString.append(",");
+ }
+ QString assignOperator = ({{isExplode}}) ? "=" : ",";
+ switch(parameter.value(key).type()) {
+ case QJsonValue::String:
+ {
+ headerString.append(key+assignOperator+parameter.value(key).toString());
+ break;
+ }
+ case QJsonValue::Double:
+ {
+ headerString.append(key+assignOperator+QString::number(parameter.value(key).toDouble()));
+ break;
+ }
+ case QJsonValue::Bool:
+ {
+ headerString.append(key+assignOperator+QVariant(parameter.value(key).toBool()).toString());
+ break;
+ }
+ case QJsonValue::Array:
+ {
+ headerString.append(key+assignOperator+QVariant(parameter.value(key).toArray()).toString());
+ break;
+ }
+ case QJsonValue::Object:
+ {
+ headerString.append(key+assignOperator+QVariant(parameter.value(key).toObject()).toString());
+ break;
+ }
+ case QJsonValue::Null:
+ case QJsonValue::Undefined:
+ break;
+ }
+ count++;
}
- QString assignOperator = ({{isExplode}}) ? "=" : ",";
- switch(parameter.value(key).type()) {
- case QJsonValue::String:
- {
- headerString.append(key+assignOperator+parameter.value(key).toString());
- break;
- }
- case QJsonValue::Double:
- {
- headerString.append(key+assignOperator+QString::number(parameter.value(key).toDouble()));
- break;
- }
- case QJsonValue::Bool:
- {
- headerString.append(key+assignOperator+QVariant(parameter.value(key).toBool()).toString());
- break;
- }
- case QJsonValue::Array:
- {
- headerString.append(key+assignOperator+QVariant(parameter.value(key).toArray()).toString());
- break;
- }
- case QJsonValue::Object:
- {
- headerString.append(key+assignOperator+QVariant(parameter.value(key).toObject()).toString());
- break;
- }
- case QJsonValue::Null:
- case QJsonValue::Undefined:
- break;
+ input.headers.insert("{{baseName}}", headerString);
+ {{/isPrimitiveType}}
+ {{#isPrimitiveType}}
+ if (!::{{cppNamespace}}::toStringValue({{paramName}}{{^required}}.value<{{{dataType}}}>(){{/required}}).isEmpty()) {
+ input.headers.insert("{{baseName}}", ::{{cppNamespace}}::toStringValue({{paramName}}{{^required}}.value<{{{dataType}}}>(){{/required}}));
}
- count++;
- }
- input.headers.insert("{{baseName}}", headerString);
-{{/isPrimitiveType}}{{#isPrimitiveType}}
- if (!::{{cppNamespace}}::toStringValue({{paramName}}).isEmpty()) {
- input.headers.insert("{{baseName}}", ::{{cppNamespace}}::toStringValue({{paramName}}));
- }
-{{/isPrimitiveType}}{{/collectionFormat}}{{#collectionFormat}}
- QString headerString;
- if ({{{paramName}}}.size() > 0) {
- qint32 count = 0;
- foreach ({{{baseType}}} t, {{paramName}}) {
- if (count > 0) {
- headerString.append(",");
+ {{/isPrimitiveType}}{{/collectionFormat}}{{#collectionFormat}}
+ QString headerString;
+ if ({{{paramName}}}{{^required}}.value<{{{dataType}}}>(){{/required}}.size() > 0) {
+ qint32 count = 0;
+ foreach ({{{baseType}}} t, {{paramName}}{{^required}}.value<{{{dataType}}}>(){{/required}}) {
+ if (count > 0) {
+ headerString.append(",");
+ }
+ headerString.append(::{{cppNamespace}}::toStringValue(t));
+ count++;
}
- headerString.append(::{{cppNamespace}}::toStringValue(t));
- count++;
- }
- input.headers.insert("{{baseName}}", headerString);
- }
-{{/collectionFormat}}
+ input.headers.insert("{{baseName}}", headerString);
+ }
+ {{/collectionFormat}}
+}
{{/headerParams}}
{{#cookieParams}}
-if(QString("{{style}}").indexOf("form") == 0){
-{{^collectionFormat}}{{^isPrimitiveType}}{{^isExplode}}
- QString cookieString = "{{baseName}}=";
- QJsonObject parameter = {{paramName}}.asJsonObject();
- qint32 count = 0;
- foreach(const QString& key, parameter.keys()) {
- if (count > 0) {
- cookieString.append(",");
+ {{^required}}if(!{{paramName}}.isNull()){{/required}}
+ {
+ if(QString("{{style}}").indexOf("form") == 0){
+ {{^collectionFormat}}
+ {{^isPrimitiveType}}
+ {{^isExplode}}
+ QString cookieString = "{{baseName}}=";
+ QJsonObject parameter = {{paramName}}{{^required}}.value<{{{dataType}}}>(){{/required}}.asJsonObject();
+ qint32 count = 0;
+ foreach(const QString& key, parameter.keys()) {
+ if (count > 0) {
+ cookieString.append(",");
+ }
+ switch(parameter.value(key).type()) {
+ case QJsonValue::String:
+ {
+ cookieString.append(key+","+parameter.value(key).toString());
+ break;
+ }
+ case QJsonValue::Double:
+ {
+ cookieString.append(key+","+QString::number(parameter.value(key).toDouble()));
+ break;
+ }
+ case QJsonValue::Bool:
+ {
+ cookieString.append(key+","+QVariant(parameter.value(key).toBool()).toString());
+ break;
+ }
+ case QJsonValue::Array:
+ {
+ cookieString.append(key+","+QVariant(parameter.value(key).toArray()).toString());
+ break;
+ }
+ case QJsonValue::Object:
+ {
+ cookieString.append(key+","+QVariant(parameter.value(key).toObject()).toString());
+ break;
+ }
+ case QJsonValue::Null:
+ case QJsonValue::Undefined:
+ break;
+ }
+ count++;
+ }
+ input.headers.insert("Cookie", cookieString);
+ {{/isExplode}}
+ {{/isPrimitiveType}}
+ {{#isPrimitiveType}}
+ if (!::{{cppNamespace}}::toStringValue({{paramName}}{{^required}}.value<{{{dataType}}}>(){{/required}}).isEmpty()) {
+ input.headers.insert("Cookie", "{{baseName}}="+::{{cppNamespace}}::toStringValue({{paramName}}{{^required}}.value<{{{dataType}}}>(){{/required}}));
+ }
+ {{/isPrimitiveType}}
+ {{/collectionFormat}}
+ {{#collectionFormat}}
+ {{^isExplode}}
+ QString cookieString = "{{baseName}}=";
+ if ({{{paramName}}}.size() > 0) {
+ qint32 count = 0;
+ foreach ({{{baseType}}} t, {{paramName}}{{^required}}.value<{{{dataType}}}>(){{/required}}) {
+ if (count > 0) {
+ cookieString.append(",");
+ }
+ cookieString.append(::{{cppNamespace}}::toStringValue(t));
+ count++;
+ }
+ input.headers.insert("Cookie", cookieString);
+ }
+ {{/isExplode}}{{/collectionFormat}}
}
- switch(parameter.value(key).type()) {
- case QJsonValue::String:
- {
- cookieString.append(key+","+parameter.value(key).toString());
- break;
- }
- case QJsonValue::Double:
- {
- cookieString.append(key+","+QString::number(parameter.value(key).toDouble()));
- break;
- }
- case QJsonValue::Bool:
- {
- cookieString.append(key+","+QVariant(parameter.value(key).toBool()).toString());
- break;
- }
- case QJsonValue::Array:
- {
- cookieString.append(key+","+QVariant(parameter.value(key).toArray()).toString());
- break;
- }
- case QJsonValue::Object:
- {
- cookieString.append(key+","+QVariant(parameter.value(key).toObject()).toString());
- break;
- }
- case QJsonValue::Null:
- case QJsonValue::Undefined:
- break;
- }
- count++;
}
- input.headers.insert("Cookie", cookieString);
-{{/isExplode}}{{/isPrimitiveType}}{{#isPrimitiveType}}
- if (!::{{cppNamespace}}::toStringValue({{paramName}}).isEmpty()) {
- input.headers.insert("Cookie", "{{baseName}}="+::{{cppNamespace}}::toStringValue({{paramName}}));
- }
-{{/isPrimitiveType}}{{/collectionFormat}}{{#collectionFormat}}{{^isExplode}}
- QString cookieString = "{{baseName}}=";
- if ({{{paramName}}}.size() > 0) {
- qint32 count = 0;
- foreach ({{{baseType}}} t, {{paramName}}) {
- if (count > 0) {
- cookieString.append(",");
- }
- cookieString.append(::{{cppNamespace}}::toStringValue(t));
- count++;
- }
- input.headers.insert("Cookie", cookieString);
- }
-{{/isExplode}}{{/collectionFormat}}
-}
{{/cookieParams}}
foreach (QString key, this->defaultHeaders.keys()) { input.headers.insert(key, this->defaultHeaders.value(key)); }
diff --git a/modules/openapi-generator/src/main/resources/cpp-qt5-client/api-header.mustache b/modules/openapi-generator/src/main/resources/cpp-qt5-client/api-header.mustache
index 2a8b5e0f8b..ec9228f4f6 100644
--- a/modules/openapi-generator/src/main/resources/cpp-qt5-client/api-header.mustache
+++ b/modules/openapi-generator/src/main/resources/cpp-qt5-client/api-header.mustache
@@ -10,9 +10,10 @@
#include
#include
-#include
+#include
#include
#include
+#include
{{#cppNamespaceDeclarations}}
namespace {{this}} {
@@ -22,23 +23,22 @@ class {{classname}} : public QObject {
Q_OBJECT
public:
- {{classname}}(const QString &scheme = "{{scheme}}", const QString &host = "{{serverHost}}", int port = {{#serverPort}}{{serverPort}}{{/serverPort}}{{^serverPort}}0{{/serverPort}}, const QString &basePath = "{{basePathWithoutHost}}", const int timeOut = 0);
+ {{classname}}(const int timeOut = 0);
~{{classname}}();
void initializeServerConfigs();
int setDefaultServerValue(int serverIndex,const QString &operation, const QString &variable,const QString &val);
void setServerIndex(const QString &operation, int serverIndex);
- void setScheme(const QString &scheme);
- void setHost(const QString &host);
- void setPort(int port);
void setApiKey(const QString &apiKeyName, const QString &apiKey);
void setBearerToken(const QString &token);
void setUsername(const QString &username);
void setPassword(const QString &password);
- void setBasePath(const QString &basePath);
void setTimeOut(const int timeOut);
void setWorkingDirectory(const QString &path);
void setNetworkAccessManager(QNetworkAccessManager* manager);
+ int addServerConfiguration(const QString &operation, const QUrl &url, const QString &description = "", const QMap &variables = QMap());
+ void setNewServerForAllOperations(const QUrl &url, const QString &description = "", const QMap &variables = QMap());
+ void setNewServer(const QString &operation, const QUrl &url, const QString &description = "", const QMap &variables = QMap());
void addHeaders(const QString &key, const QString &value);
void enableRequestCompression();
void enableResponseCompression();
@@ -47,12 +47,20 @@ public:
QString getParamStyleSuffix(QString style);
QString getParamStyleDelimiter(QString style, QString name, bool isExplode);
{{#operations}}{{#operation}}
- void {{nickname}}({{#allParams}}const {{{dataType}}} &{{paramName}}{{^-last}}, {{/-last}}{{/allParams}});{{/operation}}{{/operations}}
+{{#hasParams}} /**
+ {{#allParams}}
+ {{#required}}
+ * @param[in] {{paramName}} {{{dataType}}} [required]
+ {{/required}}
+ {{^required}}
+ * @param[in] {{paramName}} {{{dataType}}} [optional]
+ {{/required}}
+ {{/allParams}}
+ */{{/hasParams}}
+ {{#isDeprecated}}Q_DECL_DEPRECATED {{/isDeprecated}}void {{nickname}}({{#allParams}}{{#required}}const {{{dataType}}} &{{/required}}{{^required}}const QVariant &{{/required}}{{paramName}}{{^required}} = QVariant(){{/required}}{{^-last}}, {{/-last}}{{/allParams}});
+{{/operation}}{{/operations}}
private:
- QString _scheme, _host;
- int _port;
- QString _basePath;
QMap _serverIndices;
QMap> _serverConfigs;
QMap _apiKeys;
diff --git a/modules/openapi-generator/src/main/resources/cpp-qt5-client/helpers-header.mustache b/modules/openapi-generator/src/main/resources/cpp-qt5-client/helpers-header.mustache
index 0a8e6b8b21..994ae81763 100644
--- a/modules/openapi-generator/src/main/resources/cpp-qt5-client/helpers-header.mustache
+++ b/modules/openapi-generator/src/main/resources/cpp-qt5-client/helpers-header.mustache
@@ -25,21 +25,33 @@ bool setDateTimeFormat(const QString&);
template
QString toStringValue(const QList &val);
+template
+QString toStringValue(const QSet &val);
+
template
bool fromStringValue(const QList &inStr, QList &val);
+template
+bool fromStringValue(const QSet &inStr, QList &val);
+
template
bool fromStringValue(const QMap &inStr, QMap &val);
template
QJsonValue toJsonValue(const QList &val);
+template
+QJsonValue toJsonValue(const QSet &val);
+
template
QJsonValue toJsonValue(const QMap &val);
template
bool fromJsonValue(QList &val, const QJsonValue &jval);
+template
+bool fromJsonValue(QSet &val, const QJsonValue &jval);
+
template
bool fromJsonValue(QMap &val, const QJsonValue &jval);
@@ -68,6 +80,18 @@ QString toStringValue(const QList &val) {
return strArray;
}
+template
+QString toStringValue(const QSet &val) {
+ QString strArray;
+ for (const auto &item : val) {
+ strArray.append(toStringValue(item) + ",");
+ }
+ if (val.count() > 0) {
+ strArray.chop(1);
+ }
+ return strArray;
+}
+
QJsonValue toJsonValue(const QString &value);
QJsonValue toJsonValue(const QDateTime &value);
QJsonValue toJsonValue(const QByteArray &value);
@@ -90,6 +114,15 @@ QJsonValue toJsonValue(const QList &val) {
return jArray;
}
+template
+QJsonValue toJsonValue(const QSet &val) {
+ QJsonArray jArray;
+ for (const auto &item : val) {
+ jArray.append(toJsonValue(item));
+ }
+ return jArray;
+}
+
template
QJsonValue toJsonValue(const QMap &val) {
QJsonObject jObject;
@@ -123,6 +156,17 @@ bool fromStringValue(const QList &inStr, QList &val) {
return ok;
}
+template
+bool fromStringValue(const QSet &inStr, QList &val) {
+ bool ok = (inStr.count() > 0);
+ for (const auto &item : inStr) {
+ T itemVal;
+ ok &= fromStringValue(item, itemVal);
+ val.push_back(itemVal);
+ }
+ return ok;
+}
+
template
bool fromStringValue(const QMap &inStr, QMap &val) {
bool ok = (inStr.count() > 0);
@@ -162,6 +206,21 @@ bool fromJsonValue(QList &val, const QJsonValue &jval) {
return ok;
}
+template
+bool fromJsonValue(QSet