Compare commits

..

1 Commits

Author SHA1 Message Date
William Cheng
8a7472fd1c add cpp-oatpp-server generator (alpha) 2020-11-09 18:19:23 +08:00
3275 changed files with 56564 additions and 99119 deletions

14
.gitignore vendored
View File

@@ -234,15 +234,11 @@ samples/client/petstore/erlang-proper/rebar.lock
samples/server/petstore/erlang-server/_build/
samples/server/petstore/erlang-server/rebar.lock
# Dart
**/dart*/**/.dart_tool
**/dart*/**/.packages
**/dart*/**/pubspec.lock
# Dart dio
**/dart*/**/*.g.dart
# Dart jaguar
**/dart*/**/*.jser.dart
**/dart*/**/*.jretro.dart
# dart
samples/client/petstore/dart/petstore/packages
samples/client/petstore/dart/flutter_petstore/test/packages
samples/client/petstore/dart/petstore/test/packages
**/.dart_tool
# JS
samples/client/petstore/javascript-es6/package-lock.json

View File

@@ -140,8 +140,6 @@ install:
script:
# fail fast
- set -e
# 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'
- /bin/bash ./bin/utils/detect_carriage_return.sh
# fail if generators contain merge conflicts

View File

@@ -42,7 +42,6 @@ steps:
# test java native client
- ./mvnw clean test -f samples/client/petstore/java/native/pom.xml
- ./mvnw clean test -f samples/client/petstore/java/native-async/pom.xml
- ./mvnw clean test -f samples/openapi3/client/petstore/java/native/pom.xml
# test all generators with fake petstore spec (2.0, 3.0)
- /bin/bash bin/utils/test-fake-petstore-for-all.sh
# generate test scripts

View File

@@ -30,7 +30,7 @@
:notebook_with_decorative_cover: The eBook [A Beginner's Guide to Code Generation for REST APIs](https://gum.co/openapi_generator_ebook) is a good starting point for beginners :notebook_with_decorative_cover:
:warning: If the OpenAPI spec, templates or any input (e.g. options, environment variables) is obtained from an untrusted source or environment, please make sure you've reviewed these inputs before using OpenAPI Generator to generate the API client, server stub or documentation to avoid potential security issues (e.g. [code injection](https://en.wikipedia.org/wiki/Code_injection)). For security vulnerabilities, please contact [team@openapitools.org](mailto:team@openapitools.org). :warning:
:warning: If the OpenAPI spec, templates or any input (e.g. options, environment variables) is obtained from an untrusted source or environment, please make sure you've reviewed these inputs before using OpenAPI Generator to generate the API client, server stub or documentation to avoid potential security issues (e.g. [code injection](https://en.wikipedia.org/wiki/Code_injection)) :warning:
:bangbang: Both "OpenAPI Tools" (https://OpenAPITools.org - the parent organization of OpenAPI Generator) and "OpenAPI Generator" are not affiliated with OpenAPI Initiative (OAI) :bangbang:
@@ -103,7 +103,9 @@ The OpenAPI Specification has undergone 3 revisions since initial creation in 20
| OpenAPI Generator Version | Release Date | Notes |
| --------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------ | ------------------------------------------------- |
| 5.0.0 (upcoming major release) [SNAPSHOT](https://oss.sonatype.org/content/repositories/snapshots/org/openapitools/openapi-generator-cli/5.0.0-SNAPSHOT/) | TBD | Major release with breaking changes (no fallback) |
| [5.0.0-beta3](https://github.com/OpenAPITools/openapi-generator/releases/tag/v5.0.0-beta3) (latest beta release) | 20.11.2020 | Major beta release with breaking changes (no fallback) |
| 5.0.0-beta3 (upcoming beta release) [SNAPSHOT](https://oss.sonatype.org/content/repositories/snapshots/org/openapitools/openapi-generator-cli/5.0.0-SNAPSHOT/) | 01.11.2020 | Major beta release with breaking changes (no fallback) |
| [5.0.0-beta2](https://github.com/OpenAPITools/openapi-generator/releases/tag/v5.0.0-beta2) (latest beta release) | 04.09.2020 | Major beta release with breaking changes (no fallback) |
| [5.0.0-beta](https://github.com/OpenAPITools/openapi-generator/releases/tag/v5.0.0-beta) (latest beta release) | 30.06.2020 | Major beta release with breaking changes (no fallback) |
| [4.3.1](https://github.com/OpenAPITools/openapi-generator/releases/tag/v4.3.1) (latest stable release) | 06.05.2020 | Patch release (enhancements, bug fixes, etc) |
OpenAPI Spec compatibility: 1.0, 1.1, 1.2, 2.0, 3.0
@@ -160,16 +162,16 @@ See the different versions of the [openapi-generator-cli](https://mvnrepository.
<!-- RELEASE_VERSION -->
If you're looking for the latest stable version, you can grab it directly from Maven.org (Java 8 runtime at a minimum):
JAR location: `https://repo1.maven.org/maven2/org/openapitools/openapi-generator-cli/5.0.0-beta3/openapi-generator-cli-5.0.0-beta3.jar`
JAR location: `https://repo1.maven.org/maven2/org/openapitools/openapi-generator-cli/5.0.0-beta2/openapi-generator-cli-5.0.0-beta2.jar`
For **Mac/Linux** users:
```sh
wget https://repo1.maven.org/maven2/org/openapitools/openapi-generator-cli/5.0.0-beta3/openapi-generator-cli-5.0.0-beta3.jar -O openapi-generator-cli.jar
wget https://repo1.maven.org/maven2/org/openapitools/openapi-generator-cli/5.0.0-beta2/openapi-generator-cli-5.0.0-beta2.jar -O openapi-generator-cli.jar
```
For **Windows** users, you will need to install [wget](http://gnuwin32.sourceforge.net/packages/wget.htm) or you can use Invoke-WebRequest in PowerShell (3.0+), e.g.
```
Invoke-WebRequest -OutFile openapi-generator-cli.jar https://repo1.maven.org/maven2/org/openapitools/openapi-generator-cli/5.0.0-beta3/openapi-generator-cli-5.0.0-beta3.jar
Invoke-WebRequest -OutFile openapi-generator-cli.jar https://repo1.maven.org/maven2/org/openapitools/openapi-generator-cli/5.0.0-beta2/openapi-generator-cli-5.0.0-beta2.jar
```
After downloading the JAR, run `java -jar openapi-generator-cli.jar help` to show the usage.
@@ -418,7 +420,7 @@ java -jar modules/openapi-generator-cli/target/openapi-generator-cli.jar generat
(if you're on Windows, replace the last command with `java -jar modules\openapi-generator-cli\target\openapi-generator-cli.jar generate -i https://raw.githubusercontent.com/openapitools/openapi-generator/master/modules/openapi-generator/src/test/resources/3_0/petstore.yaml -g php -o c:\temp\php_api_client`)
<!-- RELEASE_VERSION -->
You can also download the JAR (latest release) directly from [maven.org](https://repo1.maven.org/maven2/org/openapitools/openapi-generator-cli/5.0.0-beta3/openapi-generator-cli-5.0.0-beta3.jar)
You can also download the JAR (latest release) directly from [maven.org](https://repo1.maven.org/maven2/org/openapitools/openapi-generator-cli/5.0.0-beta2/openapi-generator-cli-5.0.0-beta2.jar)
<!-- /RELEASE_VERSION -->
To get a list of **general** options available, please run `java -jar modules/openapi-generator-cli/target/openapi-generator-cli.jar help generate`
@@ -610,7 +612,6 @@ Here are some companies/projects (alphabetical order) using OpenAPI Generator in
- [Kubernetes](https://kubernetes.io)
- [Linode](https://www.linode.com/)
- [Logicdrop](https://www.logicdrop.com)
- [LVM Versicherungen](https://www.lvm.de)
- [MailSlurp](https://www.mailslurp.com)
- [Médiavision](https://www.mediavision.fr/)
- [Metaswitch](https://www.metaswitch.com/)
@@ -784,8 +785,6 @@ Here are some companies/projects (alphabetical order) using OpenAPI Generator in
- 2020-09-25 - [Generate OpenAPI Angular Client](https://medium.com/@pguso/generate-openapi-angular-client-8c9288e8bbd4) by [Patric](https://medium.com/@pguso)
- 2020-10-24 - [Working with Microsoft Identity - React Native Client](https://www.josephguadagno.net/2020/10/24/working-with-microsoft-identity-react-native-client) by [Joseph Guadagno](https://www.josephguadagno.net/)
- 2020-10-31 - [[B2] OpenAPI Specification으로 타입-세이프하게 API 개발하기: 희망편 VS 절망편](https://www.youtube.com/watch?v=J4JHLESAiFk) by 최태건 at [FEConf 2020](https://2020.feconf.kr/)
- 2020-11-05 - [Automated REST-Api Code Generation: Wie IT-Systeme miteinander sprechen](https://www.massiveart.com/blog/automated-rest-api-code-generation-wie-it-systeme-miteinander-sprechen) by Stefan Rottensteiner at [MASSIVE ART Blog](https://www.massiveart.com/blog)
- 2020-12-01 - [OpenAPI GeneratorでGoのAPIサーバー/クライアントコードを自動生成する](https://qiita.com/saki-engineering/items/b20d8b6074c4da9664a5) by [@saki-engineering](https://qiita.com/saki-engineering)
## [6 - About Us](#table-of-contents)
@@ -860,7 +859,7 @@ Here is a list of template creators:
* PHP (Guzzle): @baartosz
* PowerShell: @beatcracker
* PowerShell (refactored in 5.0.0): @wing328
* Python: @spacether
* Python-experimental: @spacether
* R: @ramnov
* Ruby (Faraday): @meganemura @dkliban
* Rust: @farcaller

View File

@@ -1,6 +0,0 @@
generatorName: dart-dio
outputDir: samples/openapi3/client/petstore/dart-dio/petstore_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/dart-dio
additionalProperties:
hideGenerationTimestamp: "true"

View File

@@ -1,6 +0,0 @@
generatorName: dart-dio
outputDir: samples/openapi3/client/petstore/dart-dio/petstore_client_lib
inputSpec: modules/openapi-generator/src/test/resources/3_0/petstore.yaml
templateDir: modules/openapi-generator/src/main/resources/dart-dio
additionalProperties:
hideGenerationTimestamp: "true"

View File

@@ -1,5 +1,5 @@
generatorName: dart-dio
outputDir: samples/client/petstore/dart-dio/petstore_client_lib
outputDir: samples/client/petstore/dart-dio
inputSpec: modules/openapi-generator/src/test/resources/2_0/petstore.yaml
templateDir: modules/openapi-generator/src/main/resources/dart-dio
additionalProperties:

View File

@@ -1,6 +0,0 @@
generatorName: dart
outputDir: samples/openapi3/client/petstore/dart2/petstore_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"

View File

@@ -1,6 +0,0 @@
generatorName: dart
outputDir: samples/openapi3/client/petstore/dart2/petstore_client_lib
inputSpec: modules/openapi-generator/src/test/resources/3_0/petstore.yaml
templateDir: modules/openapi-generator/src/main/resources/dart2
additionalProperties:
hideGenerationTimestamp: "true"

View File

@@ -0,0 +1,4 @@
generatorName: cpp-oatpp-server
outputDir: samples/server/petstore/cpp-oatpp
inputSpec: modules/openapi-generator/src/test/resources/3_0/petstore.yaml
templateDir: modules/openapi-generator/src/main/resources/cpp-oatpp-server

View File

@@ -1,7 +0,0 @@
generatorName: jaxrs-cxf-client
outputDir: samples/client/petstore/jaxrs-cxf-client-jackson
inputSpec: modules/openapi-generator/src/test/resources/2_0/petstore.yaml
templateDir: modules/openapi-generator/src/main/resources/JavaJaxRS/cxf
additionalProperties:
artifactId: jaxrs-cxf-jackson-petstore-client
jackson: "true"

View File

@@ -10,7 +10,3 @@ additionalProperties:
powershellGalleryUrl: https://www.powershellgallery.com/packages/PSPetstore
apiNamePrefix: PS
powershellVersion: "5.0"
licenseUri: https://www.apache.org/licenses/LICENSE-2.0.txt
projectUri: https://github.com/OpenAPITools/openapi-generator
releaseNotes: 'This is a sample project'
tags: 'PetStore,powershell,sdk'

View File

@@ -1,7 +1,7 @@
generatorName: python-legacy
generatorName: python
outputDir: samples/client/petstore/python-asyncio
library: asyncio
inputSpec: modules/openapi-generator/src/test/resources/2_0/petstore-with-fake-endpoints-models-for-testing.yaml
templateDir: modules/openapi-generator/src/main/resources/python-legacy
templateDir: modules/openapi-generator/src/main/resources/python
additionalProperties:
packageName: petstore_api

View File

@@ -1,5 +1,5 @@
generatorName: python
outputDir: samples/openapi3/client/extensions/x-auth-id-alias/python/
generatorName: python-experimental
outputDir: samples/openapi3/client/extensions/x-auth-id-alias/python-experimental/
inputSpec: modules/openapi-generator/src/test/resources/3_0/extensions/x-auth-id-alias.yaml
templateDir: modules/openapi-generator/src/main/resources/python
additionalProperties:

View File

@@ -1,5 +1,5 @@
generatorName: python
outputDir: samples/openapi3/client/features/dynamic-servers/python/
generatorName: python-experimental
outputDir: samples/openapi3/client/features/dynamic-servers/python-experimental/
inputSpec: modules/openapi-generator/src/test/resources/3_0/features/dynamic-servers.yaml
templateDir: modules/openapi-generator/src/main/resources/python
additionalProperties:

View File

@@ -0,0 +1,7 @@
generatorName: python-experimental
outputDir: samples/client/petstore/python-experimental
inputSpec: modules/openapi-generator/src/test/resources/2_0/python-client-experimental/petstore-with-fake-endpoints-models-for-testing.yaml
templateDir: modules/openapi-generator/src/main/resources/python
additionalProperties:
disallowAdditionalPropertiesIfNotPresent: "true"
packageName: petstore_api

View File

@@ -0,0 +1,7 @@
generatorName: python-experimental
outputDir: samples/openapi3/client/petstore/python-experimental
inputSpec: modules/openapi-generator/src/test/resources/3_0/python-experimental/petstore-with-fake-endpoints-models-for-testing-with-http-signature.yaml
templateDir: modules/openapi-generator/src/main/resources/python
additionalProperties:
packageName: petstore_api
recursionLimit: "1234"

View File

@@ -1,6 +0,0 @@
generatorName: python-legacy
outputDir: samples/client/petstore/python-legacy
inputSpec: modules/openapi-generator/src/test/resources/2_0/petstore-with-fake-endpoints-models-for-testing.yaml
templateDir: modules/openapi-generator/src/main/resources/python-legacy
additionalProperties:
packageName: petstore_api

View File

@@ -1,6 +0,0 @@
generatorName: python-legacy
outputDir: samples/openapi3/client/petstore/python-legacy
inputSpec: modules/openapi-generator/src/test/resources/3_0/petstore-with-fake-endpoints-models-for-testing.yaml
templateDir: modules/openapi-generator/src/main/resources/python-legacy
additionalProperties:
packageName: petstore_api

View File

@@ -1,7 +1,6 @@
generatorName: python
outputDir: samples/client/petstore/python
inputSpec: modules/openapi-generator/src/test/resources/2_0/python-client-experimental/petstore-with-fake-endpoints-models-for-testing.yaml
inputSpec: modules/openapi-generator/src/test/resources/2_0/petstore-with-fake-endpoints-models-for-testing.yaml
templateDir: modules/openapi-generator/src/main/resources/python
additionalProperties:
disallowAdditionalPropertiesIfNotPresent: "true"
packageName: petstore_api

View File

@@ -1,7 +1,7 @@
generatorName: python-legacy
generatorName: python
outputDir: samples/client/petstore/python-tornado
library: tornado
inputSpec: modules/openapi-generator/src/test/resources/2_0/petstore-with-fake-endpoints-models-for-testing.yaml
templateDir: modules/openapi-generator/src/main/resources/python-legacy
templateDir: modules/openapi-generator/src/main/resources/python
additionalProperties:
packageName: petstore_api

View File

@@ -1,7 +1,6 @@
generatorName: python
outputDir: samples/openapi3/client/petstore/python
inputSpec: modules/openapi-generator/src/test/resources/3_0/python/petstore-with-fake-endpoints-models-for-testing-with-http-signature.yaml
inputSpec: modules/openapi-generator/src/test/resources/3_0/petstore-with-fake-endpoints-models-for-testing.yaml
templateDir: modules/openapi-generator/src/main/resources/python
additionalProperties:
packageName: petstore_api
recursionLimit: "1234"

View File

@@ -1,9 +0,0 @@
generatorName: typescript-angular
outputDir: samples/client/petstore/typescript-angular-v11-provided-in-root/builds/with-npm
inputSpec: modules/openapi-generator/src/test/resources/2_0/petstore.yaml
additionalProperties:
ngVersion: 11.0.0
npmVersion: 1.0.0
npmName: '@openapitools/typescript-angular-petstore'
npmRepository: https://skimdb.npmjs.com/registry
snapshot: false

View File

@@ -1,5 +0,0 @@
generatorName: typescript-angular
outputDir: samples/client/petstore/typescript-angular-v11-provided-in-root/builds/default
inputSpec: modules/openapi-generator/src/test/resources/2_0/petstore.yaml
additionalProperties:
ngVersion: 11.0.0

View File

@@ -1,3 +0,0 @@
generatorName: typescript-fetch
outputDir: samples/client/petstore/typescript-fetch/builds/default-v3.0
inputSpec: modules/openapi-generator/src/test/resources/3_0/petstore-with-fake-endpoints-models-for-testing.yaml

View File

@@ -1,3 +0,0 @@
generatorName: typescript-fetch
outputDir: samples/client/petstore/typescript-fetch/builds/enum
inputSpec: modules/openapi-generator/src/test/resources/3_0/typescript-fetch/enum.yaml

View File

@@ -1,9 +0,0 @@
generatorName: typescript-fetch
outputDir: samples/client/petstore/typescript-fetch/builds/without-runtime-checks
inputSpec: modules/openapi-generator/src/test/resources/2_0/petstore.yaml
additionalProperties:
npmVersion: 1.0.0
npmName: '@openapitools/typescript-fetch-petstore'
npmRepository: https://skimdb.npmjs.com/registry
withoutRuntimeChecks: true
snapshot: false

View File

@@ -1,57 +0,0 @@
#!/usr/bin/env ruby
# ruby script to detect changes in test-related files
require 'yaml'
require 'digest'
hash = Digest::SHA256.hexdigest("xyz")
filename= ARGV[0]
if !filename
puts "Usage: #{$0} filename"
exit 1
end
if !File.file? filename
warn "Error. #{filename} doesn't exist."
exit 1
end
mismatch = 0
count = 0
test_files = YAML.load_file(filename)
test_files.each do |test_file|
count = count + 1
# file still exists?
if !File.file? test_file['filename']
warn "Error. Provided test file `#{test_file['filename']}` doesn't exist."
mismatch = mismatch + 1
end
# check sha256 hash
sha256 = Digest::SHA256.hexdigest(File.read(test_file['filename']))
if test_file['sha256'] != sha256
warn "Looks like #{test_file['filename']} has been modified as its SHA256 `#{sha256}` is not the same as the one in the record: #{test_file['sha256']}"
mismatch = mismatch + 1
else
# no change to the test file
end
end
if mismatch > 0
warn "!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!"
warn "There are #{mismatch} mismatch. Please review the test files to ensure it has not been deleted/regenerated."
warn "!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!"
exit 1
else
puts "OK. All matched!"
end
if count == 0
warn "!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!"
warn "Looks like the test file list in #{filename} is empty! Please check!"
warn "!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!"
exit 1
end

View File

@@ -1,6 +0,0 @@
---
# csharp-netcore test files and image for upload
- filename: "samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/Api/PetApiTests.cs"
sha256: b74ef9eefa4b41fd3233e083fe2355babf25a77f9073d28e1aa81ae2e0a5f1d0
- filename: "samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/linux-logo.png"
sha256: 0a67c32728197e942b13bdda064b73793f12f5c795f1e5cf35a3adf69c973230

View File

@@ -48,8 +48,8 @@ The following generators are available:
* [perl](generators/perl.md)
* [php](generators/php.md)
* [powershell (beta)](generators/powershell.md)
* [python (experimental)](generators/python.md)
* [python-legacy](generators/python-legacy.md)
* [python](generators/python.md)
* [python-experimental (experimental)](generators/python-experimental.md)
* [r](generators/r.md)
* [ruby](generators/ruby.md)
* [rust](generators/rust.md)

View File

@@ -40,8 +40,8 @@ The following generators are available:
* [perl](perl.md)
* [php](php.md)
* [powershell](powershell.md)
* [python](python.md)
* [python-legacy](python-legacy.md)
* [python](python.md)
* [python-experimental (experimental)](python-experimental.md)
* [r](r.md)
* [ruby](ruby.md)
* [rust](rust.md)

View File

@@ -32,7 +32,6 @@ These options may be applied as additional-properties (cli) or configOptions (pl
| ---------- | ------- |
|BuiltList|package:built_collection/built_collection.dart|
|BuiltMap|package:built_collection/built_collection.dart|
|BuiltSet|package:built_collection/built_collection.dart|
|JsonObject|package:built_value/json_object.dart|
|Uint8List|dart:typed_data|

View File

@@ -15,11 +15,6 @@ These options may be applied as additional-properties (cli) or configOptions (pl
| Type/Alias | Imports |
| ---------- | ------- |
|File|FILE|
|List|LIST|
|Map|STRING_TABLE|
|Set|SET|
|file|FILE|
## INSTANTIATION TYPES
@@ -57,7 +52,6 @@ These options may be applied as additional-properties (cli) or configOptions (pl
<li>and</li>
<li>as</li>
<li>assign</li>
<li>attached</li>
<li>attribute</li>
<li>check</li>
<li>class</li>
@@ -66,7 +60,6 @@ These options may be applied as additional-properties (cli) or configOptions (pl
<li>current</li>
<li>debug</li>
<li>deferred</li>
<li>detachable</li>
<li>do</li>
<li>else</li>
<li>elseif</li>

View File

@@ -52,7 +52,6 @@ These options may be applied as additional-properties (cli) or configOptions (pl
|sortModelPropertiesByRequiredFlag|Sort model properties to place required parameters before optional parameters.| |true|
|sortParamsByRequiredFlag|Sort method arguments to place required parameters before optional parameters.| |true|
|sourceFolder|source folder for generated code| |/app|
|supportAsync|Support Async operations| |false|
|title|server title name or client service name| |openapi-java-playframework|
|useBeanValidation|Use BeanValidation API annotations| |true|
|useInterfaces|Makes the controllerImp implements an interface to facilitate automatic completion when updating from version x to y of your spec| |true|

View File

@@ -11,15 +11,10 @@ These options may be applied as additional-properties (cli) or configOptions (pl
|commonVerbs|PS common verb mappings. e.g. Delete=Remove:Patch=Update to map Delete with Remove and Patch with Update accordingly.| |null|
|disallowAdditionalPropertiesIfNotPresent|Specify the behavior when the 'additionalProperties' keyword is not present in the OAS document. If false: the 'additionalProperties' implementation is compliant with the OAS and JSON schema specifications. If true: when the 'additionalProperties' keyword is not present in a schema, the value of 'additionalProperties' is set to false, i.e. no additional properties are allowed. Note: this mode is not compliant with the JSON schema specification. This is the original openapi-generator behavior.This setting is currently ignored for OAS 2.0 documents: 1) When the 'additionalProperties' keyword is not present in a 2.0 schema, additional properties are NOT allowed. 2) Boolean values of the 'additionalProperties' keyword are ignored. It's as if additional properties are NOT allowed.Note: the root cause are issues #1369 and #1371, which must be resolved in the swagger-parser project.|<dl><dt>**false**</dt><dd>The 'additionalProperties' implementation is compliant with the OAS and JSON schema specifications.</dd><dt>**true**</dt><dd>when the 'additionalProperties' keyword is not present in a schema, the value of 'additionalProperties' is automatically set to false, i.e. no additional properties are allowed. Note: this mode is not compliant with the JSON schema specification. This is the original openapi-generator behavior.</dd></dl>|true|
|discardReadOnly|Set discardReadonly to true to generate the Initialize cmdlet without readonly parameters| |null|
|iconUri|A URL to an icon representing the generated PowerShell module| |null|
|licenseUri|A URL to the license for the generated PowerShell module| |null|
|packageGuid|GUID for PowerShell module (e.g. a27b908d-2a20-467f-bc32-af6f3a654ac5). A random GUID will be generated by default.| |null|
|packageName|Client package name (e.g. PSTwitter).| |PSOpenAPITools|
|packageVersion|Package version (e.g. 0.1.2).| |0.1.2|
|powershellGalleryUrl|URL to the module in PowerShell Gallery (e.g. https://www.powershellgallery.com/packages/PSTwitter/).| |null|
|projectUri|A URL to the main website for this project| |null|
|releaseNotes|Release notes of the generated PowerShell module| |null|
|tags|Tags applied to the generated PowerShell module. These help with module discovery in online galleries| |null|
|useOneOfDiscriminatorLookup|Use the discriminator's mapping in oneOf to speed up the model lookup. IMPORTANT: Validation (e.g. one and onlye one match in oneOf's schemas) will be skipped.| |null|
## IMPORT MAPPING

View File

@@ -1,6 +1,6 @@
---
title: Config Options for python-legacy
sidebar_label: python-legacy
title: Config Options for python-experimental
sidebar_label: python-experimental
---
These options may be applied as additional-properties (cli) or configOptions (plugins). Refer to [configuration docs](https://openapi-generator.tech/docs/configuration) for more details.
@@ -14,8 +14,8 @@ These options may be applied as additional-properties (cli) or configOptions (pl
|packageUrl|python package URL.| |null|
|packageVersion|python package version.| |1.0.0|
|projectName|python project name in setup.py (e.g. petstore-api).| |null|
|pythonAttrNoneIfUnset|when accessing unset attribute, return `None` instead of raising `ApiAttributeError`| |false|
|recursionLimit|Set the recursion limit. If not set, use the system default value.| |null|
|sortParamsByRequiredFlag|Sort method arguments to place required parameters before optional parameters.| |true|
|useNose|use the nose test framework| |false|
## IMPORT MAPPING
@@ -28,6 +28,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl
| Type/Alias | Instantiated By |
| ---------- | --------------- |
|map|dict|
## LANGUAGE PRIMITIVES
@@ -39,9 +40,11 @@ These options may be applied as additional-properties (cli) or configOptions (pl
<li>datetime</li>
<li>dict</li>
<li>file</li>
<li>file_type</li>
<li>float</li>
<li>int</li>
<li>list</li>
<li>none_type</li>
<li>object</li>
<li>str</li>
</ul>
@@ -164,7 +167,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl
|Examples|✓|OAS2,OAS3
|XMLStructureDefinitions|✗|OAS2,OAS3
|MultiServer|✗|OAS3
|ParameterizedServer||OAS3
|ParameterizedServer||OAS3
|ParameterStyling|✗|OAS3
|Callbacks|✗|OAS3
|LinkObjects|✗|OAS3

View File

@@ -14,8 +14,8 @@ These options may be applied as additional-properties (cli) or configOptions (pl
|packageUrl|python package URL.| |null|
|packageVersion|python package version.| |1.0.0|
|projectName|python project name in setup.py (e.g. petstore-api).| |null|
|pythonAttrNoneIfUnset|when accessing unset attribute, return `None` instead of raising `ApiAttributeError`| |false|
|recursionLimit|Set the recursion limit. If not set, use the system default value.| |null|
|sortParamsByRequiredFlag|Sort method arguments to place required parameters before optional parameters.| |true|
|useNose|use the nose test framework| |false|
## IMPORT MAPPING
@@ -28,7 +28,6 @@ These options may be applied as additional-properties (cli) or configOptions (pl
| Type/Alias | Instantiated By |
| ---------- | --------------- |
|map|dict|
## LANGUAGE PRIMITIVES
@@ -40,11 +39,9 @@ These options may be applied as additional-properties (cli) or configOptions (pl
<li>datetime</li>
<li>dict</li>
<li>file</li>
<li>file_type</li>
<li>float</li>
<li>int</li>
<li>list</li>
<li>none_type</li>
<li>object</li>
<li>str</li>
</ul>
@@ -167,7 +164,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl
|Examples|✓|OAS2,OAS3
|XMLStructureDefinitions|✗|OAS2,OAS3
|MultiServer|✗|OAS3
|ParameterizedServer||OAS3
|ParameterizedServer||OAS3
|ParameterStyling|✗|OAS3
|Callbacks|✗|OAS3
|LinkObjects|✗|OAS3

View File

@@ -16,6 +16,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl
| Type/Alias | Imports |
| ---------- | ------- |
|ArrayBuffer|scala.collection.mutable.ArrayBuffer|
|BigDecimal|java.math.BigDecimal|
|Date|java.util.Date|
|DateTime|java.time.LocalDateTime|
|File|java.io.File|

View File

@@ -26,6 +26,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl
| ---------- | ------- |
|Array|java.util.List|
|ArrayList|java.util.ArrayList|
|BigDecimal|java.math.BigDecimal|
|Date|java.util.Date|
|DateTime|org.joda.time.DateTime|
|File|java.io.File|

View File

@@ -19,7 +19,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl
|modelFileSuffix|The suffix of the file of the generated model (model&lt;suffix&gt;.ts).| |null|
|modelPropertyNaming|Naming convention for the property: 'camelCase', 'PascalCase', 'snake_case' and 'original', which keeps the original name. Only change it if you provide your own run-time code for (de-)serialization of models| |original|
|modelSuffix|The suffix of the generated model.| |null|
|ngVersion|The version of Angular. (At least 6.0.0)| |11.0.0|
|ngVersion|The version of Angular. (At least 6.0.0)| |10.0.0|
|npmName|The name under which you want to publish generated npm package. Required to generate a full package| |null|
|npmRepository|Use this property to set an url your private npmRepo in the package.json| |null|
|npmVersion|The version of your npm package. If not provided, using the version from the OpenAPI specification file.| |1.0.0|

View File

@@ -27,7 +27,6 @@ These options may be applied as additional-properties (cli) or configOptions (pl
|typescriptThreePlus|Setting this property to true will generate TypeScript 3.6+ compatible code.| |false|
|useSingleRequestParameter|Setting this property to true will generate functions with a single argument containing all API endpoint parameters instead of one argument per parameter.| |true|
|withInterfaces|Setting this property to true will generate interfaces next to the default class implementations.| |false|
|withoutRuntimeChecks|Setting this property to true will remove any runtime checks on the request and response payloads. Payloads will be casted to their expected types.| |false|
## IMPORT MAPPING

View File

@@ -150,9 +150,9 @@ public interface CodegenConfig {
Map<String, String> reservedWordsMappings();
void preprocessOpenAPI();
void preprocessOpenAPI(OpenAPI openAPI);
void processOpenAPI();
void processOpenAPI(OpenAPI openAPI);
Compiler processCompiler(Compiler compiler);

View File

@@ -2,7 +2,7 @@ package org.openapitools.codegen;
import org.apache.commons.lang3.builder.ToStringBuilder;
import java.util.TreeSet;
import java.util.LinkedHashSet;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
@@ -25,14 +25,14 @@ public class CodegenDiscriminator {
private String propertyType;
private Map<String, String> mapping;
// mappedModels is populated differently if legacyDiscriminatorBehavior is
// mappedModels is populated differently if discriminatorExplicitMappingVerbose is
// True or False. When:
//
// legacyDiscriminatorBehavior == False, this contains:
// discriminatorExplicitMappingVerbose == False, this contains:
// - the name to schema map info in the discriminator mapping entry in your openapi spec OR
// - child schemas that allOf inherit self schema
//
// legacyDiscriminatorBehavior == True, this contains:
// discriminatorExplicitMappingVerbose == True, this contains:
// - the name to schema map info in the discriminMappedModelator mapping entry in your openapi spec AND
// - x-discriminator-value mappings in child oneOf + anyOf schemas + descendant schemas that allOf inherit self schema AND
// - descendant schemas that allOf inherit self schema AND
@@ -40,7 +40,7 @@ public class CodegenDiscriminator {
//
// see the method createDiscriminator in DefaultCodegen.java
private Set<MappedModel> mappedModels = new TreeSet<>();
private Set<MappedModel> mappedModels = new LinkedHashSet<>();
public String getPropertyName() {
return propertyName;

View File

@@ -111,8 +111,8 @@ public class CodegenProperty implements Cloneable, IJsonSchemaValidationProperti
/**
* True if this property is an array of items or a map container.
* See:
* - modelUtils.isArraySchema()
* - modelUtils.isMapSchema()
* - ModelUtils.isArraySchema()
* - ModelUtils.isMapSchema()
*/
public boolean isContainer;
public boolean isString;

View File

@@ -86,8 +86,7 @@ public class CodegenResponse implements IJsonSchemaValidationProperties {
isMap, isArray, isBinary, isFile, schema, jsonSchema, vendorExtensions, items, additionalProperties,
vars, requiredVars,
getMaxProperties(), getMinProperties(), uniqueItems, getMaxItems(), getMinItems(), getMaxLength(),
getMinLength(), exclusiveMinimum, exclusiveMaximum, getMinimum(), getMaximum(), getPattern(),
is1xx, is2xx, is3xx, is4xx, is5xx);
getMinLength(), exclusiveMinimum, exclusiveMaximum, getMinimum(), getMaximum(), getPattern());
}
@Override
@@ -122,11 +121,6 @@ public class CodegenResponse implements IJsonSchemaValidationProperties {
isFile == that.isFile &&
items == that.items &&
additionalProperties == that.additionalProperties &&
is1xx == that.is1xx &&
is2xx == that.is2xx &&
is3xx == that.is3xx &&
is4xx == that.is4xx &&
is5xx == that.is5xx &&
Objects.equals(vars, that.vars) &&
Objects.equals(requiredVars, that.requiredVars) &&
Objects.equals(headers, that.headers) &&
@@ -368,11 +362,6 @@ public class CodegenResponse implements IJsonSchemaValidationProperties {
final StringBuilder sb = new StringBuilder("CodegenResponse{");
sb.append("headers=").append(headers);
sb.append(", code='").append(code).append('\'');
sb.append(", is1xx='").append(is1xx).append('\'');
sb.append(", is2xx='").append(is2xx).append('\'');
sb.append(", is3xx='").append(is3xx).append('\'');
sb.append(", is4xx='").append(is4xx).append('\'');
sb.append(", is5xx='").append(is5xx).append('\'');
sb.append(", message='").append(message).append('\'');
sb.append(", examples=").append(examples);
sb.append(", dataType='").append(dataType).append('\'');
@@ -432,15 +421,4 @@ public class CodegenResponse implements IJsonSchemaValidationProperties {
public boolean isWildcard() {
return "0".equals(code) || "default".equals(code);
}
/*
* Boolean value indicating whether the status code is a range
*
* @return True if the status code is a range (e.g. 2XX)
*/
public boolean isRange() {
if (code != null && code.length() == 3 && "XX".equalsIgnoreCase(code.substring(1)))
return true;
return false;
}
}

View File

@@ -18,7 +18,6 @@
package org.openapitools.codegen;
import com.google.common.collect.ImmutableList;
import io.swagger.models.Model;
import io.swagger.v3.core.util.Json;
import io.swagger.v3.oas.models.OpenAPI;
import io.swagger.v3.oas.models.Operation;
@@ -42,7 +41,7 @@ import org.openapitools.codegen.config.GlobalSettings;
import org.openapitools.codegen.api.TemplatingEngineAdapter;
import org.openapitools.codegen.api.TemplateFileType;
import org.openapitools.codegen.ignore.CodegenIgnoreProcessor;
import org.openapitools.codegen.languages.PythonClientCodegen;
import org.openapitools.codegen.languages.PythonClientExperimentalCodegen;
import org.openapitools.codegen.meta.GeneratorMetadata;
import org.openapitools.codegen.meta.Stability;
import org.openapitools.codegen.serializer.SerializerUtils;
@@ -77,7 +76,6 @@ public class DefaultGenerator implements Generator {
protected CodegenConfig config;
protected ClientOptInput opts;
protected OpenAPI openAPI;
protected ModelUtils modelUtils;
protected CodegenIgnoreProcessor ignoreProcessor;
private Boolean generateApis = null;
private Boolean generateModels = null;
@@ -110,10 +108,7 @@ public class DefaultGenerator implements Generator {
public Generator opts(ClientOptInput opts) {
this.opts = opts;
this.openAPI = opts.getOpenAPI();
this.modelUtils = new ModelUtils(openAPI);
this.config = opts.getConfig();
this.config.setOpenAPI(this.openAPI);
List<TemplateDefinition> userFiles = opts.getUserDefinedTemplates();
if (userFiles != null) {
this.userDefinedTemplates = ImmutableList.copyOf(userFiles);
@@ -157,10 +152,6 @@ public class DefaultGenerator implements Generator {
return this;
}
public ModelUtils getModelUtils() {
return modelUtils;
}
/**
* Retrieves an instance to the configured template processor, available after user-defined options are
* applied via {@link DefaultGenerator#opts(ClientOptInput)}.
@@ -257,7 +248,10 @@ public class DefaultGenerator implements Generator {
}
config.processOpts();
config.preprocessOpenAPI();
config.preprocessOpenAPI(openAPI);
// set OpenAPI to make these available to all methods
config.setOpenAPI(openAPI);
config.additionalProperties().put("generatorVersion", ImplementationVersion.read());
config.additionalProperties().put("generatedDate", ZonedDateTime.now().toString());
@@ -403,7 +397,7 @@ public class DefaultGenerator implements Generator {
return;
}
final Map<String, Schema> schemas = modelUtils.getSchemas();
final Map<String, Schema> schemas = ModelUtils.getSchemas(this.openAPI);
if (schemas == null) {
LOGGER.warn("Skipping generation of models because specification document has no schemas.");
return;
@@ -464,7 +458,7 @@ public class DefaultGenerator implements Generator {
Schema schema = schemas.get(name);
if (modelUtils.isFreeFormObject(schema)) { // check to see if it'a a free-form object
if (ModelUtils.isFreeFormObject(this.openAPI, schema)) { // check to see if it'a a free-form object
// there are 3 free form use cases
// 1. free form with no validation that is not allOf included in any composed schemas
// 2. free form with validation
@@ -478,17 +472,17 @@ public class DefaultGenerator implements Generator {
LOGGER.info("Model {} not generated since it's a free-form object", name);
continue;
}
} else if (modelUtils.isMapSchema(schema)) { // check to see if it's a "map" model
} else if (ModelUtils.isMapSchema(schema)) { // check to see if it's a "map" model
// A composed schema (allOf, oneOf, anyOf) is considered a Map schema if the additionalproperties attribute is set
// for that composed schema. However, in the case of a composed schema, the properties are defined or referenced
// in the inner schemas, and the outer schema does not have properties.
if (!modelUtils.isGenerateAliasAsModel(schema) && !modelUtils.isComposedSchema(schema) && (schema.getProperties() == null || schema.getProperties().isEmpty())) {
if (!ModelUtils.isGenerateAliasAsModel(schema) && !ModelUtils.isComposedSchema(schema) && (schema.getProperties() == null || schema.getProperties().isEmpty())) {
// schema without property, i.e. alias to map
LOGGER.info("Model {} not generated since it's an alias to map (without property) and `generateAliasAsModel` is set to false (default)", name);
continue;
}
} else if (modelUtils.isArraySchema(schema)) { // check to see if it's an "array" model
if (!modelUtils.isGenerateAliasAsModel(schema) && (schema.getProperties() == null || schema.getProperties().isEmpty())) {
} else if (ModelUtils.isArraySchema(schema)) { // check to see if it's an "array" model
if (!ModelUtils.isGenerateAliasAsModel(schema) && (schema.getProperties() == null || schema.getProperties().isEmpty())) {
// schema without property, i.e. alias to array
LOGGER.info("Model {} not generated since it's an alias to array (without property) and `generateAliasAsModel` is set to false (default)", name);
continue;
@@ -526,9 +520,9 @@ public class DefaultGenerator implements Generator {
Map<String, Object> modelTemplate = (Map<String, Object>) ((List<Object>) models.get("models")).get(0);
if (modelTemplate != null && modelTemplate.containsKey("model")) {
CodegenModel m = (CodegenModel) modelTemplate.get("model");
if (m.isAlias && !(config instanceof PythonClientCodegen)) {
if (m.isAlias && !(config instanceof PythonClientExperimentalCodegen)) {
// alias to number, string, enum, etc, which should not be generated as model
// for PythonClientCodegen, all aliases are generated as models
// for PythonClientExperimentalCodegen, all aliases are generated as models
continue; // Don't create user-defined classes for aliases
}
}
@@ -775,7 +769,7 @@ public class DefaultGenerator implements Generator {
bundle.put("basePathWithoutHost", basePathWithoutHost);
bundle.put("scheme", URLPathUtils.getScheme(url, config));
bundle.put("host", url.getHost());
if (url.getPort() != 80 && url.getPort() != 443 && url.getPort() != -1) {
if (url.getPort() != 80 && url.getPort() != 443 ) {
bundle.put("port", url.getPort());
}
bundle.put("contextPath", contextPath);
@@ -862,19 +856,19 @@ public class DefaultGenerator implements Generator {
}
// resolve inline models
InlineModelResolver inlineModelResolver = new InlineModelResolver(openAPI);
inlineModelResolver.flatten();
InlineModelResolver inlineModelResolver = new InlineModelResolver();
inlineModelResolver.flatten(openAPI);
configureGeneratorProperties();
configureOpenAPIInfo();
config.processOpenAPI();
config.processOpenAPI(openAPI);
processUserDefinedTemplates();
List<File> files = new ArrayList<>();
// models
List<String> filteredSchemas = modelUtils.getSchemasUsedOnlyInFormParam();
List<String> filteredSchemas = ModelUtils.getSchemasUsedOnlyInFormParam(openAPI);
List<Object> allModels = new ArrayList<>();
generateModels(files, allModels, filteredSchemas);
// apis

View File

@@ -38,8 +38,7 @@ import java.util.*;
import java.util.stream.Collectors;
public class InlineModelResolver {
private OpenAPI openAPI;
private ModelUtils modelUtils;
private OpenAPI openapi;
private Map<String, Schema> addedModels = new HashMap<String, Schema>();
private Map<String, String> generatedSignature = new HashMap<String, String>();
@@ -55,36 +54,27 @@ public class InlineModelResolver {
static final Logger LOGGER = LoggerFactory.getLogger(InlineModelResolver.class);
public InlineModelResolver(OpenAPI openAPI) {
this.openAPI = openAPI;
this.modelUtils = new ModelUtils(openAPI);
}
void flatten(OpenAPI openapi) {
this.openapi = openapi;
public OpenAPI getOpenAPI() {
return this.openAPI;
}
public ModelUtils getModelUtils() {
return this.modelUtils;
}
void flatten() {
if (openAPI.getComponents() == null) {
openAPI.setComponents(new Components());
if (openapi.getComponents() == null) {
openapi.setComponents(new Components());
}
if (openAPI.getComponents().getSchemas() == null) {
openAPI.getComponents().setSchemas(new HashMap<String, Schema>());
if (openapi.getComponents().getSchemas() == null) {
openapi.getComponents().setSchemas(new HashMap<String, Schema>());
}
flattenPaths();
flattenComponents();
flattenPaths(openapi);
flattenComponents(openapi);
}
/**
* Flatten inline models in Paths
*
* @param openAPI target spec
*/
private void flattenPaths() {
private void flattenPaths(OpenAPI openAPI) {
Paths paths = openAPI.getPaths();
if (paths == null) {
return;
@@ -106,9 +96,9 @@ public class InlineModelResolver {
}
for (Operation operation : operations) {
flattenRequestBody(pathname, operation);
flattenParameters(pathname, operation);
flattenResponses(pathname, operation);
flattenRequestBody(openAPI, pathname, operation);
flattenParameters(openAPI, pathname, operation);
flattenResponses(openAPI, pathname, operation);
}
}
}
@@ -116,21 +106,22 @@ public class InlineModelResolver {
/**
* Flatten inline models in RequestBody
*
* @param pathname target pathname
* @param openAPI target spec
* @param pathname target pathname
* @param operation target operation
*/
private void flattenRequestBody(String pathname, Operation operation) {
private void flattenRequestBody(OpenAPI openAPI, String pathname, Operation operation) {
RequestBody requestBody = operation.getRequestBody();
if (requestBody == null) {
return;
}
Schema model = modelUtils.getSchemaFromRequestBody(requestBody);
Schema model = ModelUtils.getSchemaFromRequestBody(requestBody);
if (model instanceof ObjectSchema) {
Schema obj = (Schema) model;
if (obj.getType() == null || "object".equals(obj.getType())) {
if (obj.getProperties() != null && obj.getProperties().size() > 0) {
flattenProperties(obj.getProperties(), pathname);
flattenProperties(openAPI, obj.getProperties(), pathname);
// for model name, use "title" if defined, otherwise default to 'inline_object'
String modelName = resolveModelName(obj.getTitle(), "inline_object");
addGenerated(modelName, model);
@@ -172,6 +163,7 @@ public class InlineModelResolver {
// update requestBody to use $ref instead of inline def
requestBody.set$ref(modelName);
}
}
} else if (model instanceof ArraySchema) {
@@ -180,10 +172,10 @@ public class InlineModelResolver {
if (inner instanceof ObjectSchema) {
ObjectSchema op = (ObjectSchema) inner;
if (op.getProperties() != null && op.getProperties().size() > 0) {
flattenProperties(op.getProperties(), pathname);
flattenProperties(openAPI, op.getProperties(), pathname);
// Generate a unique model name based on the title.
String modelName = resolveModelName(op.getTitle(), null);
Schema innerModel = modelFromProperty(op, modelName);
Schema innerModel = modelFromProperty(openAPI, op, modelName);
String existing = matchGenerated(innerModel);
if (existing != null) {
Schema schema = new Schema().$ref(existing);
@@ -204,10 +196,11 @@ public class InlineModelResolver {
/**
* Flatten inline models in parameters
*
* @param pathname target pathname
* @param openAPI target spec
* @param pathname target pathname
* @param operation target operation
*/
private void flattenParameters(String pathname, Operation operation) {
private void flattenParameters(OpenAPI openAPI, String pathname, Operation operation) {
List<Parameter> parameters = operation.getParameters();
if (parameters == null) {
return;
@@ -223,7 +216,7 @@ public class InlineModelResolver {
Schema obj = (Schema) model;
if (obj.getType() == null || "object".equals(obj.getType())) {
if (obj.getProperties() != null && obj.getProperties().size() > 0) {
flattenProperties(obj.getProperties(), pathname);
flattenProperties(openAPI, obj.getProperties(), pathname);
String modelName = resolveModelName(obj.getTitle(), parameter.getName());
parameter.$ref(modelName);
@@ -237,9 +230,9 @@ public class InlineModelResolver {
if (inner instanceof ObjectSchema) {
ObjectSchema op = (ObjectSchema) inner;
if (op.getProperties() != null && op.getProperties().size() > 0) {
flattenProperties(op.getProperties(), pathname);
flattenProperties(openAPI, op.getProperties(), pathname);
String modelName = resolveModelName(op.getTitle(), parameter.getName());
Schema innerModel = modelFromProperty(op, modelName);
Schema innerModel = modelFromProperty(openAPI, op, modelName);
String existing = matchGenerated(innerModel);
if (existing != null) {
Schema schema = new Schema().$ref(existing);
@@ -261,10 +254,11 @@ public class InlineModelResolver {
/**
* Flatten inline models in ApiResponses
*
* @param pathname target pathname
* @param openAPI target spec
* @param pathname target pathname
* @param operation target operation
*/
private void flattenResponses(String pathname, Operation operation) {
private void flattenResponses(OpenAPI openAPI, String pathname, Operation operation) {
ApiResponses responses = operation.getResponses();
if (responses == null) {
return;
@@ -272,16 +266,16 @@ public class InlineModelResolver {
for (String key : responses.keySet()) {
ApiResponse response = responses.get(key);
if (modelUtils.getSchemaFromResponse(response) == null) {
if (ModelUtils.getSchemaFromResponse(response) == null) {
continue;
}
Schema property = modelUtils.getSchemaFromResponse(response);
Schema property = ModelUtils.getSchemaFromResponse(response);
if (property instanceof ObjectSchema) {
ObjectSchema op = (ObjectSchema) property;
if (op.getProperties() != null && op.getProperties().size() > 0) {
String modelName = resolveModelName(op.getTitle(), "inline_response_" + key);
Schema model = modelFromProperty(op, modelName);
Schema model = modelFromProperty(openAPI, op, modelName);
String existing = matchGenerated(model);
Content content = response.getContent();
for (MediaType mediaType : content.values()) {
@@ -304,10 +298,10 @@ public class InlineModelResolver {
if (inner instanceof ObjectSchema) {
ObjectSchema op = (ObjectSchema) inner;
if (op.getProperties() != null && op.getProperties().size() > 0) {
flattenProperties(op.getProperties(), pathname);
flattenProperties(openAPI, op.getProperties(), pathname);
String modelName = resolveModelName(op.getTitle(),
"inline_response_" + key);
Schema innerModel = modelFromProperty(op, modelName);
Schema innerModel = modelFromProperty(openAPI, op, modelName);
String existing = matchGenerated(innerModel);
if (existing != null) {
Schema schema = this.makeSchema(existing, op);
@@ -324,14 +318,14 @@ public class InlineModelResolver {
}
} else if (property instanceof MapSchema) {
MapSchema mp = (MapSchema) property;
Schema innerProperty = modelUtils.getAdditionalProperties(mp);
Schema innerProperty = ModelUtils.getAdditionalProperties(openAPI, mp);
if (innerProperty instanceof ObjectSchema) {
ObjectSchema op = (ObjectSchema) innerProperty;
if (op.getProperties() != null && op.getProperties().size() > 0) {
flattenProperties(op.getProperties(), pathname);
flattenProperties(openAPI, op.getProperties(), pathname);
String modelName = resolveModelName(op.getTitle(),
"inline_response_" + key);
Schema innerModel = modelFromProperty(op, modelName);
Schema innerModel = modelFromProperty(openAPI, op, modelName);
String existing = matchGenerated(innerModel);
if (existing != null) {
Schema schema = new Schema().$ref(existing);
@@ -354,29 +348,30 @@ public class InlineModelResolver {
* Flattens properties of inline object schemas that belong to a composed schema into a
* single flat list of properties. This is useful to generate a single or multiple
* inheritance model.
* <p>
*
* In the example below, codegen may generate a 'Dog' class that extends from the
* generated 'Animal' class. 'Dog' has additional properties 'name', 'age' and 'breed' that
* are flattened as a single list of properties.
* <p>
* Dog:
* allOf:
* - $ref: '#/components/schemas/Animal'
* - type: object
* properties:
* name:
* type: string
* age:
* type: string
* - type: object
* properties:
* breed:
* type: string
*
* @param key a unique name ofr the composed schema.
* Dog:
* allOf:
* - $ref: '#/components/schemas/Animal'
* - type: object
* properties:
* name:
* type: string
* age:
* type: string
* - type: object
* properties:
* breed:
* type: string
*
* @param openAPI the OpenAPI document
* @param key a unique name ofr the composed schema.
* @param children the list of nested schemas within a composed schema (allOf, anyOf, oneOf).
*/
private void flattenComposedChildren(String key, List<Schema> children) {
private void flattenComposedChildren(OpenAPI openAPI, String key, List<Schema> children) {
if (children == null || children.isEmpty()) {
return;
}
@@ -399,7 +394,7 @@ public class InlineModelResolver {
// To have complete control of the model naming, one can define the model separately
// instead of inline.
String innerModelName = resolveModelName(op.getTitle(), key);
Schema innerModel = modelFromProperty(op, innerModelName);
Schema innerModel = modelFromProperty(openAPI, op, innerModelName);
String existing = matchGenerated(innerModel);
if (existing == null) {
openAPI.getComponents().addSchemas(innerModelName, innerModel);
@@ -421,8 +416,10 @@ public class InlineModelResolver {
/**
* Flatten inline models in components
*
* @param openAPI target spec
*/
private void flattenComponents() {
private void flattenComponents(OpenAPI openAPI) {
Map<String, Schema> models = openAPI.getComponents().getSchemas();
if (models == null) {
return;
@@ -431,25 +428,25 @@ public class InlineModelResolver {
List<String> modelNames = new ArrayList<String>(models.keySet());
for (String modelName : modelNames) {
Schema model = models.get(modelName);
if (modelUtils.isComposedSchema(model)) {
if (ModelUtils.isComposedSchema(model)) {
ComposedSchema m = (ComposedSchema) model;
// inline child schemas
flattenComposedChildren(modelName + "_allOf", m.getAllOf());
flattenComposedChildren(modelName + "_anyOf", m.getAnyOf());
flattenComposedChildren(modelName + "_oneOf", m.getOneOf());
flattenComposedChildren(openAPI, modelName + "_allOf", m.getAllOf());
flattenComposedChildren(openAPI, modelName + "_anyOf", m.getAnyOf());
flattenComposedChildren(openAPI, modelName + "_oneOf", m.getOneOf());
} else if (model instanceof Schema) {
Schema m = (Schema) model;
Map<String, Schema> properties = m.getProperties();
flattenProperties(properties, modelName);
flattenProperties(openAPI, properties, modelName);
fixStringModel(m);
} else if (modelUtils.isArraySchema(model)) {
} else if (ModelUtils.isArraySchema(model)) {
ArraySchema m = (ArraySchema) model;
Schema inner = m.getItems();
if (inner instanceof ObjectSchema) {
ObjectSchema op = (ObjectSchema) inner;
if (op.getProperties() != null && op.getProperties().size() > 0) {
String innerModelName = resolveModelName(op.getTitle(), modelName + "_inner");
Schema innerModel = modelFromProperty(op, innerModelName);
Schema innerModel = modelFromProperty(openAPI, op, innerModelName);
String existing = matchGenerated(innerModel);
if (existing == null) {
openAPI.getComponents().addSchemas(innerModelName, innerModel);
@@ -486,11 +483,12 @@ public class InlineModelResolver {
/**
* Generates a unique model name. Non-alphanumeric characters will be replaced
* with underscores
* <p>
*
* e.g. io.schema.User_name => io_schema_User_name
*
* @param title String title field in the schema if present
* @param key String model name
* @param key String model name
*
* @return if provided the sanitized {@code title}, else the sanitized {@code key}
*/
private String resolveModelName(String title, String key) {
@@ -529,24 +527,24 @@ public class InlineModelResolver {
/**
* Sanitizes the input so that it's valid name for a class or interface
* <p>
*
* e.g. 12.schema.User name => _2_schema_User_name
*/
private String sanitizeName(final String name) {
return name
.replaceAll("^[0-9]", "_") // e.g. 12object => _2object
.replaceAll("[^A-Za-z0-9]", "_"); // e.g. io.schema.User name => io_schema_User_name
.replaceAll("^[0-9]", "_") // e.g. 12object => _2object
.replaceAll("[^A-Za-z0-9]", "_"); // e.g. io.schema.User name => io_schema_User_name
}
private String uniqueName(final String name) {
if (openAPI.getComponents().getSchemas() == null) {
if (openapi.getComponents().getSchemas() == null) {
return name;
}
String uniqueName = name;
int count = 0;
while (true) {
if (!openAPI.getComponents().getSchemas().containsKey(uniqueName)) {
if (!openapi.getComponents().getSchemas().containsKey(uniqueName)) {
return uniqueName;
}
uniqueName = name + "_" + ++count;
@@ -554,7 +552,7 @@ public class InlineModelResolver {
// TODO it would probably be a good idea to check against a list of used uniqueNames to make sure there are no collisions
}
private void flattenProperties(Map<String, Schema> properties, String path) {
private void flattenProperties(OpenAPI openAPI, Map<String, Schema> properties, String path) {
if (properties == null) {
return;
}
@@ -566,7 +564,7 @@ public class InlineModelResolver {
&& ((ObjectSchema) property).getProperties().size() > 0) {
ObjectSchema op = (ObjectSchema) property;
String modelName = resolveModelName(op.getTitle(), path + "_" + key);
Schema model = modelFromProperty(op, modelName);
Schema model = modelFromProperty(openAPI, op, modelName);
String existing = matchGenerated(model);
if (existing != null) {
Schema schema = new Schema().$ref(existing);
@@ -578,7 +576,7 @@ public class InlineModelResolver {
propsToUpdate.put(key, schema);
modelsToAdd.put(modelName, model);
addGenerated(modelName, model);
openAPI.getComponents().addSchemas(modelName, model);
openapi.getComponents().addSchemas(modelName, model);
}
} else if (property instanceof ArraySchema) {
ArraySchema ap = (ArraySchema) property;
@@ -586,9 +584,9 @@ public class InlineModelResolver {
if (inner instanceof ObjectSchema) {
ObjectSchema op = (ObjectSchema) inner;
if (op.getProperties() != null && op.getProperties().size() > 0) {
flattenProperties(op.getProperties(), path);
flattenProperties(openAPI, op.getProperties(), path);
String modelName = resolveModelName(op.getTitle(), path + "_" + key);
Schema innerModel = modelFromProperty(op, modelName);
Schema innerModel = modelFromProperty(openAPI, op, modelName);
String existing = matchGenerated(innerModel);
if (existing != null) {
Schema schema = new Schema().$ref(existing);
@@ -599,19 +597,19 @@ public class InlineModelResolver {
schema.setRequired(op.getRequired());
ap.setItems(schema);
addGenerated(modelName, innerModel);
openAPI.getComponents().addSchemas(modelName, innerModel);
openapi.getComponents().addSchemas(modelName, innerModel);
}
}
}
}
if (modelUtils.isMapSchema(property)) {
Schema inner = modelUtils.getAdditionalProperties(property);
if (ModelUtils.isMapSchema(property)) {
Schema inner = ModelUtils.getAdditionalProperties(openAPI, property);
if (inner instanceof ObjectSchema) {
ObjectSchema op = (ObjectSchema) inner;
if (op.getProperties() != null && op.getProperties().size() > 0) {
flattenProperties(op.getProperties(), path);
flattenProperties(openAPI, op.getProperties(), path);
String modelName = resolveModelName(op.getTitle(), path + "_" + key);
Schema innerModel = modelFromProperty(op, modelName);
Schema innerModel = modelFromProperty(openAPI, op, modelName);
String existing = matchGenerated(innerModel);
if (existing != null) {
Schema schema = new Schema().$ref(existing);
@@ -622,7 +620,7 @@ public class InlineModelResolver {
schema.setRequired(op.getRequired());
property.setAdditionalProperties(schema);
addGenerated(modelName, innerModel);
openAPI.getComponents().addSchemas(modelName, innerModel);
openapi.getComponents().addSchemas(modelName, innerModel);
}
}
}
@@ -634,12 +632,12 @@ public class InlineModelResolver {
}
}
for (String key : modelsToAdd.keySet()) {
openAPI.getComponents().addSchemas(key, modelsToAdd.get(key));
openapi.getComponents().addSchemas(key, modelsToAdd.get(key));
this.addedModels.put(key, modelsToAdd.get(key));
}
}
private Schema modelFromProperty(Schema object, String path) {
private Schema modelFromProperty(OpenAPI openAPI, Schema object, String path) {
String description = object.getDescription();
String example = null;
Object obj = object.getExample();
@@ -688,7 +686,7 @@ public class InlineModelResolver {
model.setDeprecated(object.getDeprecated());
if (properties != null) {
flattenProperties(properties, path);
flattenProperties(openAPI, properties, path);
model.setProperties(properties);
}
return model;
@@ -717,7 +715,7 @@ public class InlineModelResolver {
private void copyVendorExtensions(Schema source, Schema target) {
Map<String, Object> vendorExtensions = source.getExtensions();
if (vendorExtensions == null) {
return;
return;
}
for (String extName : vendorExtensions.keySet()) {
target.addExtension(extName, vendorExtensions.get(extName));

View File

@@ -264,7 +264,7 @@ public class CodegenConfigurator {
public CodegenConfigurator setGenerateAliasAsModel(boolean generateAliasAsModel) {
workflowSettingsBuilder.withGenerateAliasAsModel(generateAliasAsModel);
GlobalSettings.setProperty("generateAliasAsModelKey", String.valueOf(generateAliasAsModel));
ModelUtils.setGenerateAliasAsModel(generateAliasAsModel);
return this;
}
@@ -508,6 +508,9 @@ public class CodegenConfigurator {
GlobalSettings.setProperty(entry.getKey(), entry.getValue());
}
// if caller resets GlobalSettings, we'll need to reset generateAliasAsModel. As noted in this method, this should be moved.
ModelUtils.setGenerateAliasAsModel(workflowSettings.isGenerateAliasAsModel());
// TODO: Support custom spec loader implementations (https://github.com/OpenAPITools/openapi-generator/issues/844)
final List<AuthorizationValue> authorizationValues = AuthParser.parse(this.auth);
ParseOptions options = new ParseOptions();
@@ -520,18 +523,13 @@ public class CodegenConfigurator {
// TODO: The line below could be removed when at least one of the issue below has been resolved.
// https://github.com/swagger-api/swagger-parser/issues/1369
// https://github.com/swagger-api/swagger-parser/pull/1374
//modelUtils.getOpenApiVersion(specification, inputSpec, authorizationValues);
ModelUtils modelUtils = new ModelUtils(specification);
// if caller resets GlobalSettings, we'll need to reset generateAliasAsModel. As noted in this method, this should be moved.
modelUtils.setGenerateAliasAsModel(workflowSettings.isGenerateAliasAsModel());
//ModelUtils.getOpenApiVersion(specification, inputSpec, authorizationValues);
// NOTE: We will only expose errors+warnings if there are already errors in the spec.
if (validationMessages.size() > 0) {
Set<String> warnings = new HashSet<>();
if (specification != null) {
List<String> unusedModels = modelUtils.getUnusedSchemas();
List<String> unusedModels = ModelUtils.getUnusedSchemas(specification);
if (unusedModels != null) {
unusedModels.forEach(name -> warnings.add("Unused model: " + name));
}

View File

@@ -17,7 +17,6 @@
package org.openapitools.codegen.examples;
import com.sun.org.apache.xpath.internal.operations.Mod;
import io.swagger.v3.core.util.Json;
import io.swagger.v3.oas.models.OpenAPI;
import io.swagger.v3.oas.models.media.ArraySchema;
@@ -47,13 +46,11 @@ public class ExampleGenerator {
protected Map<String, Schema> examples;
private OpenAPI openAPI;
private ModelUtils modelUtils;
private Random random;
public ExampleGenerator(Map<String, Schema> examples, OpenAPI openAPI) {
this.examples = examples;
this.openAPI = openAPI;
this.modelUtils = new ModelUtils(openAPI);
// use a fixed seed to make the "random" numbers reproducible.
this.random = new Random("ExampleGenerator".hashCode());
}
@@ -72,7 +69,7 @@ public class ExampleGenerator {
}
private List<Map<String, String>> generateFromResponseSchema(Schema responseSchema, Set<String> producesInfo) {
if (responseSchema.getExample() == null && StringUtils.isEmpty(responseSchema.get$ref()) && !modelUtils.isArraySchema(responseSchema)) {
if (responseSchema.getExample() == null && StringUtils.isEmpty(responseSchema.get$ref()) && !ModelUtils.isArraySchema(responseSchema)) {
// no example provided
return null;
}
@@ -81,14 +78,14 @@ public class ExampleGenerator {
return generate(responseSchema.getExample(), new ArrayList<>(producesInfo));
}
if (modelUtils.isArraySchema(responseSchema)) { // array of schema
if (ModelUtils.isArraySchema(responseSchema)) { // array of schema
ArraySchema as = (ArraySchema) responseSchema;
if (as.getItems() != null && StringUtils.isEmpty(as.getItems().get$ref())) { // arary of primtive types
return generate((Map<String, Object>) responseSchema.getExample(),
new ArrayList<String>(producesInfo), as.getItems());
} else if (as.getItems() != null && !StringUtils.isEmpty(as.getItems().get$ref())) { // array of model
return generate((Map<String, Object>) responseSchema.getExample(),
new ArrayList<String>(producesInfo), modelUtils.getSimpleRef(as.getItems().get$ref()));
new ArrayList<String>(producesInfo), ModelUtils.getSimpleRef(as.getItems().get$ref()));
} else {
// TODO log warning message as such case is not handled at the moment
return null;
@@ -98,7 +95,7 @@ public class ExampleGenerator {
new ArrayList<String>(producesInfo), responseSchema);
} else { // model
return generate((Map<String, Object>) responseSchema.getExample(),
new ArrayList<String>(producesInfo), modelUtils.getSimpleRef(responseSchema.get$ref()));
new ArrayList<String>(producesInfo), ModelUtils.getSimpleRef(responseSchema.get$ref()));
}
}
@@ -121,7 +118,7 @@ public class ExampleGenerator {
output.add(kv);
}
} else if (property != null && mediaType.startsWith(MIME_TYPE_XML)) {
String example = new XmlExampleGenerator(this.examples, openAPI).toXml(property);
String example = new XmlExampleGenerator(this.examples).toXml(property);
if (example != null) {
kv.put(EXAMPLE, example);
output.add(kv);
@@ -168,7 +165,7 @@ public class ExampleGenerator {
}
} else if (modelName != null && mediaType.startsWith(MIME_TYPE_XML)) {
final Schema schema = this.examples.get(modelName);
String example = new XmlExampleGenerator(this.examples, openAPI).toXml(schema, 0, Collections.<String>emptySet());
String example = new XmlExampleGenerator(this.examples).toXml(schema, 0, Collections.<String>emptySet());
if (example != null) {
kv.put(EXAMPLE, example);
output.add(kv);
@@ -225,13 +222,13 @@ public class ExampleGenerator {
if (property.getExample() != null) {
LOGGER.debug("Example set in openapi spec, returning example: '{}'", property.getExample().toString());
return property.getExample();
} else if (modelUtils.isBooleanSchema(property)) {
} else if (ModelUtils.isBooleanSchema(property)) {
Object defaultValue = property.getDefault();
if (defaultValue != null) {
return defaultValue;
}
return Boolean.TRUE;
} else if (modelUtils.isArraySchema(property)) {
} else if (ModelUtils.isArraySchema(property)) {
Schema innerType = ((ArraySchema) property).getItems();
if (innerType != null) {
int arrayLength = null == ((ArraySchema) property).getMaxItems() ? 2 : ((ArraySchema) property).getMaxItems();
@@ -244,45 +241,45 @@ public class ExampleGenerator {
}
return objectProperties;
}
} else if (modelUtils.isDateSchema(property)) {
} else if (ModelUtils.isDateSchema(property)) {
return "2000-01-23";
} else if (modelUtils.isDateTimeSchema(property)) {
} else if (ModelUtils.isDateTimeSchema(property)) {
return "2000-01-23T04:56:07.000+00:00";
} else if (modelUtils.isNumberSchema(property)) {
} else if (ModelUtils.isNumberSchema(property)) {
Double min = getPropertyValue(property.getMinimum());
Double max = getPropertyValue(property.getMaximum());
if (modelUtils.isFloatSchema(property)) { // float
if (ModelUtils.isFloatSchema(property)) { // float
return (float) randomNumber(min, max);
} else if (modelUtils.isDoubleSchema(property)) { // decimal/double
} else if (ModelUtils.isDoubleSchema(property)) { // decimal/double
return BigDecimal.valueOf(randomNumber(min, max));
} else { // no format defined
return randomNumber(min, max);
}
} else if (modelUtils.isFileSchema(property)) {
} else if (ModelUtils.isFileSchema(property)) {
return ""; // TODO
} else if (modelUtils.isIntegerSchema(property)) {
} else if (ModelUtils.isIntegerSchema(property)) {
Double min = getPropertyValue(property.getMinimum());
Double max = getPropertyValue(property.getMaximum());
if (modelUtils.isLongSchema(property)) {
if (ModelUtils.isLongSchema(property)) {
return (long) randomNumber(min, max);
}
return (int) randomNumber(min, max);
} else if (modelUtils.isMapSchema(property)) {
} else if (ModelUtils.isMapSchema(property)) {
Map<String, Object> mp = new HashMap<String, Object>();
if (property.getName() != null) {
mp.put(property.getName(),
resolvePropertyToExample(propertyName, mediaType, modelUtils.getAdditionalProperties(property), processedModels));
resolvePropertyToExample(propertyName, mediaType, ModelUtils.getAdditionalProperties(openAPI, property), processedModels));
} else {
mp.put("key",
resolvePropertyToExample(propertyName, mediaType, modelUtils.getAdditionalProperties(property), processedModels));
resolvePropertyToExample(propertyName, mediaType, ModelUtils.getAdditionalProperties(openAPI, property), processedModels));
}
return mp;
} else if (modelUtils.isUUIDSchema(property)) {
} else if (ModelUtils.isUUIDSchema(property)) {
return "046b6c7f-0b8a-43b9-b35d-6489e6daee91";
} else if (modelUtils.isURISchema(property)) {
} else if (ModelUtils.isURISchema(property)) {
return "https://openapi-generator.tech";
} else if (modelUtils.isStringSchema(property)) {
} else if (ModelUtils.isStringSchema(property)) {
LOGGER.debug("String property");
String defaultValue = (String) property.getDefault();
if (defaultValue != null && !defaultValue.isEmpty()) {
@@ -302,14 +299,14 @@ public class ExampleGenerator {
LOGGER.debug("No values found, using property name " + propertyName + " as example");
return propertyName;
} else if (!StringUtils.isEmpty(property.get$ref())) { // model
String simpleName = modelUtils.getSimpleRef(property.get$ref());
Schema schema = modelUtils.getSchema(simpleName);
String simpleName = ModelUtils.getSimpleRef(property.get$ref());
Schema schema = ModelUtils.getSchema(openAPI, simpleName);
if (schema == null) { // couldn't find the model/schema
return "{}";
}
return resolveModelToExample(simpleName, mediaType, schema, processedModels);
} else if (modelUtils.isObjectSchema(property)) {
} else if (ModelUtils.isObjectSchema(property)) {
return "{}";
}

View File

@@ -17,7 +17,6 @@
package org.openapitools.codegen.examples;
import io.swagger.v3.oas.models.OpenAPI;
import io.swagger.v3.oas.models.media.ArraySchema;
import io.swagger.v3.oas.models.media.Schema;
import io.swagger.v3.oas.models.media.XML;
@@ -36,12 +35,8 @@ public class XmlExampleGenerator {
public static String TAG_END = "</";
private static String EMPTY = "";
protected Map<String, Schema> examples;
protected OpenAPI openAPI;
protected ModelUtils modelUtils;
public XmlExampleGenerator(Map<String, Schema> examples, OpenAPI openAPI) {
this.openAPI = openAPI;
this.modelUtils = new ModelUtils(openAPI);
public XmlExampleGenerator(Map<String, Schema> examples) {
this.examples = examples;
if (examples == null) {
this.examples = new HashMap<String, Schema>();
@@ -129,7 +124,7 @@ public class XmlExampleGenerator {
}
StringBuilder sb = new StringBuilder();
if (modelUtils.isArraySchema(schema)) {
if (ModelUtils.isArraySchema(schema)) {
ArraySchema as = (ArraySchema) schema;
Schema inner = as.getItems();
boolean wrapped = false;
@@ -182,29 +177,29 @@ public class XmlExampleGenerator {
protected String getExample(Schema schema) {
if (schema.getExample() != null) {
return schema.getExample().toString();
} else if (modelUtils.isDateTimeSchema(schema)) {
} else if (ModelUtils.isDateTimeSchema(schema)) {
return "2000-01-23T04:56:07.000Z";
} else if (modelUtils.isDateSchema(schema)) {
} else if (ModelUtils.isDateSchema(schema)) {
return "2000-01-23";
} else if (modelUtils.isBooleanSchema(schema)) {
} else if (ModelUtils.isBooleanSchema(schema)) {
return "true";
} else if (modelUtils.isNumberSchema(schema)) {
if (modelUtils.isFloatSchema(schema)) { // float
} else if (ModelUtils.isNumberSchema(schema)) {
if (ModelUtils.isFloatSchema(schema)) { // float
return "1.3579";
} else { // double
return "3.149";
}
} else if (modelUtils.isPasswordSchema(schema)) {
} else if (ModelUtils.isPasswordSchema(schema)) {
return "********";
} else if (modelUtils.isUUIDSchema(schema)) {
} else if (ModelUtils.isUUIDSchema(schema)) {
return "046b6c7f-0b8a-43b9-b35d-6489e6daee91";
} else if (modelUtils.isURISchema(schema)) {
} else if (ModelUtils.isURISchema(schema)) {
return "https://openapi-generator.tech";
// do these last in case the specific types above are derived from these classes
} else if (modelUtils.isStringSchema(schema)) {
} else if (ModelUtils.isStringSchema(schema)) {
return "aeiou";
} else if (modelUtils.isIntegerSchema(schema)) {
if (modelUtils.isLongSchema(schema)) { // long
} else if (ModelUtils.isIntegerSchema(schema)) {
if (ModelUtils.isLongSchema(schema)) { // long
return "123456789";
} else { //integer
return "123";

View File

@@ -142,7 +142,7 @@ public class CodegenIgnoreProcessor {
public boolean allowsFile(final File targetFile) {
if(this.ignoreFile == null) return true;
File file = new File(this.ignoreFile.getAbsoluteFile().getParentFile().toURI().relativize(targetFile.toURI()).getPath());
File file = new File(this.ignoreFile.getParentFile().toURI().relativize(targetFile.toURI()).getPath());
Boolean directoryExcluded = false;
Boolean exclude = false;
if(exclusionRules.size() == 0 && inclusionRules.size() == 0) {

View File

@@ -410,12 +410,12 @@ abstract public class AbstractAdaCodegen extends DefaultCodegen implements Codeg
schemaType = schemaType.replace("-", "_");
}
if (modelUtils.isArraySchema(p)) {
if (ModelUtils.isArraySchema(p)) {
ArraySchema ap = (ArraySchema) p;
Schema inner = ap.getItems();
return getTypeDeclaration(inner) + "_Vectors.Vector";
}
if (modelUtils.isMapSchema(p)) {
if (ModelUtils.isMapSchema(p)) {
Schema inner = getAdditionalProperties(p);
String name = getTypeDeclaration(inner) + "_Map";
if (name.startsWith("Swagger.")) {
@@ -432,7 +432,7 @@ abstract public class AbstractAdaCodegen extends DefaultCodegen implements Codeg
return schemaType;
}
String modelType = toModelName(schemaType).replace("-", "_");
if (modelUtils.isStringSchema(p) || modelUtils.isFileSchema(p)
if (ModelUtils.isStringSchema(p) || ModelUtils.isFileSchema(p)
|| languageSpecificPrimitives.contains(modelType)) {
return modelType;
}
@@ -526,8 +526,8 @@ abstract public class AbstractAdaCodegen extends DefaultCodegen implements Codeg
if (operation.getResponses() != null && !operation.getResponses().isEmpty()) {
ApiResponse methodResponse = findMethodResponse(operation.getResponses());
if (methodResponse != null && modelUtils.getSchemaFromResponse(methodResponse) != null) {
CodegenProperty cm = fromProperty("response", modelUtils.getSchemaFromResponse(methodResponse));
if (methodResponse != null && ModelUtils.getSchemaFromResponse(methodResponse) != null) {
CodegenProperty cm = fromProperty("response", ModelUtils.getSchemaFromResponse(methodResponse));
op.vendorExtensions.put("x-codegen-response", cm);
op.vendorExtensions.put("x-is-model-type", isModelType(cm));
op.vendorExtensions.put("x-is-stream-type", isStreamType(cm));

View File

@@ -185,7 +185,7 @@ public abstract class AbstractApexCodegen extends DefaultCodegen implements Code
@Override
public String getTypeDeclaration(Schema p) {
if (modelUtils.isArraySchema(p)) {
if (ModelUtils.isArraySchema(p)) {
ArraySchema ap = (ArraySchema) p;
Schema inner = ap.getItems();
if (inner == null) {
@@ -194,7 +194,7 @@ public abstract class AbstractApexCodegen extends DefaultCodegen implements Code
return null;
}
return getSchemaType(p) + "<" + getTypeDeclaration(inner) + ">";
} else if (modelUtils.isMapSchema(p)) {
} else if (ModelUtils.isMapSchema(p)) {
Schema inner = getAdditionalProperties(p);
if (inner == null) {
@@ -217,7 +217,7 @@ public abstract class AbstractApexCodegen extends DefaultCodegen implements Code
@Override
public String toDefaultValue(Schema p) {
if (modelUtils.isArraySchema(p)) {
if (ModelUtils.isArraySchema(p)) {
final ArraySchema ap = (ArraySchema) p;
final String pattern = "new ArrayList<%s>()";
if (ap.getItems() == null) {
@@ -225,7 +225,7 @@ public abstract class AbstractApexCodegen extends DefaultCodegen implements Code
}
return String.format(Locale.ROOT, pattern, getTypeDeclaration(ap.getItems()));
} else if (modelUtils.isMapSchema(p)) {
} else if (ModelUtils.isMapSchema(p)) {
final MapSchema ap = (MapSchema) p;
final String pattern = "new HashMap<%s>()";
if (getAdditionalProperties(ap) == null) {
@@ -233,32 +233,32 @@ public abstract class AbstractApexCodegen extends DefaultCodegen implements Code
}
return String.format(Locale.ROOT, pattern, String.format(Locale.ROOT, "String, %s", getTypeDeclaration(getAdditionalProperties(ap))));
} else if (modelUtils.isLongSchema(p)) {
} else if (ModelUtils.isLongSchema(p)) {
if (p.getDefault() != null) {
return p.getDefault().toString() + "l";
}
return "null";
} else if (modelUtils.isIntegerSchema(p)) {
} else if (ModelUtils.isIntegerSchema(p)) {
if (p.getDefault() != null) {
return p.getDefault().toString();
}
return "null";
} else if (modelUtils.isFloatSchema(p)) {
} else if (ModelUtils.isFloatSchema(p)) {
if (p.getDefault() != null) {
return p.getDefault().toString() + "f";
}
return "null";
} else if (modelUtils.isDoubleSchema(p)) {
} else if (ModelUtils.isDoubleSchema(p)) {
if (p.getDefault() != null) {
return p.getDefault().toString() + "d";
}
return "null";
} else if (modelUtils.isBooleanSchema(p)) {
} else if (ModelUtils.isBooleanSchema(p)) {
if (p.getDefault() != null) {
return p.getDefault().toString();
}
return "null";
} else if (modelUtils.isStringSchema(p)) {
} else if (ModelUtils.isStringSchema(p)) {
if (p.getDefault() != null) {
String _default = (String) p.getDefault();
if (p.getEnum() == null) {
@@ -314,18 +314,18 @@ public abstract class AbstractApexCodegen extends DefaultCodegen implements Code
Object obj = p.getExample();
String example = obj == null ? "" : obj.toString();
if (modelUtils.isArraySchema(p)) {
if (ModelUtils.isArraySchema(p)) {
example = "new " + getTypeDeclaration(p) + "{" + toExampleValue(
((ArraySchema) p).getItems()) + "}";
} else if (modelUtils.isBooleanSchema(p)) {
} else if (ModelUtils.isBooleanSchema(p)) {
example = String.valueOf(!"false".equals(example));
} else if (modelUtils.isByteArraySchema(p)) {
} else if (ModelUtils.isByteArraySchema(p)) {
if (example.isEmpty()) {
example = "VGhlIHF1aWNrIGJyb3duIGZveCBqdW1wZWQgb3ZlciB0aGUgbGF6eSBkb2cu";
}
p.setExample(example);
example = "EncodingUtil.base64Decode('" + example + "')";
} else if (modelUtils.isDateSchema(p)) {
} else if (ModelUtils.isDateSchema(p)) {
if (example.matches("^\\d{4}(-\\d{2}){2}")) {
example = example.substring(0, 10).replaceAll("-0?", ", ");
} else if (example.isEmpty()) {
@@ -336,7 +336,7 @@ public abstract class AbstractApexCodegen extends DefaultCodegen implements Code
example = "2000, 1, 23";
}
example = "Date.newInstance(" + example + ")";
} else if (modelUtils.isDateTimeSchema(p)) {
} else if (ModelUtils.isDateTimeSchema(p)) {
if (example.matches("^\\d{4}([-T:]\\d{2}){5}.+")) {
example = example.substring(0, 19).replaceAll("[-T:]0?", ", ");
} else if (example.isEmpty()) {
@@ -347,31 +347,31 @@ public abstract class AbstractApexCodegen extends DefaultCodegen implements Code
example = "2000, 1, 23, 4, 56, 7";
}
example = "Datetime.newInstanceGmt(" + example + ")";
} else if (modelUtils.isNumberSchema(p)) {
} else if (ModelUtils.isNumberSchema(p)) {
example = example.replaceAll("[^-0-9.]", "");
example = example.isEmpty() ? "1.3579" : example;
} else if (modelUtils.isFileSchema(p)) {
} else if (ModelUtils.isFileSchema(p)) {
if (example.isEmpty()) {
example = "VGhlIHF1aWNrIGJyb3duIGZveCBqdW1wZWQgb3ZlciB0aGUgbGF6eSBkb2cu";
p.setExample(example);
}
example = "EncodingUtil.base64Decode(" + example + ")";
} else if (modelUtils.isEmailSchema(p)) {
} else if (ModelUtils.isEmailSchema(p)) {
if (example.isEmpty()) {
example = "example@example.com";
p.setExample(example);
}
example = "'" + example + "'";
} else if (modelUtils.isLongSchema(p)) {
} else if (ModelUtils.isLongSchema(p)) {
example = example.isEmpty() ? "123456789L" : example + "L";
} else if (modelUtils.isMapSchema(p)) {
} else if (ModelUtils.isMapSchema(p)) {
example = "new " + getTypeDeclaration(p) + "{'key'=>" + toExampleValue(getAdditionalProperties(p)) + "}";
} else if (modelUtils.isPasswordSchema(p)) {
} else if (ModelUtils.isPasswordSchema(p)) {
example = example.isEmpty() ? "password123" : escapeText(example);
p.setExample(example);
example = "'" + example + "'";
} else if (modelUtils.isStringSchema(p)) {
} else if (ModelUtils.isStringSchema(p)) {
List<String> enums = p.getEnum();
if (enums != null && example.isEmpty()) {
example = enums.get(0);
@@ -383,13 +383,13 @@ public abstract class AbstractApexCodegen extends DefaultCodegen implements Code
p.setExample(example);
}
example = "'" + example + "'";
} else if (modelUtils.isUUIDSchema(p)) {
} else if (ModelUtils.isUUIDSchema(p)) {
example = example.isEmpty()
? "'046b6c7f-0b8a-43b9-b35d-6489e6daee91'"
: "'" + escapeText(example) + "'";
} else if (modelUtils.isIntegerSchema(p)) {
} else if (ModelUtils.isIntegerSchema(p)) {
example = example.matches("^-?\\d+$") ? example : "0";
} else if (modelUtils.isObjectSchema(p)) {
} else if (ModelUtils.isObjectSchema(p)) {
example = example.isEmpty() ? "null" : example;
} else {
example = getTypeDeclaration(p) + ".getExample()";
@@ -571,7 +571,7 @@ public abstract class AbstractApexCodegen extends DefaultCodegen implements Code
if (op.getHasExamples()) {
// prepare examples for Apex test classes
ApiResponse apiResponse = findMethodResponse(operation.getResponses());
final Schema responseSchema = modelUtils.getSchemaFromResponse(apiResponse);
final Schema responseSchema = ModelUtils.getSchemaFromResponse(apiResponse);
String deserializedExample = toExampleValue(responseSchema);
for (Map<String, String> example : op.examples) {
example.put("example", escapeText(example.get("example")));

View File

@@ -437,7 +437,7 @@ public abstract class AbstractCSharpCodegen extends DefaultCodegen implements Co
private void postProcessEnumRefs(final Map<String, Object> models) {
Map<String, CodegenModel> enumRefs = new HashMap<String, CodegenModel>();
for (Map.Entry<String, Object> entry : models.entrySet()) {
CodegenModel model = modelUtils.getModelByName(entry.getKey(), models);
CodegenModel model = ModelUtils.getModelByName(entry.getKey(), models);
if (model.isEnum) {
enumRefs.put(entry.getKey(), model);
}
@@ -445,7 +445,7 @@ public abstract class AbstractCSharpCodegen extends DefaultCodegen implements Co
for (Map.Entry<String, Object> entry : models.entrySet()) {
String openAPIName = entry.getKey();
CodegenModel model = modelUtils.getModelByName(openAPIName, models);
CodegenModel model = ModelUtils.getModelByName(openAPIName, models);
if (model != null) {
for (CodegenProperty var : model.allVars) {
if (enumRefs.containsKey(var.dataType)) {
@@ -594,7 +594,7 @@ public abstract class AbstractCSharpCodegen extends DefaultCodegen implements Co
protected void updateValueTypeProperty(Map<String, Object> models) {
for (Map.Entry<String, Object> entry : models.entrySet()) {
String openAPIName = entry.getKey();
CodegenModel model = modelUtils.getModelByName(openAPIName, models);
CodegenModel model = ModelUtils.getModelByName(openAPIName, models);
if (model != null) {
for (CodegenProperty var : model.vars) {
var.vendorExtensions.put("x-is-value-type", isValueType(var));
@@ -611,7 +611,7 @@ public abstract class AbstractCSharpCodegen extends DefaultCodegen implements Co
protected void updateNullableTypeProperty(Map<String, Object> models) {
for (Map.Entry<String, Object> entry : models.entrySet()) {
String openAPIName = entry.getKey();
CodegenModel model = modelUtils.getModelByName(openAPIName, models);
CodegenModel model = ModelUtils.getModelByName(openAPIName, models);
if (model != null) {
for (CodegenProperty var : model.vars) {
if (!var.isContainer && (nullableType.contains(var.dataType) || var.isEnum)) {
@@ -859,23 +859,23 @@ public abstract class AbstractCSharpCodegen extends DefaultCodegen implements Co
*/
@Override
public String toExampleValue(Schema p) {
if (modelUtils.isStringSchema(p)) {
if (ModelUtils.isStringSchema(p)) {
if (p.getExample() != null) {
return "\"" + p.getExample().toString() + "\"";
}
} else if (modelUtils.isBooleanSchema(p)) {
} else if (ModelUtils.isBooleanSchema(p)) {
if (p.getExample() != null) {
return p.getExample().toString();
}
} else if (modelUtils.isDateSchema(p)) {
} else if (ModelUtils.isDateSchema(p)) {
// TODO
} else if (modelUtils.isDateTimeSchema(p)) {
} else if (ModelUtils.isDateTimeSchema(p)) {
// TODO
} else if (modelUtils.isNumberSchema(p)) {
} else if (ModelUtils.isNumberSchema(p)) {
if (p.getExample() != null) {
return p.getExample().toString();
}
} else if (modelUtils.isIntegerSchema(p)) {
} else if (ModelUtils.isIntegerSchema(p)) {
if (p.getExample() != null) {
return p.getExample().toString();
}
@@ -891,33 +891,33 @@ public abstract class AbstractCSharpCodegen extends DefaultCodegen implements Co
*/
@Override
public String toDefaultValue(Schema p) {
if (modelUtils.isBooleanSchema(p)) {
if (ModelUtils.isBooleanSchema(p)) {
if (p.getDefault() != null) {
return p.getDefault().toString();
}
} else if (modelUtils.isDateSchema(p)) {
} else if (ModelUtils.isDateSchema(p)) {
if (p.getDefault() != null) {
return "\"" + p.getDefault().toString() + "\"";
}
} else if (modelUtils.isDateTimeSchema(p)) {
} else if (ModelUtils.isDateTimeSchema(p)) {
if (p.getDefault() != null) {
return "\"" + p.getDefault().toString() + "\"";
}
} else if (modelUtils.isNumberSchema(p)) {
} else if (ModelUtils.isNumberSchema(p)) {
if (p.getDefault() != null) {
if (modelUtils.isFloatSchema(p)) { // float
if (ModelUtils.isFloatSchema(p)) { // float
return p.getDefault().toString() + "F";
} else if (modelUtils.isDoubleSchema(p)) { // double
} else if (ModelUtils.isDoubleSchema(p)) { // double
return p.getDefault().toString() + "D";
} else { // decimal
return p.getDefault().toString() + "M";
}
}
} else if (modelUtils.isIntegerSchema(p)) {
} else if (ModelUtils.isIntegerSchema(p)) {
if (p.getDefault() != null) {
return p.getDefault().toString();
}
} else if (modelUtils.isStringSchema(p)) {
} else if (ModelUtils.isStringSchema(p)) {
if (p.getDefault() != null) {
String _default = (String) p.getDefault();
if (p.getEnum() == null) {
@@ -989,7 +989,7 @@ public abstract class AbstractCSharpCodegen extends DefaultCodegen implements Co
@Override
public String toInstantiationType(Schema p) {
if (modelUtils.isArraySchema(p)) {
if (ModelUtils.isArraySchema(p)) {
return getArrayTypeDeclaration((ArraySchema) p);
}
return super.toInstantiationType(p);
@@ -997,9 +997,9 @@ public abstract class AbstractCSharpCodegen extends DefaultCodegen implements Co
@Override
public String getTypeDeclaration(Schema p) {
if (modelUtils.isArraySchema(p)) {
if (ModelUtils.isArraySchema(p)) {
return getArrayTypeDeclaration((ArraySchema) p);
} else if (modelUtils.isMapSchema(p)) {
} else if (ModelUtils.isMapSchema(p)) {
// Should we also support maps of maps?
Schema inner = getAdditionalProperties(p);
return getSchemaType(p) + "<string, " + getTypeDeclaration(inner) + ">";

View File

@@ -326,7 +326,7 @@ abstract public class AbstractCppCodegen extends DefaultCodegen implements Codeg
}
@Override
public void preprocessOpenAPI() {
public void preprocessOpenAPI(OpenAPI openAPI) {
URL url = URLPathUtils.getServerURL(openAPI, serverVariableOverrides());
String port = URLPathUtils.getPort(url, "");
String host = url.getHost();
@@ -362,7 +362,7 @@ abstract public class AbstractCppCodegen extends DefaultCodegen implements Codeg
public Map<String, Object> postProcessAllModels(Map<String, Object> objs){
Map<String, Object> models = super.postProcessAllModels(objs);
for (final Entry<String, Object> model : models.entrySet()) {
CodegenModel mo = modelUtils.getModelByName(model.getKey(), models);
CodegenModel mo = ModelUtils.getModelByName(model.getKey(), models);
addForwardDeclarations(mo, models);
}
return models;
@@ -379,7 +379,7 @@ abstract public class AbstractCppCodegen extends DefaultCodegen implements Codeg
}
String childPropertyType = property.isContainer? property.mostInnerItems.baseType : property.baseType;
for(final Entry<String, Object> mo : objs.entrySet()) {
CodegenModel childModel = modelUtils.getModelByName(mo.getKey(), objs);
CodegenModel childModel = ModelUtils.getModelByName(mo.getKey(), objs);
if( !childPropertyType.equals(childModel.classname) || childPropertyType.equals(parentModel.classname) || !childModel.hasVars ){
continue;
}

View File

@@ -48,8 +48,8 @@ public abstract class AbstractEiffelCodegen extends DefaultCodegen implements Co
setReservedWordsLowerCase(Arrays.asList(
// language reserved words
"across", "agent", "alias", "all", "and", "as", "assign", "attached", "attribute", "check", "class", "convert",
"create", "Current", "debug", "deferred", "detachable", "do", "else", "elseif", "end", "ensure", "expanded", "export",
"across", "agent", "alias", "all", "and", "as", "assign", "attribute", "check", "class", "convert",
"create", "Current", "debug", "deferred", "do", "else", "elseif", "end", "ensure", "expanded", "export",
"external", "False", "feature", "from", "frozen", "if", "implies", "inherit", "inspect", "invariant",
"like", "local", "loop", "not", "note", "obsolete", "old", "once", "only", "or", "Precursor",
"redefine", "rename", "require", "rescue", "Result", "retry", "select", "separate", "then", "True",
@@ -68,7 +68,6 @@ public abstract class AbstractEiffelCodegen extends DefaultCodegen implements Co
typeMapping.put("long", "INTEGER_64");
typeMapping.put("number", "REAL_32");
typeMapping.put("float", "REAL_32");
typeMapping.put("decimal", "REAL_64");
typeMapping.put("double", "REAL_64");
typeMapping.put("boolean", "BOOLEAN");
typeMapping.put("string", "STRING_32");
@@ -86,17 +85,10 @@ public abstract class AbstractEiffelCodegen extends DefaultCodegen implements Co
typeMapping.put("map", "STRING_TABLE");
typeMapping.put("array", "LIST");
typeMapping.put("list", "LIST");
typeMapping.put("AnyType", "ANY");
instantiationTypes.put("array", "ARRAYED_LIST");
instantiationTypes.put("list", "ARRAYED_LIST");
instantiationTypes.put("map", "STRING_TABLE");
importMapping.put("List", "LIST");
importMapping.put("Set", "SET");
importMapping.put("file", "FILE");
importMapping.put("File", "FILE");
importMapping.put("Map", "STRING_TABLE");
cliOptions.clear();
@@ -175,12 +167,6 @@ public abstract class AbstractEiffelCodegen extends DefaultCodegen implements Co
@Override
public String toModelFilename(String name) {
// We need to check if import-mapping has a different model for this class, so we use it
// instead of the auto-generated one.
if (importMapping.containsKey(name)) {
return importMapping.get(name);
}
if (!StringUtils.isEmpty(modelNamePrefix)) {
name = modelNamePrefix + "_" + name;
}
@@ -205,13 +191,6 @@ public abstract class AbstractEiffelCodegen extends DefaultCodegen implements Co
name = "model_" + name; // e.g. 200Response => Model200Response
// (after camelize)
}
// model name starts with _
if (name.startsWith("_")) {
LOGGER.warn(name + " (model name starts with _) cannot be used as model name. Renamed to "
+ ("model" + name));
name = "model" + name; // e.g. 200Response => Model200Response
// (after camelize)
}
return underscore(name);
}
@@ -292,14 +271,14 @@ public abstract class AbstractEiffelCodegen extends DefaultCodegen implements Co
@Override
public String getTypeDeclaration(Schema p) {
if (modelUtils.isArraySchema(p)) {
if (ModelUtils.isArraySchema(p)) {
ArraySchema ap = (ArraySchema) p;
Schema inner = ap.getItems();
return "LIST [" + getTypeDeclaration(inner) + "]";
} else if (modelUtils.isMapSchema(p)) {
} else if (ModelUtils.isMapSchema(p)) {
Schema inner = getAdditionalProperties(p);
return getSchemaType(p) + " [" + getTypeDeclaration(inner) + "]";
return getSchemaType(p) + "[" + getTypeDeclaration(inner) + "]";
}
// return super.getTypeDeclaration(p);
@@ -336,12 +315,7 @@ public abstract class AbstractEiffelCodegen extends DefaultCodegen implements Co
@Override
public String toOperationId(String operationId) {
// throw exception if method name is empty
if (StringUtils.isEmpty(operationId)) {
throw new RuntimeException("Empty method/operation name (operationId) not allowed");
}
String sanitizedOperationId = camelize(sanitizeName(operationId), true);
String sanitizedOperationId = sanitizeName(operationId);
// method name cannot use reserved keyword, e.g. return
if (isReservedWord(sanitizedOperationId)) {
@@ -349,13 +323,6 @@ public abstract class AbstractEiffelCodegen extends DefaultCodegen implements Co
+ camelize("call_" + operationId));
sanitizedOperationId = "call_" + sanitizedOperationId;
}
// operationId starts with a number
if (operationId.matches("^\\d.*")) {
LOGGER.warn(operationId + " (starting with a number) cannot be used as method sname. Renamed to " + camelize("call_" + operationId), true);
sanitizedOperationId = camelize("call_" + sanitizedOperationId, true);
}
// method name from updateSomething to update_Something.
sanitizedOperationId = unCamelize(sanitizedOperationId);
@@ -463,7 +430,7 @@ public abstract class AbstractEiffelCodegen extends DefaultCodegen implements Co
private void postProcessParentModels(final Map<String, Object> models) {
for (final String parent : parentModels) {
final CodegenModel parentModel = modelUtils.getModelByName(parent, models);
final CodegenModel parentModel = ModelUtils.getModelByName(parent, models);
final Collection<CodegenModel> childrenModels = childrenByParent.get(parent);
for (final CodegenModel child : childrenModels) {
processParentPropertiesInChildModel(parentModel, child);
@@ -492,7 +459,7 @@ public abstract class AbstractEiffelCodegen extends DefaultCodegen implements Co
@Override
public CodegenModel fromModel(String name, Schema model) {
Map<String, Schema> allDefinitions = modelUtils.getSchemas();
Map<String, Schema> allDefinitions = ModelUtils.getSchemas(this.openAPI);
CodegenModel codegenModel = super.fromModel(name, model);
if (allDefinitions != null && codegenModel.parentSchema != null && codegenModel.hasEnums) {
final Schema parentModel = allDefinitions.get(codegenModel.parentSchema);
@@ -570,23 +537,22 @@ public abstract class AbstractEiffelCodegen extends DefaultCodegen implements Co
@Override
public String toInstantiationType(Schema p) {
return getTypeDeclaration(p);
// if (modelUtils.isMapSchema(p)) {
// Schema additionalProperties2 = getAdditionalProperties(p);
// String type = additionalProperties2.getType();
// if (null == type) {
// LOGGER.error("No Type defined for Additional Schema " + additionalProperties2 + "\n" //
// + "\tIn Schema: " + p);
// }
// String inner = toModelName(getSchemaType(additionalProperties2));
// return instantiationTypes.get("map") + " [" + inner + "]";
// } else if (modelUtils.isArraySchema(p)) {
// ArraySchema ap = (ArraySchema) p;
// String inner = toModelName(getSchemaType(ap.getItems()));
// return instantiationTypes.get("array") + " [" + inner + "]";
// } else {
// return null;
// }
if (ModelUtils.isMapSchema(p)) {
Schema additionalProperties2 = getAdditionalProperties(p);
String type = additionalProperties2.getType();
if (null == type) {
LOGGER.error("No Type defined for Additional Schema " + additionalProperties2 + "\n" //
+ "\tIn Schema: " + p);
}
String inner = toModelName(getSchemaType(additionalProperties2));
return instantiationTypes.get("map") + " [" + inner + "]";
} else if (ModelUtils.isArraySchema(p)) {
ArraySchema ap = (ArraySchema) p;
String inner = toModelName(getSchemaType(ap.getItems()));
return instantiationTypes.get("array") + " [" + inner + "]";
} else {
return null;
}
}
public String unCamelize(String name) {

View File

@@ -358,7 +358,7 @@ public abstract class AbstractFSharpCodegen extends DefaultCodegen implements Co
List<String> classNames = new ArrayList<String>();
for (String k : objs.keySet()) {
CodegenModel model = modelUtils.getModelByName(k, objs);
CodegenModel model = ModelUtils.getModelByName(k, objs);
if (model == null || model.classname == null) {
throw new RuntimeException("Null model encountered");
}
@@ -405,7 +405,7 @@ public abstract class AbstractFSharpCodegen extends DefaultCodegen implements Co
private void postProcessEnumRefs(final Map<String, Object> models) {
Map<String, CodegenModel> enumRefs = new HashMap<String, CodegenModel>();
for (Map.Entry<String, Object> entry : models.entrySet()) {
CodegenModel model = modelUtils.getModelByName(entry.getKey(), models);
CodegenModel model = ModelUtils.getModelByName(entry.getKey(), models);
if (model.isEnum) {
enumRefs.put(entry.getKey(), model);
}
@@ -413,7 +413,7 @@ public abstract class AbstractFSharpCodegen extends DefaultCodegen implements Co
for (Map.Entry<String, Object> entry : models.entrySet()) {
String openAPIName = entry.getKey();
CodegenModel model = modelUtils.getModelByName(openAPIName, models);
CodegenModel model = ModelUtils.getModelByName(openAPIName, models);
if (model != null) {
for (CodegenProperty var : model.allVars) {
if (enumRefs.containsKey(var.dataType)) {
@@ -735,23 +735,23 @@ public abstract class AbstractFSharpCodegen extends DefaultCodegen implements Co
*/
@Override
public String toExampleValue(Schema p) {
if (modelUtils.isStringSchema(p)) {
if (ModelUtils.isStringSchema(p)) {
if (p.getExample() != null) {
return "\"" + p.getExample().toString() + "\"";
}
} else if (modelUtils.isBooleanSchema(p)) {
} else if (ModelUtils.isBooleanSchema(p)) {
if (p.getExample() != null) {
return p.getExample().toString();
}
} else if (modelUtils.isDateSchema(p)) {
} else if (ModelUtils.isDateSchema(p)) {
// TODO
} else if (modelUtils.isDateTimeSchema(p)) {
} else if (ModelUtils.isDateTimeSchema(p)) {
// TODO
} else if (modelUtils.isNumberSchema(p)) {
} else if (ModelUtils.isNumberSchema(p)) {
if (p.getExample() != null) {
return p.getExample().toString();
}
} else if (modelUtils.isIntegerSchema(p)) {
} else if (ModelUtils.isIntegerSchema(p)) {
if (p.getExample() != null) {
return p.getExample().toString();
}
@@ -768,33 +768,33 @@ public abstract class AbstractFSharpCodegen extends DefaultCodegen implements Co
*/
@Override
public String toDefaultValue(Schema p) {
if (modelUtils.isBooleanSchema(p)) {
if (ModelUtils.isBooleanSchema(p)) {
if (p.getDefault() != null) {
return p.getDefault().toString();
}
} else if (modelUtils.isDateSchema(p)) {
} else if (ModelUtils.isDateSchema(p)) {
if (p.getDefault() != null) {
return "\"" + p.getDefault().toString() + "\"";
}
} else if (modelUtils.isDateTimeSchema(p)) {
} else if (ModelUtils.isDateTimeSchema(p)) {
if (p.getDefault() != null) {
return "\"" + p.getDefault().toString() + "\"";
}
} else if (modelUtils.isNumberSchema(p)) {
} else if (ModelUtils.isNumberSchema(p)) {
if (p.getDefault() != null) {
if (modelUtils.isFloatSchema(p)) { // float
if (ModelUtils.isFloatSchema(p)) { // float
return p.getDefault().toString() + "F";
} else if (modelUtils.isDoubleSchema(p)) { // double
} else if (ModelUtils.isDoubleSchema(p)) { // double
return p.getDefault().toString() + "D";
} else { // decimal
return p.getDefault().toString() + "M";
}
}
} else if (modelUtils.isIntegerSchema(p)) {
} else if (ModelUtils.isIntegerSchema(p)) {
if (p.getDefault() != null) {
return p.getDefault().toString();
}
} else if (modelUtils.isStringSchema(p)) {
} else if (ModelUtils.isStringSchema(p)) {
if (p.getDefault() != null) {
String _default = (String) p.getDefault();
if (p.getEnum() == null) {
@@ -817,7 +817,7 @@ public abstract class AbstractFSharpCodegen extends DefaultCodegen implements Co
public String getNullableType(Schema p, String type) {
if (languageSpecificPrimitives.contains(type)) {
if (isSupportNullable() && modelUtils.isNullable(p) && nullableType.contains(type)) {
if (isSupportNullable() && ModelUtils.isNullable(p) && nullableType.contains(type)) {
return type + " option";
} else {
return type;
@@ -869,7 +869,7 @@ public abstract class AbstractFSharpCodegen extends DefaultCodegen implements Co
@Override
public String toInstantiationType(Schema p) {
if (modelUtils.isArraySchema(p)) {
if (ModelUtils.isArraySchema(p)) {
return getArrayTypeDeclaration((ArraySchema) p);
}
return super.toInstantiationType(p);
@@ -877,9 +877,9 @@ public abstract class AbstractFSharpCodegen extends DefaultCodegen implements Co
@Override
public String getTypeDeclaration(Schema p) {
if (modelUtils.isArraySchema(p)) {
if (ModelUtils.isArraySchema(p)) {
return getArrayTypeDeclaration((ArraySchema) p);
} else if (modelUtils.isMapSchema(p)) {
} else if (ModelUtils.isMapSchema(p)) {
// Should we also support maps of maps?
Schema inner = getAdditionalProperties(p);
return getSchemaType(p) + "<string, " + getTypeDeclaration(inner) + ">";

View File

@@ -17,7 +17,6 @@
package org.openapitools.codegen.languages;
import com.sun.org.apache.xpath.internal.operations.Mod;
import io.swagger.v3.oas.models.media.ArraySchema;
import io.swagger.v3.oas.models.media.Schema;
import org.apache.commons.io.FilenameUtils;
@@ -331,7 +330,7 @@ public abstract class AbstractGoCodegen extends DefaultCodegen implements Codege
*/
@Override
public String getTypeDeclaration(Schema p) {
if (modelUtils.isArraySchema(p)) {
if (ModelUtils.isArraySchema(p)) {
ArraySchema ap = (ArraySchema) p;
Schema inner = ap.getItems();
// In OAS 3.0.x, the array "items" attribute is required.
@@ -339,7 +338,7 @@ public abstract class AbstractGoCodegen extends DefaultCodegen implements Codege
// specification is aligned with the JSON schema specification.
// When "items" is not specified, the elements of the array may be anything at all.
if (inner != null) {
inner = modelUtils.unaliasSchema(inner);
inner = ModelUtils.unaliasSchema(this.openAPI, inner);
}
String typDecl;
if (inner != null) {
@@ -348,9 +347,9 @@ public abstract class AbstractGoCodegen extends DefaultCodegen implements Codege
typDecl = "interface{}";
}
return "[]" + typDecl;
} else if (modelUtils.isMapSchema(p)) {
} else if (ModelUtils.isMapSchema(p)) {
Schema inner = getAdditionalProperties(p);
return getSchemaType(p) + "[string]" + getTypeDeclaration(modelUtils.unaliasSchema(inner));
return getSchemaType(p) + "[string]" + getTypeDeclaration(ModelUtils.unaliasSchema(this.openAPI, inner));
}
//return super.getTypeDeclaration(p);
@@ -395,7 +394,7 @@ public abstract class AbstractGoCodegen extends DefaultCodegen implements Codege
if (ref != null && !ref.isEmpty()) {
type = openAPIType;
} else if ("object".equals(openAPIType) && modelUtils.isAnyTypeSchema(p)) {
} else if ("object".equals(openAPIType) && isAnyTypeSchema(p)) {
// Arbitrary type. Note this is not the same thing as free-form object.
type = "interface{}";
} else if (typeMapping.containsKey(openAPIType)) {
@@ -426,9 +425,9 @@ public abstract class AbstractGoCodegen extends DefaultCodegen implements Codege
*/
@Override
public String toInstantiationType(Schema property) {
if (modelUtils.isMapSchema(property)) {
if (ModelUtils.isMapSchema(property)) {
return getTypeDeclaration(property);
} else if (modelUtils.isArraySchema(property)) {
} else if (ModelUtils.isArraySchema(property)) {
return getTypeDeclaration(property);
}
return super.toInstantiationType(property);

View File

@@ -266,11 +266,11 @@ public abstract class AbstractGraphQLCodegen extends DefaultCodegen implements C
@Override
public String getTypeDeclaration(Schema p) {
if (modelUtils.isArraySchema(p)) {
if (ModelUtils.isArraySchema(p)) {
ArraySchema ap = (ArraySchema) p;
Schema inner = ap.getItems();
return "[" + getTypeDeclaration(inner) + "]";
} else if (modelUtils.isMapSchema(p)) {
} else if (ModelUtils.isMapSchema(p)) {
Schema inner = (Schema) p.getAdditionalProperties();
return getTypeDeclaration(inner);
}
@@ -278,7 +278,7 @@ public abstract class AbstractGraphQLCodegen extends DefaultCodegen implements C
// Not using the supertype invocation, because we want to UpperCamelize
// the type.
String schemaType = getSchemaType(p);
String nullable = modelUtils.isNullable(p) ? "" : "!";
String nullable = ModelUtils.isNullable(p) ? "" : "!";
/*
if (p != null && Boolean.TRUE.equals(p.getNullable())) {
nullable = "";

View File

@@ -21,12 +21,10 @@ import com.google.common.base.Strings;
import io.swagger.v3.oas.models.OpenAPI;
import io.swagger.v3.oas.models.Operation;
import io.swagger.v3.oas.models.PathItem;
import io.swagger.v3.oas.models.examples.Example;
import io.swagger.v3.oas.models.media.ArraySchema;
import io.swagger.v3.oas.models.media.ComposedSchema;
import io.swagger.v3.oas.models.media.Schema;
import io.swagger.v3.oas.models.media.StringSchema;
import io.swagger.v3.oas.models.parameters.Parameter;
import io.swagger.v3.oas.models.servers.Server;
import io.swagger.v3.parser.util.SchemaTypeUtil;
import org.apache.commons.io.FilenameUtils;
@@ -794,13 +792,13 @@ public abstract class AbstractJavaCodegen extends DefaultCodegen implements Code
@Override
public String getTypeDeclaration(Schema p) {
Schema<?> schema = modelUtils.unaliasSchema(p, importMapping);
Schema<?> target = modelUtils.isGenerateAliasAsModel() ? p : schema;
if (modelUtils.isArraySchema(target)) {
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) + ">";
} else if (modelUtils.isMapSchema(target)) {
// Note: modelUtils.isMapSchema(p) returns true when p is a composed schema that also defines
} else 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) {
@@ -823,10 +821,10 @@ public abstract class AbstractJavaCodegen extends DefaultCodegen implements Code
@Override
public String toDefaultValue(Schema schema) {
schema = modelUtils.getReferencedSchema(schema);
if (modelUtils.isArraySchema(schema)) {
schema = ModelUtils.getReferencedSchema(this.openAPI, schema);
if (ModelUtils.isArraySchema(schema)) {
final String pattern;
if (modelUtils.isSet(schema)) {
if (ModelUtils.isSet(schema)) {
String mapInstantiationType = instantiationTypes().getOrDefault("set", "LinkedHashSet");
pattern = "new " + mapInstantiationType + "<%s>()";
} else {
@@ -836,7 +834,7 @@ public abstract class AbstractJavaCodegen extends DefaultCodegen implements Code
Schema<?> items = getSchemaItems((ArraySchema) schema);
String typeDeclaration = getTypeDeclaration(modelUtils.unaliasSchema(items));
String typeDeclaration = getTypeDeclaration(ModelUtils.unaliasSchema(this.openAPI, items));
Object java8obj = additionalProperties.get("java8");
if (java8obj != null) {
Boolean java8 = Boolean.valueOf(java8obj.toString());
@@ -846,7 +844,7 @@ public abstract class AbstractJavaCodegen extends DefaultCodegen implements Code
}
return String.format(Locale.ROOT, pattern, typeDeclaration);
} else if (modelUtils.isMapSchema(schema) && !(schema instanceof ComposedSchema)) {
} else if (ModelUtils.isMapSchema(schema) && !(schema instanceof ComposedSchema)) {
if (schema.getProperties() != null && schema.getProperties().size() > 0) {
// object is complex object with free-form additional properties
if (schema.getDefault() != null) {
@@ -872,7 +870,7 @@ public abstract class AbstractJavaCodegen extends DefaultCodegen implements Code
}
return String.format(Locale.ROOT, pattern, typeDeclaration);
} else if (modelUtils.isIntegerSchema(schema)) {
} else if (ModelUtils.isIntegerSchema(schema)) {
if (schema.getDefault() != null) {
if (SchemaTypeUtil.INTEGER64_FORMAT.equals(schema.getFormat())) {
return schema.getDefault().toString() + "l";
@@ -881,28 +879,26 @@ public abstract class AbstractJavaCodegen extends DefaultCodegen implements Code
}
}
return null;
} else if (modelUtils.isNumberSchema(schema)) {
} else if (ModelUtils.isNumberSchema(schema)) {
if (schema.getDefault() != null) {
if (SchemaTypeUtil.FLOAT_FORMAT.equals(schema.getFormat())) {
return schema.getDefault().toString() + "f";
} else if (SchemaTypeUtil.DOUBLE_FORMAT.equals(schema.getFormat())) {
return schema.getDefault().toString() + "d";
} else {
return "new BigDecimal(\"" + schema.getDefault().toString() + "\")";
return schema.getDefault().toString() + "d";
}
}
return null;
} else if (modelUtils.isBooleanSchema(schema)) {
} else if (ModelUtils.isBooleanSchema(schema)) {
if (schema.getDefault() != null) {
return schema.getDefault().toString();
}
return null;
} else if (modelUtils.isURISchema(schema)) {
} else if (ModelUtils.isURISchema(schema)) {
if (schema.getDefault() != null) {
return "URI.create(\"" + escapeText((String) schema.getDefault()) + "\")";
}
return null;
} else if (modelUtils.isStringSchema(schema)) {
} else if (ModelUtils.isStringSchema(schema)) {
if (schema.getDefault() != null) {
String _default;
if (schema.getDefault() instanceof Date) {
@@ -923,7 +919,7 @@ public abstract class AbstractJavaCodegen extends DefaultCodegen implements Code
}
}
return null;
} else if (modelUtils.isObjectSchema(schema)) {
} else if (ModelUtils.isObjectSchema(schema)) {
if (schema.getDefault() != null) {
return super.toDefaultValue(schema);
}
@@ -933,37 +929,6 @@ public abstract class AbstractJavaCodegen extends DefaultCodegen implements Code
return super.toDefaultValue(schema);
}
/**
* Return the example value of the parameter. Overrides the
* setParameterExampleValue(CodegenParameter, Parameter) method in
* DefaultCodegen to always call setParameterExampleValue(CodegenParameter)
* in this class, which adds single quotes around strings from the
* x-example property.
*
* @param codegenParameter Codegen parameter
* @param parameter Parameter
*/
@Override
public void setParameterExampleValue(CodegenParameter codegenParameter, Parameter parameter) {
if (parameter.getExample() != null) {
codegenParameter.example = parameter.getExample().toString();
}
if (parameter.getExamples() != null && !parameter.getExamples().isEmpty()) {
Example example = parameter.getExamples().values().iterator().next();
if (example.getValue() != null) {
codegenParameter.example = example.getValue().toString();
}
}
Schema schema = parameter.getSchema();
if (schema != null && schema.getExample() != null) {
codegenParameter.example = schema.getExample().toString();
}
setParameterExampleValue(codegenParameter);
}
@Override
public void setParameterExampleValue(CodegenParameter p) {
String example;
@@ -992,17 +957,15 @@ public abstract class AbstractJavaCodegen extends DefaultCodegen implements Code
if (example == null) {
example = "56";
}
example = StringUtils.appendIfMissingIgnoreCase(example, "L");
example = example + "L";
} else if ("Float".equals(type)) {
if (example == null) {
example = "3.4";
}
example = StringUtils.appendIfMissingIgnoreCase(example, "F");
example = example + "F";
} else if ("Double".equals(type)) {
if (example == null) {
example = "3.4";
}
example = StringUtils.appendIfMissingIgnoreCase(example, "D");
example = "3.4";
example = example + "D";
} else if ("Boolean".equals(type)) {
if (example == null) {
example = "true";
@@ -1014,14 +977,6 @@ public abstract class AbstractJavaCodegen extends DefaultCodegen implements Code
example = "new File(\"" + escapeText(example) + "\")";
} else if ("Date".equals(type)) {
example = "new Date()";
} else if ("OffsetDateTime".equals(type)) {
example = "OffsetDateTime.now()";
} else if ("BigDecimal".equals(type)) {
example = "new BigDecimal(78)";
} else if (p.allowableValues != null && !p.allowableValues.isEmpty()) {
Map<String, Object> allowableValues = p.allowableValues;
List<Object> values = (List<Object>) allowableValues.get("values");
example = type + ".fromValue(\"" + String.valueOf(values.get(0)) + "\")";
} else if (!languageSpecificPrimitives.contains(type)) {
// type is a model class, e.g. User
example = "new " + type + "()";
@@ -1100,7 +1055,7 @@ public abstract class AbstractJavaCodegen extends DefaultCodegen implements Code
@Override
public CodegenModel fromModel(String name, Schema model) {
Map<String, Schema> allDefinitions = modelUtils.getSchemas();
Map<String, Schema> allDefinitions = ModelUtils.getSchemas(this.openAPI);
CodegenModel codegenModel = super.fromModel(name, model);
if (codegenModel.description != null) {
codegenModel.imports.add("ApiModel");
@@ -1184,24 +1139,12 @@ public abstract class AbstractJavaCodegen extends DefaultCodegen implements Code
itr.remove();
}
}
Map<String, Object> operations = (Map<String, Object>) objs.get("operations");
List<CodegenOperation> operationList = (List<CodegenOperation>) operations.get("operation");
for (CodegenOperation op : operationList) {
Collection<String> operationImports = new TreeSet<String>();
for (CodegenParameter p : op.allParams) {
if (importMapping.containsKey(p.dataType)) {
operationImports.add(importMapping.get(p.dataType));
}
}
op.vendorExtensions.put("x-java-import", operationImports);
}
return objs;
}
@Override
public void preprocessOpenAPI() {
super.preprocessOpenAPI();
public void preprocessOpenAPI(OpenAPI openAPI) {
super.preprocessOpenAPI(openAPI);
if (openAPI == null) {
return;
}
@@ -1213,13 +1156,13 @@ public abstract class AbstractJavaCodegen extends DefaultCodegen implements Code
}
for (Operation operation : path.readOperations()) {
LOGGER.info("Processing operation " + operation.getOperationId());
if (hasBodyParameter(operation) || hasFormParameter(operation)) {
String defaultContentType = hasFormParameter(operation) ? "application/x-www-form-urlencoded" : "application/json";
List<String> consumes = new ArrayList<>(getConsumesInfo(operation));
if (hasBodyParameter(openAPI, operation) || hasFormParameter(openAPI, operation)) {
String defaultContentType = hasFormParameter(openAPI, operation) ? "application/x-www-form-urlencoded" : "application/json";
List<String> consumes = new ArrayList<>(getConsumesInfo(openAPI, operation));
String contentType = consumes == null || consumes.isEmpty() ? defaultContentType : consumes.get(0);
operation.addExtension("x-contentType", contentType);
}
String accepts = getAccept(operation);
String accepts = getAccept(openAPI, operation);
operation.addExtension("x-accepts", accepts);
}
@@ -1271,10 +1214,10 @@ public abstract class AbstractJavaCodegen extends DefaultCodegen implements Code
}
}
private String getAccept(Operation operation) {
private static String getAccept(OpenAPI openAPI, Operation operation) {
String accepts = null;
String defaultContentType = "application/json";
Set<String> producesInfo = getProducesInfo(operation);
Set<String> producesInfo = getProducesInfo(openAPI, operation);
if (producesInfo != null && !producesInfo.isEmpty()) {
ArrayList<String> produces = new ArrayList<>(producesInfo);
StringBuilder sb = new StringBuilder();

View File

@@ -127,8 +127,8 @@ public abstract class AbstractJavaJAXRSServerCodegen extends AbstractJavaCodegen
}
@Override
public void preprocessOpenAPI() {
super.preprocessOpenAPI();
public void preprocessOpenAPI(OpenAPI openAPI) {
super.preprocessOpenAPI(openAPI);
/* TODO there should be no need for the following logic
if ("/".equals(swagger.getBasePath())) {
swagger.setBasePath("");

View File

@@ -310,13 +310,13 @@ public abstract class AbstractKotlinCodegen extends DefaultCodegen implements Co
*/
@Override
public String getTypeDeclaration(Schema p) {
Schema<?> schema = modelUtils.unaliasSchema(p, importMapping);
Schema<?> target = modelUtils.isGenerateAliasAsModel() ? p : schema;
if (modelUtils.isArraySchema(target)) {
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) + ">";
} else if (modelUtils.isMapSchema(target)) {
// Note: modelUtils.isMapSchema(p) returns true when p is a composed schema that also defines
} else 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) {
@@ -899,27 +899,27 @@ public abstract class AbstractKotlinCodegen extends DefaultCodegen implements Co
@Override
public String toDefaultValue(Schema p) {
if (modelUtils.isBooleanSchema(p)) {
if (ModelUtils.isBooleanSchema(p)) {
if (p.getDefault() != null) {
return p.getDefault().toString();
}
} else if (modelUtils.isDateSchema(p)) {
} else if (ModelUtils.isDateSchema(p)) {
// TODO
} else if (modelUtils.isDateTimeSchema(p)) {
} else if (ModelUtils.isDateTimeSchema(p)) {
// TODO
} else if (modelUtils.isNumberSchema(p)) {
} else if (ModelUtils.isNumberSchema(p)) {
if (p.getDefault() != null) {
return p.getDefault().toString();
}
} else if (modelUtils.isIntegerSchema(p)) {
} else if (ModelUtils.isIntegerSchema(p)) {
if (p.getDefault() != null) {
return p.getDefault().toString();
}
} else if (modelUtils.isURISchema(p)) {
} else if (ModelUtils.isURISchema(p)) {
if (p.getDefault() != null) {
return "URI.create('" + p.getDefault() + "')";
}
} else if (modelUtils.isStringSchema(p)) {
} else if (ModelUtils.isStringSchema(p)) {
if (p.getDefault() != null) {
return "\"" + p.getDefault() + "\"";
}

View File

@@ -293,7 +293,7 @@ public abstract class AbstractPhpCodegen extends DefaultCodegen implements Codeg
@Override
public String getTypeDeclaration(Schema p) {
if (modelUtils.isArraySchema(p)) {
if (ModelUtils.isArraySchema(p)) {
ArraySchema ap = (ArraySchema) p;
Schema inner = ap.getItems();
if (inner == null) {
@@ -301,7 +301,7 @@ public abstract class AbstractPhpCodegen extends DefaultCodegen implements Codeg
inner = new StringSchema().description("TODO default missing array inner type to string");
}
return getTypeDeclaration(inner) + "[]";
} else if (modelUtils.isMapSchema(p)) {
} else if (ModelUtils.isMapSchema(p)) {
Schema inner = getAdditionalProperties(p);
if (inner == null) {
LOGGER.warn(p.getName() + "(map property) does not have a proper inner type defined. Default to string");
@@ -514,23 +514,23 @@ public abstract class AbstractPhpCodegen extends DefaultCodegen implements Codeg
*/
@Override
public String toDefaultValue(Schema p) {
if (modelUtils.isBooleanSchema(p)) {
if (ModelUtils.isBooleanSchema(p)) {
if (p.getDefault() != null) {
return p.getDefault().toString();
}
} else if (modelUtils.isDateSchema(p)) {
} else if (ModelUtils.isDateSchema(p)) {
// TODO
} else if (modelUtils.isDateTimeSchema(p)) {
} else if (ModelUtils.isDateTimeSchema(p)) {
// TODO
} else if (modelUtils.isNumberSchema(p)) {
} else if (ModelUtils.isNumberSchema(p)) {
if (p.getDefault() != null) {
return p.getDefault().toString();
}
} else if (modelUtils.isIntegerSchema(p)) {
} else if (ModelUtils.isIntegerSchema(p)) {
if (p.getDefault() != null) {
return p.getDefault().toString();
}
} else if (modelUtils.isStringSchema(p)) {
} else if (ModelUtils.isStringSchema(p)) {
if (p.getDefault() != null) {
return "'" + p.getDefault() + "'";
}

View File

@@ -345,11 +345,11 @@ public abstract class AbstractPythonConnexionServerCodegen extends DefaultCodege
@Override
public String getTypeDeclaration(Schema p) {
if (modelUtils.isArraySchema(p)) {
if (ModelUtils.isArraySchema(p)) {
ArraySchema ap = (ArraySchema) p;
Schema inner = ap.getItems();
return getSchemaType(p) + "[" + getTypeDeclaration(inner) + "]";
} else if (modelUtils.isMapSchema(p)) {
} else if (ModelUtils.isMapSchema(p)) {
Schema inner = getAdditionalProperties(p);
return getSchemaType(p) + "[str, " + getTypeDeclaration(inner) + "]";
}
@@ -372,7 +372,7 @@ public abstract class AbstractPythonConnexionServerCodegen extends DefaultCodege
}
@Override
public void preprocessOpenAPI() {
public void preprocessOpenAPI(OpenAPI openAPI) {
// need vendor extensions for x-openapi-router-controller
Map<String, PathItem> paths = openAPI.getPaths();
if (paths != null) {
@@ -704,26 +704,26 @@ public abstract class AbstractPythonConnexionServerCodegen extends DefaultCodege
*/
@Override
public String toDefaultValue(Schema p) {
if (modelUtils.isBooleanSchema(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)) {
} else if (ModelUtils.isDateSchema(p)) {
// TODO
} else if (modelUtils.isDateTimeSchema(p)) {
} else if (ModelUtils.isDateTimeSchema(p)) {
// TODO
} else if (modelUtils.isNumberSchema(p)) {
} else if (ModelUtils.isNumberSchema(p)) {
if (p.getDefault() != null) {
return p.getDefault().toString();
}
} else if (modelUtils.isIntegerSchema(p)) {
} else if (ModelUtils.isIntegerSchema(p)) {
if (p.getDefault() != null) {
return p.getDefault().toString();
}
} else if (modelUtils.isStringSchema(p)) {
} else if (ModelUtils.isStringSchema(p)) {
if (p.getDefault() != null) {
return "'" + (String) p.getDefault() + "'";
}

View File

@@ -114,10 +114,10 @@ abstract public class AbstractRubyCodegen extends DefaultCodegen implements Code
@Override
public String getTypeDeclaration(Schema schema) {
if (modelUtils.isArraySchema(schema)) {
if (ModelUtils.isArraySchema(schema)) {
Schema inner = ((ArraySchema) schema).getItems();
return getSchemaType(schema) + "<" + getTypeDeclaration(inner) + ">";
} else if (modelUtils.isMapSchema(schema)) {
} else if (ModelUtils.isMapSchema(schema)) {
Schema inner = getAdditionalProperties(schema);
return getSchemaType(schema) + "<String, " + getTypeDeclaration(inner) + ">";
}
@@ -127,11 +127,11 @@ abstract public class AbstractRubyCodegen extends DefaultCodegen implements Code
@Override
public String toInstantiationType(Schema schema) {
if (modelUtils.isMapSchema(schema)) {
if (ModelUtils.isMapSchema(schema)) {
return instantiationTypes.get("map");
} else if (modelUtils.isArraySchema(schema)) {
} else if (ModelUtils.isArraySchema(schema)) {
String parentType;
if (modelUtils.isSet(schema)) {
if (ModelUtils.isSet(schema)) {
parentType = "set";
} else {
parentType = "array";
@@ -143,12 +143,12 @@ abstract public class AbstractRubyCodegen extends DefaultCodegen implements Code
@Override
public String toDefaultValue(Schema p) {
p = modelUtils.getReferencedSchema(p);
if (modelUtils.isIntegerSchema(p) || modelUtils.isNumberSchema(p) || modelUtils.isBooleanSchema(p)) {
p = ModelUtils.getReferencedSchema(this.openAPI, p);
if (ModelUtils.isIntegerSchema(p) || ModelUtils.isNumberSchema(p) || ModelUtils.isBooleanSchema(p)) {
if (p.getDefault() != null) {
return p.getDefault().toString();
}
} else if (modelUtils.isStringSchema(p)) {
} else if (ModelUtils.isStringSchema(p)) {
if (p.getDefault() != null) {
if (p.getDefault() instanceof Date) {
Date date = (Date) p.getDefault();

View File

@@ -320,11 +320,11 @@ public abstract class AbstractScalaCodegen extends DefaultCodegen {
@Override
public String getTypeDeclaration(Schema p) {
if (modelUtils.isArraySchema(p)) {
if (ModelUtils.isArraySchema(p)) {
ArraySchema ap = (ArraySchema) p;
Schema inner = ap.getItems();
return getSchemaType(p) + "[" + getTypeDeclaration(inner) + "]";
} else if (modelUtils.isMapSchema(p)) {
} else if (ModelUtils.isMapSchema(p)) {
Schema inner = getAdditionalProperties(p);
return getSchemaType(p) + "[String, " + getTypeDeclaration(inner) + "]";
@@ -335,7 +335,7 @@ public abstract class AbstractScalaCodegen extends DefaultCodegen {
@Override
public String getSchemaType(Schema p) {
String openAPIType = super.getSchemaType(p);
if (modelUtils.isSet(p)) {
if (ModelUtils.isSet(p)) {
openAPIType = "set";
}
@@ -353,13 +353,13 @@ public abstract class AbstractScalaCodegen extends DefaultCodegen {
@Override
public String toInstantiationType(Schema p) {
if (modelUtils.isMapSchema(p)) {
if (ModelUtils.isMapSchema(p)) {
String inner = getSchemaType(getAdditionalProperties(p));
return instantiationTypes.get("map") + "[String, " + inner + "]";
} else if (modelUtils.isArraySchema(p)) {
} else if (ModelUtils.isArraySchema(p)) {
ArraySchema ap = (ArraySchema) p;
String inner = getSchemaType(ap.getItems());
return ( modelUtils.isSet(ap) ? instantiationTypes.get("set") : instantiationTypes.get("array") ) + "[" + inner + "]";
return ( ModelUtils.isSet(ap) ? instantiationTypes.get("set") : instantiationTypes.get("array") ) + "[" + inner + "]";
} else {
return null;
}
@@ -372,24 +372,24 @@ public abstract class AbstractScalaCodegen extends DefaultCodegen {
}
// comment out the following as the default value is no handled differently
if (modelUtils.isBooleanSchema(p)) {
if (ModelUtils.isBooleanSchema(p)) {
return null;
} else if (modelUtils.isDateSchema(p)) {
} else if (ModelUtils.isDateSchema(p)) {
return null;
} else if (modelUtils.isDateTimeSchema(p)) {
} else if (ModelUtils.isDateTimeSchema(p)) {
return null;
} else if (modelUtils.isNumberSchema(p)) {
} else if (ModelUtils.isNumberSchema(p)) {
return null;
} else if (modelUtils.isIntegerSchema(p)) {
} else if (ModelUtils.isIntegerSchema(p)) {
return null;
} else if (modelUtils.isMapSchema(p)) {
} else if (ModelUtils.isMapSchema(p)) {
String inner = getSchemaType(getAdditionalProperties(p));
return "new HashMap[String, " + inner + "]() ";
} else if (modelUtils.isArraySchema(p)) {
} else if (ModelUtils.isArraySchema(p)) {
ArraySchema ap = (ArraySchema) p;
String inner = getSchemaType(ap.getItems());
String genericType;
if (modelUtils.isSet(ap)) {
if (ModelUtils.isSet(ap)) {
genericType = instantiationTypes.get("set");
} else {
genericType = instantiationTypes.get("array");
@@ -410,7 +410,7 @@ public abstract class AbstractScalaCodegen extends DefaultCodegen {
// Assume that any other generic types can be new'd up.
return "new " + genericType + "[" + inner + "]() ";
} else if (modelUtils.isStringSchema(p)) {
} else if (ModelUtils.isStringSchema(p)) {
return null;
} else {
return null;
@@ -427,9 +427,9 @@ public abstract class AbstractScalaCodegen extends DefaultCodegen {
@Override
public CodegenProperty fromProperty(String name, Schema p) {
CodegenProperty prop = super.fromProperty(name, p);
if (modelUtils.isArraySchema(p)) {
if (ModelUtils.isArraySchema(p)) {
ArraySchema as = (ArraySchema) p;
if (modelUtils.isSet(as)) {
if (ModelUtils.isSet(as)) {
prop.containerType = "set";
}
}

View File

@@ -269,7 +269,7 @@ public abstract class AbstractTypeScriptClientCodegen extends DefaultCodegen imp
}
@Override
public void preprocessOpenAPI() {
public void preprocessOpenAPI(OpenAPI openAPI) {
if (additionalProperties.containsKey(NPM_NAME)) {
@@ -413,16 +413,16 @@ public abstract class AbstractTypeScriptClientCodegen extends DefaultCodegen imp
@Override
public String getTypeDeclaration(Schema p) {
if (modelUtils.isArraySchema(p)) {
if (ModelUtils.isArraySchema(p)) {
Schema<?> items = getSchemaItems((ArraySchema) p);
return getSchemaType(p) + "<" + getTypeDeclaration(modelUtils.unaliasSchema(items)) + ">";
} else if (modelUtils.isMapSchema(p)) {
return getSchemaType(p) + "<" + getTypeDeclaration(ModelUtils.unaliasSchema(this.openAPI, items)) + ">";
} else if (ModelUtils.isMapSchema(p)) {
Schema<?> inner = getSchemaAdditionalProperties(p);
String nullSafeSuffix = getNullSafeAdditionalProps() ? " | undefined" : "";
return "{ [key: string]: " + getTypeDeclaration(modelUtils.unaliasSchema(inner)) + nullSafeSuffix + "; }";
} else if (modelUtils.isFileSchema(p)) {
return "{ [key: string]: " + getTypeDeclaration(ModelUtils.unaliasSchema(this.openAPI, inner)) + nullSafeSuffix + "; }";
} else if (ModelUtils.isFileSchema(p)) {
return "any";
} else if (modelUtils.isBinarySchema(p)) {
} else if (ModelUtils.isBinarySchema(p)) {
return "any";
}
return super.getTypeDeclaration(p);
@@ -432,37 +432,37 @@ public abstract class AbstractTypeScriptClientCodegen extends DefaultCodegen imp
protected String getParameterDataType(Parameter parameter, Schema p) {
// handle enums of various data types
Schema inner;
if (modelUtils.isArraySchema(p)) {
if (ModelUtils.isArraySchema(p)) {
ArraySchema mp1 = (ArraySchema) p;
inner = mp1.getItems();
return this.getSchemaType(p) + "<" + this.getParameterDataType(parameter, inner) + ">";
} else if (modelUtils.isMapSchema(p)) {
} else if (ModelUtils.isMapSchema(p)) {
inner = getAdditionalProperties(p);
return "{ [key: string]: " + this.getParameterDataType(parameter, inner) + "; }";
} else if (modelUtils.isStringSchema(p)) {
} else if (ModelUtils.isStringSchema(p)) {
// Handle string enums
if (p.getEnum() != null) {
return enumValuesToEnumTypeUnion(p.getEnum(), "string");
}
} else if (modelUtils.isIntegerSchema(p)) {
} else if (ModelUtils.isIntegerSchema(p)) {
// Handle integer enums
if (p.getEnum() != null) {
return numericEnumValuesToEnumTypeUnion(new ArrayList<Number>(p.getEnum()));
}
} else if (modelUtils.isNumberSchema(p)) {
} else if (ModelUtils.isNumberSchema(p)) {
// Handle double enums
if (p.getEnum() != null) {
return numericEnumValuesToEnumTypeUnion(new ArrayList<Number>(p.getEnum()));
}
}
/* TODO revise the logic below
else if (modelUtils.isDateSchema(p)) {
else if (ModelUtils.isDateSchema(p)) {
// Handle date enums
DateSchema sp = (DateSchema) p;
if (sp.getEnum() != null) {
return enumValuesToEnumTypeUnion(sp.getEnum(), "string");
}
} else if (modelUtils.isDateTimeSchema(p)) {
} else if (ModelUtils.isDateTimeSchema(p)) {
// Handle datetime enums
DateTimeSchema sp = (DateTimeSchema) p;
if (sp.getEnum() != null) {
@@ -510,27 +510,27 @@ public abstract class AbstractTypeScriptClientCodegen extends DefaultCodegen imp
@Override
public String toDefaultValue(Schema p) {
if (modelUtils.isBooleanSchema(p)) {
if (ModelUtils.isBooleanSchema(p)) {
if (p.getDefault() != null) {
return p.getDefault().toString();
}
return UNDEFINED_VALUE;
} else if (modelUtils.isDateSchema(p)) {
} else if (ModelUtils.isDateSchema(p)) {
if (p.getDefault() != null) {
return p.getDefault().toString();
}
return UNDEFINED_VALUE;
} else if (modelUtils.isDateTimeSchema(p)) {
} else if (ModelUtils.isDateTimeSchema(p)) {
if (p.getDefault() != null) {
return p.getDefault().toString();
}
return UNDEFINED_VALUE;
} else if (modelUtils.isNumberSchema(p) || modelUtils.isIntegerSchema(p)) {
} else if (ModelUtils.isNumberSchema(p) || ModelUtils.isIntegerSchema(p)) {
if (p.getDefault() != null) {
return p.getDefault().toString();
}
return UNDEFINED_VALUE;
} else if (modelUtils.isStringSchema(p)) {
} else if (ModelUtils.isStringSchema(p)) {
if (p.getDefault() != null) {
return "'" + (String) p.getDefault() + "'";
}
@@ -551,7 +551,7 @@ public abstract class AbstractTypeScriptClientCodegen extends DefaultCodegen imp
public String getSchemaType(Schema p) {
String openAPIType = super.getSchemaType(p);
String type = null;
if (modelUtils.isComposedSchema(p)) {
if (ModelUtils.isComposedSchema(p)) {
return openAPIType;
} else if (typeMapping.containsKey(openAPIType)) {
type = typeMapping.get(openAPIType);
@@ -898,7 +898,7 @@ public abstract class AbstractTypeScriptClientCodegen extends DefaultCodegen imp
return filteredSchemas.stream().map(schema -> {
String schemaType = getSchemaType(schema);
if (modelUtils.isArraySchema(schema)) {
if (ModelUtils.isArraySchema(schema)) {
ArraySchema ap = (ArraySchema) schema;
Schema inner = ap.getItems();
schemaType = schemaType + "<" + getSchemaType(inner) + ">";

View File

@@ -223,11 +223,11 @@ public class AndroidClientCodegen extends DefaultCodegen implements CodegenConfi
@Override
public String getTypeDeclaration(Schema p) {
if (modelUtils.isArraySchema(p)) {
if (ModelUtils.isArraySchema(p)) {
ArraySchema ap = (ArraySchema) p;
Schema inner = ap.getItems();
return getSchemaType(p) + "<" + getTypeDeclaration(inner) + ">";
} else if (modelUtils.isMapSchema(p)) {
} else if (ModelUtils.isMapSchema(p)) {
Schema inner = getAdditionalProperties(p);
return getSchemaType(p) + "<String, " + getTypeDeclaration(inner) + ">";

View File

@@ -158,7 +158,7 @@ public class ApexClientCodegen extends AbstractApexCodegen {
}
@Override
public void preprocessOpenAPI() {
public void preprocessOpenAPI(OpenAPI openAPI) {
String calloutLabel = openAPI.getInfo().getTitle();
if (StringUtils.isNotBlank(namedCredential)) {
calloutLabel = namedCredential;
@@ -221,24 +221,24 @@ public class ApexClientCodegen extends AbstractApexCodegen {
@Override
public String toDefaultValue(Schema p) {
String out = null;
if (modelUtils.isArraySchema(p)) {
if (ModelUtils.isArraySchema(p)) {
Schema inner = ((ArraySchema) p).getItems();
out = String.format(
Locale.ROOT,
"new List<%s>()",
inner == null ? "Object" : getTypeDeclaration(inner)
);
} else if (modelUtils.isBooleanSchema(p)) {
} else if (ModelUtils.isBooleanSchema(p)) {
// true => "true", false => "false", null => "null"
out = String.valueOf(p.getDefault());
} else if (modelUtils.isLongSchema(p)) {
} else if (ModelUtils.isLongSchema(p)) {
Long def = (Long) p.getDefault();
out = def == null ? out : def.toString() + "L";
} else if (modelUtils.isMapSchema(p)) {
} else if (ModelUtils.isMapSchema(p)) {
Schema inner = getAdditionalProperties(p);
String s = inner == null ? "Object" : getTypeDeclaration(inner);
out = String.format(Locale.ROOT, "new Map<String, %s>()", s);
} else if (modelUtils.isStringSchema(p)) {
} else if (ModelUtils.isStringSchema(p)) {
if (p.getDefault() != null) {
String def = p.getDefault().toString();
if (def != null) {

View File

@@ -359,14 +359,14 @@ public class AsciidocDocumentationCodegen extends DefaultCodegen implements Code
}
@Override
public void processOpenAPI() {
public void processOpenAPI(OpenAPI openAPI) {
if (this.includeSpecMarkupLambda != null) {
LOGGER.debug("specs: " + ": " + this.includeSpecMarkupLambda.resetCounter());
}
if (this.includeSnippetMarkupLambda != null) {
LOGGER.debug("snippets: " + ": " + this.includeSnippetMarkupLambda.resetCounter());
}
super.processOpenAPI();
super.processOpenAPI(openAPI);
}
}

View File

@@ -304,8 +304,8 @@ public class AspNetCoreServerCodegen extends AbstractCSharpCodegen {
}
@Override
public void preprocessOpenAPI() {
super.preprocessOpenAPI();
public void preprocessOpenAPI(OpenAPI openAPI) {
super.preprocessOpenAPI(openAPI);
URL url = URLPathUtils.getServerURL(openAPI, serverVariableOverrides());
additionalProperties.put("serverHost", url.getHost());
additionalProperties.put("serverPort", URLPathUtils.getPort(url, 8080));
@@ -450,7 +450,7 @@ public class AspNetCoreServerCodegen extends AbstractCSharpCodegen {
@Override
public String getNullableType(Schema p, String type) {
if (languageSpecificPrimitives.contains(type)) {
if (isSupportNullable() && modelUtils.isNullable(p) && nullableType.contains(type)) {
if (isSupportNullable() && ModelUtils.isNullable(p) && nullableType.contains(type)) {
return type + "?";
} else {
return type;

View File

@@ -423,11 +423,11 @@ public class BashClientCodegen extends DefaultCodegen implements CodegenConfig {
*/
@Override
public String getTypeDeclaration(Schema p) {
if (modelUtils.isArraySchema(p)) {
if (ModelUtils.isArraySchema(p)) {
ArraySchema ap = (ArraySchema) p;
Schema inner = ap.getItems();
return getSchemaType(p) + "[" + getTypeDeclaration(inner) + "]";
} else if (modelUtils.isMapSchema(p)) {
} else if (ModelUtils.isMapSchema(p)) {
Schema inner = getAdditionalProperties(p);
return getSchemaType(p) + "[String, " + getTypeDeclaration(inner) + "]";
}
@@ -619,7 +619,7 @@ public class BashClientCodegen extends DefaultCodegen implements CodegenConfig {
@Override
public CodegenOperation fromOperation(String path, String httpMethod,
Operation operation, List<Server> servers) {
Map<String, Schema> definitions = modelUtils.getSchemas();
Map<String, Schema> definitions = ModelUtils.getSchemas(this.openAPI);
CodegenOperation op = super.fromOperation(path, httpMethod, operation, servers);
/**
@@ -663,8 +663,8 @@ public class BashClientCodegen extends DefaultCodegen implements CodegenConfig {
* If the operation produces Json and has nonempty example
* try to reformat it.
*/
if (getConsumesInfo(operation) != null
&& getConsumesInfo(operation).contains("application/json")
if (getConsumesInfo(this.openAPI, operation) != null
&& getConsumesInfo(this.openAPI, operation).contains("application/json")
&& definitions.get(p.dataType).getExample() != null) {
ObjectMapper mapper = new ObjectMapper();
@@ -697,8 +697,8 @@ public class BashClientCodegen extends DefaultCodegen implements CodegenConfig {
* @param openAPI [description]
*/
@Override
public void preprocessOpenAPI() {
super.preprocessOpenAPI();
public void preprocessOpenAPI(OpenAPI openAPI) {
super.preprocessOpenAPI(openAPI);
/* TODO need to revise the logic below
if ("/".equals(openAPI.getServers())) {

View File

@@ -296,10 +296,10 @@ public class CLibcurlClientCodegen extends DefaultCodegen implements CodegenConf
@Override
public String getTypeDeclaration(Schema schema) {
/* comment out below as we'll do it in the template instead
if (modelUtils.isArraySchema(schema)) {
if (ModelUtils.isArraySchema(schema)) {
Schema inner = ((ArraySchema) schema).getItems();
return getSchemaType(schema) + "<" + getTypeDeclaration(inner) + ">";
} else if (modelUtils.isMapSchema(schema)) {
} else if (ModelUtils.isMapSchema(schema)) {
Schema inner = (Schema) schema.getAdditionalProperties();
return getSchemaType(schema) + "<String, " + getTypeDeclaration(inner) + ">";
}
@@ -310,11 +310,11 @@ public class CLibcurlClientCodegen extends DefaultCodegen implements CodegenConf
@Override
public String toDefaultValue(Schema p) {
if (modelUtils.isIntegerSchema(p) || modelUtils.isNumberSchema(p) || modelUtils.isBooleanSchema(p)) {
if (ModelUtils.isIntegerSchema(p) || ModelUtils.isNumberSchema(p) || ModelUtils.isBooleanSchema(p)) {
if (p.getDefault() != null) {
return p.getDefault().toString();
}
} else if (modelUtils.isStringSchema(p)) {
} else if (ModelUtils.isStringSchema(p)) {
if (p.getDefault() != null) {
return "'" + escapeText((String) p.getDefault()) + "'";
}
@@ -327,17 +327,17 @@ public class CLibcurlClientCodegen extends DefaultCodegen implements CodegenConf
public String toExampleValue(Schema schema) {
String example = super.toExampleValue(schema);
if (modelUtils.isNullType(schema) && null != example) {
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 "NULL";
}
// correct "&#39;"s into "'"s after toString()
if (modelUtils.isStringSchema(schema) && schema.getDefault() != null) {
if (ModelUtils.isStringSchema(schema) && schema.getDefault() != null) {
example = (String) schema.getDefault();
}
if (StringUtils.isNotBlank(example) && !"null".equals(example)) {
if (modelUtils.isStringSchema(schema)) {
if (ModelUtils.isStringSchema(schema)) {
example = "\"" + example + "\"";
}
return example;
@@ -346,7 +346,7 @@ public class CLibcurlClientCodegen extends DefaultCodegen implements CodegenConf
if (schema.getEnum() != null && !schema.getEnum().isEmpty()) {
// Enum case:
example = schema.getEnum().get(0).toString();
/* if (modelUtils.isStringSchema(schema)) {
/* if (ModelUtils.isStringSchema(schema)) {
example = "'" + escapeText(example) + "'";
}*/
if (null == example)
@@ -355,8 +355,8 @@ public class CLibcurlClientCodegen extends DefaultCodegen implements CodegenConf
return example;
} else if (null != schema.get$ref()) {
// $ref case:
Map<String, Schema> allDefinitions = modelUtils.getSchemas();
String ref = modelUtils.getSimpleRef(schema.get$ref());
Map<String, Schema> allDefinitions = ModelUtils.getSchemas(this.openAPI);
String ref = ModelUtils.getSimpleRef(schema.get$ref());
if (allDefinitions != null) {
Schema refSchema = allDefinitions.get(ref);
if (null == refSchema) {
@@ -372,18 +372,18 @@ public class CLibcurlClientCodegen extends DefaultCodegen implements CodegenConf
LOGGER.warn("allDefinitions not defined in toExampleValue!\n");
}
}
if (modelUtils.isDateSchema(schema)) {
if (ModelUtils.isDateSchema(schema)) {
example = "\"2013-10-20\"";
return example;
} else if (modelUtils.isDateTimeSchema(schema)) {
} else if (ModelUtils.isDateTimeSchema(schema)) {
example = "\"2013-10-20T19:20:30+01:00\"";
return example;
} else if (modelUtils.isBinarySchema(schema)) {
} else if (ModelUtils.isBinarySchema(schema)) {
example = "instantiate_binary_t(\"blah\", 5)";
return example;
} else if (modelUtils.isByteArraySchema(schema)) {
} else if (ModelUtils.isByteArraySchema(schema)) {
example = "YQ==";
} else if (modelUtils.isStringSchema(schema)) {
} else if (ModelUtils.isStringSchema(schema)) {
// decimal (type: string, format: decimal)
if ("number".equalsIgnoreCase(schema.getFormat())) {
return "1";
@@ -398,29 +398,29 @@ public class CLibcurlClientCodegen extends DefaultCodegen implements CodegenConf
example = "";
for (int i = 0; i < len; i++)
example += i;
} else if (modelUtils.isIntegerSchema(schema)) {
} else if (ModelUtils.isIntegerSchema(schema)) {
if (schema.getMinimum() != null)
example = schema.getMinimum().toString();
else
example = "56";
} else if (modelUtils.isNumberSchema(schema)) {
} else if (ModelUtils.isNumberSchema(schema)) {
if (schema.getMinimum() != null)
example = schema.getMinimum().toString();
else
example = "1.337";
} else if (modelUtils.isBooleanSchema(schema)) {
} else if (ModelUtils.isBooleanSchema(schema)) {
example = "1";
} else if (modelUtils.isArraySchema(schema)) {
} else if (ModelUtils.isArraySchema(schema)) {
example = "list_create()";
} else if (modelUtils.isMapSchema(schema)) {
} else if (ModelUtils.isMapSchema(schema)) {
example = "list_create()";
} else if (modelUtils.isObjectSchema(schema)) {
} else if (ModelUtils.isObjectSchema(schema)) {
return null; // models are managed at moustache level
} else {
LOGGER.warn("Type " + schema.getType() + " not handled properly in toExampleValue");
}
if (modelUtils.isStringSchema(schema)) {
if (ModelUtils.isStringSchema(schema)) {
example = "\"" + escapeText(example) + "\"";
}
@@ -716,7 +716,7 @@ public class CLibcurlClientCodegen extends DefaultCodegen implements CodegenConf
}
@Override
public void preprocessOpenAPI() {
public void preprocessOpenAPI(OpenAPI openAPI) {
if (openAPI.getInfo() != null) {
Info info = openAPI.getInfo();
setProjectName((escapeText(info.getTitle())));
@@ -744,7 +744,7 @@ public class CLibcurlClientCodegen extends DefaultCodegen implements CodegenConf
@Override
public CodegenProperty fromProperty(String name, Schema p) {
CodegenProperty cm = super.fromProperty(name, p);
Schema ref = modelUtils.getReferencedSchema(p);
Schema ref = ModelUtils.getReferencedSchema(openAPI, p);
if (ref != null) {
if (ref.getEnum() != null) {
cm.isEnum = true;

View File

@@ -588,7 +588,7 @@ public class CSharpClientCodegen extends AbstractCSharpCodegen {
@Override
public CodegenModel fromModel(String name, Schema model) {
Map<String, Schema> allDefinitions = modelUtils.getSchemas();
Map<String, Schema> allDefinitions = ModelUtils.getSchemas(this.openAPI);
CodegenModel codegenModel = super.fromModel(name, model);
if (allDefinitions != null && codegenModel != null && codegenModel.parent != null) {
final Schema parentModel = allDefinitions.get(toModelName(codegenModel.parent));
@@ -965,14 +965,14 @@ public class CSharpClientCodegen extends AbstractCSharpCodegen {
*/
@Override
public String toInstantiationType(Schema schema) {
if (modelUtils.isMapSchema(schema)) {
if (ModelUtils.isMapSchema(schema)) {
Schema additionalProperties = getAdditionalProperties(schema);
String inner = getSchemaType(additionalProperties);
if (modelUtils.isMapSchema(additionalProperties)) {
if (ModelUtils.isMapSchema(additionalProperties)) {
inner = toInstantiationType(additionalProperties);
}
return instantiationTypes.get("map") + "<String, " + inner + ">";
} else if (modelUtils.isArraySchema(schema)) {
} else if (ModelUtils.isArraySchema(schema)) {
ArraySchema arraySchema = (ArraySchema) schema;
String inner = getSchemaType(arraySchema.getItems());
return instantiationTypes.get("array") + "<" + inner + ">";
@@ -984,7 +984,7 @@ public class CSharpClientCodegen extends AbstractCSharpCodegen {
@Override
public String getNullableType(Schema p, String type) {
if (languageSpecificPrimitives.contains(type)) {
if (isSupportNullable() && modelUtils.isNullable(p) && nullableType.contains(type)) {
if (isSupportNullable() && ModelUtils.isNullable(p) && nullableType.contains(type)) {
return type + "?";
} else {
return type;

View File

@@ -51,7 +51,7 @@ public class CSharpNancyFXServerCodegen extends AbstractCSharpCodegen {
private static final String PACKAGE_CONTEXT = "packageContext";
private static final String ASYNC_SERVER = "asyncServer";
private final Map<String, Predicate<Schema>> propertyToOpenAPITypeMapping =
private static final Map<String, Predicate<Schema>> propertyToOpenAPITypeMapping =
createPropertyToOpenAPITypeMapping();
private String packageGuid = "{" + randomUUID().toString().toUpperCase(Locale.ROOT) + "}";
@@ -118,6 +118,8 @@ public class CSharpNancyFXServerCodegen extends AbstractCSharpCodegen {
addSwitch(ASYNC_SERVER, "Set to true to enable the generation of async routes/endpoints.", this.asyncServer);
typeMapping.putAll(nodaTimeTypesMappings());
languageSpecificPrimitives.addAll(nodaTimePrimitiveTypes());
importMapping.clear();
}
@Override
@@ -270,7 +272,7 @@ public class CSharpNancyFXServerCodegen extends AbstractCSharpCodegen {
private void postProcessParentModels(final Map<String, Object> models) {
LOGGER.debug("Processing parents: " + parentModels);
for (final String parent : parentModels) {
final CodegenModel parentModel = modelUtils.getModelByName(parent, models);
final CodegenModel parentModel = ModelUtils.getModelByName(parent, models);
if (parentModel != null) {
parentModel.hasChildren = true;
final Collection<CodegenModel> childrenModels = childrenByParent.get(parent);
@@ -373,7 +375,7 @@ public class CSharpNancyFXServerCodegen extends AbstractCSharpCodegen {
}
@Override
public void preprocessOpenAPI() {
public void preprocessOpenAPI(final OpenAPI openAPI) {
URL url = URLPathUtils.getServerURL(openAPI, serverVariableOverrides());
String path = URLPathUtils.getPath(url, "/");
final String packageContextOption = (String) additionalProperties.get(PACKAGE_CONTEXT);
@@ -397,17 +399,17 @@ public class CSharpNancyFXServerCodegen extends AbstractCSharpCodegen {
return super.getSchemaType(property);
}
private Map<String, Predicate<Schema>> createPropertyToOpenAPITypeMapping() {
private static Map<String, Predicate<Schema>> createPropertyToOpenAPITypeMapping() {
final ImmutableMap.Builder<String, Predicate<Schema>> mapping = ImmutableMap.builder();
mapping.put("time", timeProperty());
return mapping.build();
}
private Predicate<Schema> timeProperty() {
private static Predicate<Schema> timeProperty() {
return new Predicate<Schema>() {
@Override
public boolean apply(Schema property) {
return modelUtils.isStringSchema(property) && "time".equalsIgnoreCase(property.getFormat());
return ModelUtils.isStringSchema(property) && "time".equalsIgnoreCase(property.getFormat());
}
};
}

View File

@@ -31,7 +31,6 @@ import java.io.File;
import java.util.*;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.Consumer;
import java.util.stream.Collectors;
import static org.apache.commons.lang3.StringUtils.isEmpty;
import static org.openapitools.codegen.utils.StringUtils.camelize;
@@ -306,7 +305,7 @@ public class CSharpNetCoreClientCodegen extends AbstractCSharpCodegen {
@Override
public CodegenModel fromModel(String name, Schema model) {
Map<String, Schema> allDefinitions = modelUtils.getSchemas();
Map<String, Schema> allDefinitions = ModelUtils.getSchemas(this.openAPI);
CodegenModel codegenModel = super.fromModel(name, model);
if (allDefinitions != null && codegenModel != null && codegenModel.parent != null) {
final Schema parentModel = allDefinitions.get(toModelName(codegenModel.parent));
@@ -401,7 +400,7 @@ public class CSharpNetCoreClientCodegen extends AbstractCSharpCodegen {
@Override
public String getNullableType(Schema p, String type) {
if (languageSpecificPrimitives.contains(type)) {
if (isSupportNullable() && modelUtils.isNullable(p) && nullableType.contains(type)) {
if (isSupportNullable() && ModelUtils.isNullable(p) && nullableType.contains(type)) {
return type + "?";
} else {
return type;
@@ -548,6 +547,7 @@ public class CSharpNetCoreClientCodegen extends AbstractCSharpCodegen {
additionalProperties.put(CodegenConstants.OPTIONAL_EMIT_DEFAULT_VALUES, optionalEmitDefaultValuesFlag);
}
if (additionalProperties.containsKey(CodegenConstants.MODEL_PROPERTY_NAMING)) {
setModelPropertyNaming((String) additionalProperties.get(CodegenConstants.MODEL_PROPERTY_NAMING));
}
@@ -561,24 +561,13 @@ public class CSharpNetCoreClientCodegen extends AbstractCSharpCodegen {
clientPackage = "Client";
String framework = (String) additionalProperties.getOrDefault(CodegenConstants.DOTNET_FRAMEWORK, defaultFramework.name);
boolean strategyMatched = false;
FrameworkStrategy strategy = defaultFramework;
for (FrameworkStrategy frameworkStrategy : frameworkStrategies) {
if (framework.equals(frameworkStrategy.name)) {
strategy = frameworkStrategy;
strategyMatched = true;
}
}
// throws exception if the input targetFramework is invalid
if (strategyMatched == false) {
throw new IllegalArgumentException("Invalid .NET framework version: " +
framework + ". List of supported versions: " +
frameworkStrategies.stream()
.map(p -> p.name)
.collect(Collectors.joining(", ")));
}
strategy.configureAdditionalProperties(additionalProperties);
setTargetFrameworkNuget(strategy.getNugetFrameworkIdentifier());
@@ -721,11 +710,7 @@ public class CSharpNetCoreClientCodegen extends AbstractCSharpCodegen {
public void setTargetFramework(String dotnetFramework) {
if (!frameworks.containsKey(dotnetFramework)) {
throw new IllegalArgumentException("Invalid .NET framework version: " +
dotnetFramework + ". List of supported versions: " +
frameworkStrategies.stream()
.map(p -> p.name)
.collect(Collectors.joining(", ")));
LOGGER.warn("Invalid .NET framework version, defaulting to " + this.targetFramework);
} else {
this.targetFramework = dotnetFramework;
}
@@ -968,14 +953,14 @@ public class CSharpNetCoreClientCodegen extends AbstractCSharpCodegen {
*/
@Override
public String toInstantiationType(Schema schema) {
if (modelUtils.isMapSchema(schema)) {
if (ModelUtils.isMapSchema(schema)) {
Schema additionalProperties = getAdditionalProperties(schema);
String inner = getSchemaType(additionalProperties);
if (modelUtils.isMapSchema(additionalProperties)) {
if (ModelUtils.isMapSchema(additionalProperties)) {
inner = toInstantiationType(additionalProperties);
}
return instantiationTypes.get("map") + "<String, " + inner + ">";
} else if (modelUtils.isArraySchema(schema)) {
} else if (ModelUtils.isArraySchema(schema)) {
ArraySchema arraySchema = (ArraySchema) schema;
String inner = getSchemaType(arraySchema.getItems());
return instantiationTypes.get("array") + "<" + inner + ">";

View File

@@ -168,7 +168,7 @@ public class ClojureClientCodegen extends DefaultCodegen implements CodegenConfi
Schema inner = ap.getItems();
return "(s/coll-of " + getTypeDeclaration(inner) + ")";
} else if (modelUtils.isMapSchema(p)) {
} else if (ModelUtils.isMapSchema(p)) {
Schema inner = (Schema) p.getAdditionalProperties();
return "(s/map-of string? " + getTypeDeclaration(inner) + ")";
@@ -216,8 +216,8 @@ public class ClojureClientCodegen extends DefaultCodegen implements CodegenConfi
}
@Override
public void preprocessOpenAPI() {
super.preprocessOpenAPI();
public void preprocessOpenAPI(OpenAPI openAPI) {
super.preprocessOpenAPI(openAPI);
if (additionalProperties.containsKey(PROJECT_NAME)) {
projectName = ((String) additionalProperties.get(PROJECT_NAME));

View File

@@ -102,11 +102,11 @@ public class ConfluenceWikiCodegen extends DefaultCodegen implements CodegenConf
@Override
public String getTypeDeclaration(Schema p) {
if (modelUtils.isArraySchema(p)) {
if (ModelUtils.isArraySchema(p)) {
ArraySchema ap = (ArraySchema) p;
Schema inner = ap.getItems();
return getSchemaType(p) + "[" + getTypeDeclaration(inner) + "]";
} else if (modelUtils.isMapSchema(p)) {
} else if (ModelUtils.isMapSchema(p)) {
Schema inner = getAdditionalProperties(p);
return getSchemaType(p) + "[String, " + getTypeDeclaration(inner) + "]";
}

View File

@@ -0,0 +1,438 @@
/*
* 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 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.responses.ApiResponse;
import io.swagger.v3.oas.models.servers.Server;
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.File;
import java.util.*;
import static org.openapitools.codegen.utils.StringUtils.underscore;
public class CppOatppServerCodegen extends AbstractCppCodegen {
private static final Logger LOGGER = LoggerFactory.getLogger(CppOatppServerCodegen.class);
protected String implFolder = "impl";
protected boolean isAddExternalLibs = true;
protected boolean isUseStructModel = false;
public static final String OPTIONAL_EXTERNAL_LIB = "addExternalLibs";
public static final String OPTIONAL_EXTERNAL_LIB_DESC = "Add the Possibility to fetch and compile external Libraries needed by this Framework.";
public static final String OPTION_USE_STRUCT_MODEL = "useStructModel";
public static final String OPTION_USE_STRUCT_MODEL_DESC = "Use struct-based model template instead of get/set-based model template";
public static final String HELPERS_PACKAGE_NAME = "helpersPackage";
public static final String HELPERS_PACKAGE_NAME_DESC = "Specify the package name to be used for the helpers (e.g. org.openapitools.server.helpers).";
protected final String PREFIX = "";
protected String helpersPackage = "";
@Override
public CodegenType getTag() {
return CodegenType.SERVER;
}
@Override
public String getName() {
return "cpp-oatpp-server";
}
@Override
public String getHelp() {
// Ref: https://github.com/oatpp/oatpp
return "Generates a C++ API server (based on Oat++)";
}
public CppOatppServerCodegen() {
super();
if (StringUtils.isEmpty(modelNamePrefix)) {
modelNamePrefix = PREFIX;
}
helpersPackage = "org.openapitools.server.helpers";
apiPackage = "org.openapitools.server.api";
modelPackage = "org.openapitools.server.model";
apiTemplateFiles.put("api-header.mustache", ".h");
apiTemplateFiles.put("api-source.mustache", ".cpp");
apiTemplateFiles.put("api-impl-header.mustache", ".h");
apiTemplateFiles.put("api-impl-source.mustache", ".cpp");
embeddedTemplateDir = templateDir = "cpp-oatpp-server";
cliOptions.clear();
addSwitch(OPTIONAL_EXTERNAL_LIB, OPTIONAL_EXTERNAL_LIB_DESC, this.isAddExternalLibs);
addOption(HELPERS_PACKAGE_NAME, HELPERS_PACKAGE_NAME_DESC, this.helpersPackage);
addOption(RESERVED_WORD_PREFIX_OPTION, RESERVED_WORD_PREFIX_DESC, this.reservedWordPrefix);
addSwitch(OPTION_USE_STRUCT_MODEL, OPTION_USE_STRUCT_MODEL_DESC, this.isUseStructModel);
addOption(VARIABLE_NAME_FIRST_CHARACTER_UPPERCASE_OPTION,
VARIABLE_NAME_FIRST_CHARACTER_UPPERCASE_DESC,
Boolean.toString(this.variableNameFirstCharacterUppercase));
supportingFiles.add(new SupportingFile("helpers-header.mustache", "model", modelNamePrefix + "Helpers.h"));
supportingFiles.add(new SupportingFile("helpers-source.mustache", "model", modelNamePrefix + "Helpers.cpp"));
supportingFiles.add(new SupportingFile("main-api-server.mustache", "", modelNamePrefix + "main-api-server.cpp"));
supportingFiles.add(new SupportingFile("cmake.mustache", "", "CMakeLists.txt"));
supportingFiles.add(new SupportingFile("README.mustache", "", "README.md"));
languageSpecificPrimitives = new HashSet<String>(
Arrays.asList("int", "char", "bool", "long", "float", "double", "int32_t", "int64_t"));
typeMapping = new HashMap<String, String>();
typeMapping.put("date", "std::string");
typeMapping.put("DateTime", "std::string");
typeMapping.put("string", "std::string");
typeMapping.put("integer", "int32_t");
typeMapping.put("long", "int64_t");
typeMapping.put("boolean", "bool");
typeMapping.put("array", "std::vector");
typeMapping.put("map", "std::map");
typeMapping.put("file", "std::string");
typeMapping.put("object", "Object");
typeMapping.put("binary", "std::string");
typeMapping.put("number", "double");
typeMapping.put("UUID", "std::string");
typeMapping.put("URI", "std::string");
typeMapping.put("ByteArray", "std::string");
importMapping = new HashMap<String, String>();
importMapping.put("std::vector", "#include <vector>");
importMapping.put("std::map", "#include <map>");
importMapping.put("std::string", "#include <string>");
importMapping.put("Object", "#include \"Object.h\"");
}
@Override
public void processOpts() {
super.processOpts();
if (additionalProperties.containsKey(HELPERS_PACKAGE_NAME)) {
helpersPackage = (String) additionalProperties.get(HELPERS_PACKAGE_NAME);
}
if (additionalProperties.containsKey("modelNamePrefix")) {
additionalProperties().put("prefix", modelNamePrefix);
supportingFiles.clear();
supportingFiles.add(new SupportingFile("helpers-header.mustache", "model", modelNamePrefix + "Helpers.h"));
supportingFiles.add(new SupportingFile("helpers-source.mustache", "model", modelNamePrefix + "Helpers.cpp"));
supportingFiles.add(new SupportingFile("main-api-server.mustache", "", modelNamePrefix + "main-api-server.cpp"));
supportingFiles.add(new SupportingFile("cmake.mustache", "", "CMakeLists.txt"));
supportingFiles.add(new SupportingFile("README.mustache", "", "README.md"));
}
if (additionalProperties.containsKey(RESERVED_WORD_PREFIX_OPTION)) {
reservedWordPrefix = (String) additionalProperties.get(RESERVED_WORD_PREFIX_OPTION);
}
additionalProperties.put("modelNamespaceDeclarations", modelPackage.split("\\."));
additionalProperties.put("modelNamespace", modelPackage.replaceAll("\\.", "::"));
additionalProperties.put("apiNamespaceDeclarations", apiPackage.split("\\."));
additionalProperties.put("apiNamespace", apiPackage.replaceAll("\\.", "::"));
additionalProperties.put("helpersNamespaceDeclarations", helpersPackage.split("\\."));
additionalProperties.put("helpersNamespace", helpersPackage.replaceAll("\\.", "::"));
additionalProperties.put(RESERVED_WORD_PREFIX_OPTION, reservedWordPrefix);
if (additionalProperties.containsKey(OPTIONAL_EXTERNAL_LIB)) {
setAddExternalLibs(convertPropertyToBooleanAndWriteBack(OPTIONAL_EXTERNAL_LIB));
} else {
additionalProperties.put(OPTIONAL_EXTERNAL_LIB, isAddExternalLibs);
}
// setup model templates
if (additionalProperties.containsKey(OPTION_USE_STRUCT_MODEL))
isUseStructModel = convertPropertyToBooleanAndWriteBack(OPTION_USE_STRUCT_MODEL);
if (isUseStructModel) {
LOGGER.info("Using struct-based model template");
modelTemplateFiles.put("model-struct-header.mustache", ".h");
modelTemplateFiles.put("model-struct-source.mustache", ".cpp");
} else {
LOGGER.info("Using get/set-based model template");
modelTemplateFiles.put("model-header.mustache", ".h");
modelTemplateFiles.put("model-source.mustache", ".cpp");
}
}
@Override
public String toModelImport(String name) {
if (importMapping.containsKey(name)) {
return importMapping.get(name);
} else {
return "#include \"" + name + ".h\"";
}
}
@Override
public CodegenModel fromModel(String name, Schema model) {
CodegenModel codegenModel = super.fromModel(name, model);
Set<String> oldImports = codegenModel.imports;
codegenModel.imports = new HashSet<>();
for (String imp : oldImports) {
String newImp = toModelImport(imp);
if (!newImp.isEmpty()) {
codegenModel.imports.add(newImp);
}
}
return codegenModel;
}
@Override
public CodegenOperation fromOperation(String path, String httpMethod, Operation operation, List<Server> servers) {
CodegenOperation op = super.fromOperation(path, httpMethod, operation, servers);
if (operation.getResponses() != null && !operation.getResponses().isEmpty()) {
ApiResponse apiResponse = findMethodResponse(operation.getResponses());
if (apiResponse != null) {
Schema response = ModelUtils.getSchemaFromResponse(apiResponse);
if (response != null) {
CodegenProperty cm = fromProperty("response", response);
op.vendorExtensions.put("x-codegen-response", cm);
if ("HttpContent".equals(cm.dataType)) {
op.vendorExtensions.put("x-codegen-response-ishttpcontent", true);
}
}
}
}
String pathForOatpp = path.replaceAll("\\{(.*?)}", ":$1");
op.vendorExtensions.put("x-codegen-oatpp-path", pathForOatpp);
return op;
}
@SuppressWarnings("unchecked")
@Override
public Map<String, Object> postProcessOperationsWithModels(Map<String, Object> objs, List<Object> allModels) {
Map<String, Object> operations = (Map<String, Object>) objs.get("operations");
String classname = (String) operations.get("classname");
operations.put("classnameSnakeUpperCase", underscore(classname).toUpperCase(Locale.ROOT));
operations.put("classnameSnakeLowerCase", underscore(classname).toLowerCase(Locale.ROOT));
List<CodegenOperation> operationList = (List<CodegenOperation>) operations.get("operation");
for (CodegenOperation op : operationList) {
boolean consumeJson = false;
boolean isParsingSupported = true;
if (op.bodyParam != null) {
if (op.bodyParam.vendorExtensions == null) {
op.bodyParam.vendorExtensions = new HashMap<>();
}
boolean isStringOrDate = op.bodyParam.isString || op.bodyParam.isDate;
op.bodyParam.vendorExtensions.put("x-codegen-oatpp-is-string-or-date", isStringOrDate);
}
if (op.consumes != null) {
for (Map<String, String> consume : op.consumes) {
if (consume.get("mediaType") != null && consume.get("mediaType").equals("application/json")) {
consumeJson = true;
}
}
}
op.httpMethod = op.httpMethod.substring(0, 1).toUpperCase(Locale.ROOT) + op.httpMethod.substring(1).toLowerCase(Locale.ROOT);
for (CodegenParameter param : op.allParams) {
if (param.isFormParam) isParsingSupported = false;
if (param.isFile) isParsingSupported = false;
if (param.isCookieParam) isParsingSupported = false;
//TODO: This changes the info about the real type but it is needed to parse the header params
if (param.isHeaderParam) {
param.dataType = "Oatpp::Optional<Oatpp::Http::Header::Raw>";
param.baseType = "Oatpp::Optional<Oatpp::Http::Header::Raw>";
} else if (param.isQueryParam) {
if (param.isPrimitiveType) {
param.dataType = "Oatpp::Optional<" + param.dataType + ">";
} else {
param.dataType = "Oatpp::Optional<" + param.dataType + ">";
param.baseType = "Oatpp::Optional<" + param.baseType + ">";
}
}
}
if (op.vendorExtensions == null) {
op.vendorExtensions = new HashMap<>();
}
op.vendorExtensions.put("x-codegen-oatpp-consumes-json", consumeJson);
op.vendorExtensions.put("x-codegen-oatpp-is-parsing-supported", isParsingSupported);
// Check if any one of the operations needs a model, then at API file level, at least one model has to be included.
for (String hdr : op.imports) {
if (importMapping.containsKey(hdr)) {
continue;
}
operations.put("hasModelImport", true);
}
}
return objs;
}
@Override
public String toModelFilename(String name) {
return toModelName(name);
}
@Override
public String apiFilename(String templateName, String tag) {
String result = super.apiFilename(templateName, tag);
if (templateName.endsWith("impl-header.mustache")) {
int ix = result.lastIndexOf(File.separatorChar);
result = result.substring(0, ix) + result.substring(ix, result.length() - 2) + "Impl.h";
result = result.replace(apiFileFolder(), implFileFolder());
} else if (templateName.endsWith("impl-source.mustache")) {
int ix = result.lastIndexOf(File.separatorChar);
result = result.substring(0, ix) + result.substring(ix, result.length() - 4) + "Impl.cpp";
result = result.replace(apiFileFolder(), implFileFolder());
}
return result;
}
@Override
public String toApiFilename(String name) {
return toApiName(name);
}
/**
* Optional - type declaration. This is a String which is used by the
* templates to instantiate your types. There is typically special handling
* for different property types
*
* @return a string value used as the `dataType` field for model templates,
* `returnType` for api templates
*/
@Override
public String getTypeDeclaration(Schema p) {
String openAPIType = getSchemaType(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) + "<std::string, " + getTypeDeclaration(inner) + ">";
} else if (ModelUtils.isByteArraySchema(p)) {
return "std::string";
} else if (ModelUtils.isStringSchema(p)
|| ModelUtils.isDateSchema(p)
|| ModelUtils.isDateTimeSchema(p) || ModelUtils.isFileSchema(p)
|| languageSpecificPrimitives.contains(openAPIType)) {
return toModelName(openAPIType);
}
return openAPIType;
}
@Override
public String toDefaultValue(Schema p) {
if (ModelUtils.isBooleanSchema(p)) {
return "false";
} else if (ModelUtils.isDateSchema(p)) {
return "\"\"";
} else if (ModelUtils.isDateTimeSchema(p)) {
return "\"\"";
} else if (ModelUtils.isNumberSchema(p)) {
if (ModelUtils.isFloatSchema(p)) {
return "0.0f";
}
return "0.0";
} else if (ModelUtils.isIntegerSchema(p)) {
if (ModelUtils.isLongSchema(p)) {
return "0L";
}
return "0";
} else if (ModelUtils.isByteArraySchema(p)) {
return "\"\"";
} else if (ModelUtils.isMapSchema(p)) {
String inner = getSchemaType(getAdditionalProperties(p));
return "std::map<std::string, " + inner + ">()";
} else if (ModelUtils.isArraySchema(p)) {
ArraySchema ap = (ArraySchema) p;
String inner = getSchemaType(ap.getItems());
return "std::vector<" + inner + ">()";
} else if (!StringUtils.isEmpty(p.get$ref())) { // model
return toModelName(ModelUtils.getSimpleRef(p.get$ref())) + "()";
} else if (ModelUtils.isStringSchema(p)) {
return "\"\"";
}
return "";
}
/**
* Location to write model files. You can use the modelPackage() as defined
* when the class is instantiated
*/
public String modelFileFolder() {
return (outputFolder + "/model").replace("/", File.separator);
}
/**
* Location to write api files. You can use the apiPackage() as defined when
* the class is instantiated
*/
@Override
public String apiFileFolder() {
return (outputFolder + "/api").replace("/", File.separator);
}
private String implFileFolder() {
return (outputFolder + "/" + implFolder).replace("/", File.separator);
}
/**
* Optional - OpenAPI type conversion. This is used to map OpenAPI types in
* a `Schema` into either language specific types via `typeMapping` or
* into complex models if there is not a mapping.
*
* @return a string value of the type or complex model for this property
*/
@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 toModelName(type);
} else
type = openAPIType;
return toModelName(type);
}
@Override
public String getTypeDeclaration(String str) {
return toModelName(str);
}
/**
* Specify whether external libraries will be added during the generation
*
* @param value the value to be set
*/
public void setAddExternalLibs(boolean value) {
isAddExternalLibs = value;
}
}

View File

@@ -229,7 +229,7 @@ public class CppPistacheServerCodegen extends AbstractCppCodegen {
ApiResponse apiResponse = findMethodResponse(operation.getResponses());
if (apiResponse != null) {
Schema response = modelUtils.getSchemaFromResponse(apiResponse);
Schema response = ModelUtils.getSchemaFromResponse(apiResponse);
if (response != null) {
CodegenProperty cm = fromProperty("response", response);
op.vendorExtensions.put("x-codegen-response", cm);
@@ -350,20 +350,20 @@ public class CppPistacheServerCodegen extends AbstractCppCodegen {
public String getTypeDeclaration(Schema p) {
String openAPIType = getSchemaType(p);
if (modelUtils.isArraySchema(p)) {
if (ModelUtils.isArraySchema(p)) {
ArraySchema ap = (ArraySchema) p;
Schema inner = ap.getItems();
return getSchemaType(p) + "<" + getTypeDeclaration(inner) + ">";
}
if (modelUtils.isMapSchema(p)) {
if (ModelUtils.isMapSchema(p)) {
Schema inner = getAdditionalProperties(p);
return getSchemaType(p) + "<std::string, " + getTypeDeclaration(inner) + ">";
} else if (modelUtils.isByteArraySchema(p)) {
} else if (ModelUtils.isByteArraySchema(p)) {
return "std::string";
}
if (modelUtils.isStringSchema(p)
|| modelUtils.isDateSchema(p)
|| modelUtils.isDateTimeSchema(p) || modelUtils.isFileSchema(p)
if (ModelUtils.isStringSchema(p)
|| ModelUtils.isDateSchema(p)
|| ModelUtils.isDateTimeSchema(p) || ModelUtils.isFileSchema(p)
|| languageSpecificPrimitives.contains(openAPIType)) {
return toModelName(openAPIType);
}
@@ -373,34 +373,34 @@ public class CppPistacheServerCodegen extends AbstractCppCodegen {
@Override
public String toDefaultValue(Schema p) {
if (modelUtils.isBooleanSchema(p)) {
if (ModelUtils.isBooleanSchema(p)) {
return "false";
} else if (modelUtils.isDateSchema(p)) {
} else if (ModelUtils.isDateSchema(p)) {
return "\"\"";
} else if (modelUtils.isDateTimeSchema(p)) {
} else if (ModelUtils.isDateTimeSchema(p)) {
return "\"\"";
} else if (modelUtils.isNumberSchema(p)) {
if (modelUtils.isFloatSchema(p)) {
} else if (ModelUtils.isNumberSchema(p)) {
if (ModelUtils.isFloatSchema(p)) {
return "0.0f";
}
return "0.0";
} else if (modelUtils.isIntegerSchema(p)) {
if (modelUtils.isLongSchema(p)) {
} else if (ModelUtils.isIntegerSchema(p)) {
if (ModelUtils.isLongSchema(p)) {
return "0L";
}
return "0";
} else if (modelUtils.isByteArraySchema(p)) {
} else if (ModelUtils.isByteArraySchema(p)) {
return "\"\"";
} else if (modelUtils.isMapSchema(p)) {
} else if (ModelUtils.isMapSchema(p)) {
String inner = getSchemaType(getAdditionalProperties(p));
return "std::map<std::string, " + inner + ">()";
} else if (modelUtils.isArraySchema(p)) {
} else if (ModelUtils.isArraySchema(p)) {
ArraySchema ap = (ArraySchema) p;
String inner = getSchemaType(ap.getItems());
return "std::vector<" + inner + ">()";
} else if (!StringUtils.isEmpty(p.get$ref())) { // model
return toModelName(modelUtils.getSimpleRef(p.get$ref())) + "()";
} else if (modelUtils.isStringSchema(p)) {
return toModelName(ModelUtils.getSimpleRef(p.get$ref())) + "()";
} else if (ModelUtils.isStringSchema(p)) {
return "\"\"";
}

View File

@@ -181,16 +181,16 @@ public class CppQt5AbstractCodegen extends AbstractCppCodegen implements Codegen
public String getTypeDeclaration(Schema p) {
String openAPIType = getSchemaType(p);
if (modelUtils.isArraySchema(p)) {
if (ModelUtils.isArraySchema(p)) {
ArraySchema ap = (ArraySchema) p;
Schema inner = ap.getItems();
return getSchemaType(p) + "<" + getTypeDeclaration(inner) + ">";
} else if (modelUtils.isMapSchema(p)) {
} else if (ModelUtils.isMapSchema(p)) {
Schema inner = getAdditionalProperties(p);
return getSchemaType(p) + "<QString, " + getTypeDeclaration(inner) + ">";
} else if (modelUtils.isBinarySchema(p)) {
} else if (ModelUtils.isBinarySchema(p)) {
return getSchemaType(p);
} else if (modelUtils.isFileSchema(p)) {
} else if (ModelUtils.isFileSchema(p)) {
return getSchemaType(p);
}
if (foundationClasses.contains(openAPIType)) {
@@ -205,33 +205,33 @@ public class CppQt5AbstractCodegen extends AbstractCppCodegen implements Codegen
@Override
@SuppressWarnings("rawtypes")
public String toDefaultValue(Schema p) {
if (modelUtils.isBooleanSchema(p)) {
if (ModelUtils.isBooleanSchema(p)) {
return "false";
} else if (modelUtils.isDateSchema(p)) {
} else if (ModelUtils.isDateSchema(p)) {
return "NULL";
} else if (modelUtils.isDateTimeSchema(p)) {
} else if (ModelUtils.isDateTimeSchema(p)) {
return "NULL";
} else if (modelUtils.isNumberSchema(p)) {
} else if (ModelUtils.isNumberSchema(p)) {
if (SchemaTypeUtil.FLOAT_FORMAT.equals(p.getFormat())) {
return "0.0f";
}
return "0.0";
} else if (modelUtils.isIntegerSchema(p)) {
} else if (ModelUtils.isIntegerSchema(p)) {
if (SchemaTypeUtil.INTEGER64_FORMAT.equals(p.getFormat())) {
return "0L";
}
return "0";
} else if (modelUtils.isMapSchema(p)) {
} else if (ModelUtils.isMapSchema(p)) {
Schema inner = getAdditionalProperties(p);
return "QMap<QString, " + getTypeDeclaration(inner) + ">()";
} else if (modelUtils.isArraySchema(p)) {
} else if (ModelUtils.isArraySchema(p)) {
ArraySchema ap = (ArraySchema) p;
Schema inner = ap.getItems();
return "QList<" + getTypeDeclaration(inner) + ">()";
} else if (modelUtils.isStringSchema(p)) {
} else if (ModelUtils.isStringSchema(p)) {
return "QString(\"\")";
} else if (!StringUtils.isEmpty(p.get$ref())) {
return toModelName(modelUtils.getSimpleRef(p.get$ref())) + "()";
return toModelName(ModelUtils.getSimpleRef(p.get$ref())) + "()";
}
return "NULL";
}

View File

@@ -80,7 +80,6 @@ public class CppQt5ClientCodegen extends CppQt5AbstractCodegen implements Codege
supportingFiles.add(new SupportingFile("HttpFileElement.cpp.mustache", sourceFolder, PREFIX + "HttpFileElement.cpp"));
supportingFiles.add(new SupportingFile("object.mustache", sourceFolder, PREFIX + "Object.h"));
supportingFiles.add(new SupportingFile("enum.mustache", sourceFolder, PREFIX + "Enum.h"));
supportingFiles.add(new SupportingFile("README.mustache", "","README.md"));
supportingFiles.add(new SupportingFile("CMakeLists.txt.mustache", sourceFolder, "CMakeLists.txt"));
if (optionalProjectFileFlag) {
supportingFiles.add(new SupportingFile("Project.mustache", sourceFolder, "client.pri"));
@@ -109,7 +108,6 @@ public class CppQt5ClientCodegen extends CppQt5AbstractCodegen implements Codege
supportingFiles.add(new SupportingFile("HttpFileElement.cpp.mustache", sourceFolder, modelNamePrefix + "HttpFileElement.cpp"));
supportingFiles.add(new SupportingFile("object.mustache", sourceFolder, modelNamePrefix + "Object.h"));
supportingFiles.add(new SupportingFile("enum.mustache", sourceFolder, modelNamePrefix + "Enum.h"));
supportingFiles.add(new SupportingFile("README.mustache", "","README.md"));
supportingFiles.add(new SupportingFile("CMakeLists.txt.mustache", sourceFolder, "CMakeLists.txt"));

View File

@@ -27,6 +27,7 @@ import io.swagger.v3.oas.models.servers.Server;
import org.apache.commons.lang3.StringUtils;
import org.openapitools.codegen.*;
import org.openapitools.codegen.meta.features.*;
import org.openapitools.codegen.utils.ModelUtils;
import java.util.*;
@@ -270,8 +271,8 @@ public class CppRestSdkClientCodegen extends AbstractCppCodegen {
ApiResponse methodResponse = findMethodResponse(operation.getResponses());
if (methodResponse != null) {
Schema response = modelUtils.getSchemaFromResponse(methodResponse);
response = modelUtils.unaliasSchema(response, importMapping);
Schema response = ModelUtils.getSchemaFromResponse(methodResponse);
response = ModelUtils.unaliasSchema(this.openAPI, response, importMapping);
if (response != null) {
CodegenProperty cm = fromProperty("response", response);
op.vendorExtensions.put("x-codegen-response", cm);
@@ -343,18 +344,18 @@ public class CppRestSdkClientCodegen extends AbstractCppCodegen {
public String getTypeDeclaration(Schema p) {
String openAPIType = getSchemaType(p);
if (modelUtils.isArraySchema(p)) {
if (ModelUtils.isArraySchema(p)) {
ArraySchema ap = (ArraySchema) p;
Schema inner = ap.getItems();
return getSchemaType(p) + "<" + getTypeDeclaration(inner) + ">";
} else if (modelUtils.isMapSchema(p)) {
} else if (ModelUtils.isMapSchema(p)) {
Schema inner = getAdditionalProperties(p);
return getSchemaType(p) + "<utility::string_t, " + getTypeDeclaration(inner) + ">";
} else if (modelUtils.isFileSchema(p) || modelUtils.isBinarySchema(p)) {
} else if (ModelUtils.isFileSchema(p) || ModelUtils.isBinarySchema(p)) {
return "std::shared_ptr<" + openAPIType + ">";
} else if (modelUtils.isStringSchema(p)
|| modelUtils.isDateSchema(p) || modelUtils.isDateTimeSchema(p)
|| modelUtils.isFileSchema(p) || modelUtils.isUUIDSchema(p)
} else if (ModelUtils.isStringSchema(p)
|| ModelUtils.isDateSchema(p) || ModelUtils.isDateTimeSchema(p)
|| ModelUtils.isFileSchema(p) || ModelUtils.isUUIDSchema(p)
|| languageSpecificPrimitives.contains(openAPIType)) {
return toModelName(openAPIType);
}
@@ -364,26 +365,26 @@ public class CppRestSdkClientCodegen extends AbstractCppCodegen {
@Override
public String toDefaultValue(Schema p) {
if (modelUtils.isBooleanSchema(p)) {
if (ModelUtils.isBooleanSchema(p)) {
return "false";
} else if (modelUtils.isDateSchema(p)) {
} else if (ModelUtils.isDateSchema(p)) {
return "utility::datetime()";
} else if (modelUtils.isDateTimeSchema(p)) {
} else if (ModelUtils.isDateTimeSchema(p)) {
return "utility::datetime()";
} else if (modelUtils.isNumberSchema(p)) {
if (modelUtils.isFloatSchema(p)) {
} else if (ModelUtils.isNumberSchema(p)) {
if (ModelUtils.isFloatSchema(p)) {
return "0.0f";
}
return "0.0";
} else if (modelUtils.isIntegerSchema(p)) {
if (modelUtils.isLongSchema(p)) {
} else if (ModelUtils.isIntegerSchema(p)) {
if (ModelUtils.isLongSchema(p)) {
return "0L";
}
return "0";
} else if (modelUtils.isMapSchema(p)) {
} else if (ModelUtils.isMapSchema(p)) {
String inner = getSchemaType(getAdditionalProperties(p));
return "std::map<utility::string_t, " + inner + ">()";
} else if (modelUtils.isArraySchema(p)) {
} else if (ModelUtils.isArraySchema(p)) {
ArraySchema ap = (ArraySchema) p;
String inner = getSchemaType(ap.getItems());
if (!languageSpecificPrimitives.contains(inner)) {
@@ -391,10 +392,10 @@ public class CppRestSdkClientCodegen extends AbstractCppCodegen {
}
return "std::vector<" + inner + ">()";
} else if (!StringUtils.isEmpty(p.get$ref())) {
return "new " + toModelName(modelUtils.getSimpleRef(p.get$ref())) + "()";
} else if (modelUtils.isStringSchema(p)) {
return "new " + toModelName(ModelUtils.getSimpleRef(p.get$ref())) + "()";
} else if (ModelUtils.isStringSchema(p)) {
return "utility::conversions::to_string_t(\"\")";
} else if (modelUtils.isFreeFormObject(p)) {
} else if (isFreeFormObject(p)) {
return "new Object()";
}
@@ -445,7 +446,7 @@ public class CppRestSdkClientCodegen extends AbstractCppCodegen {
private void postProcessParentModels(final Map<String, Object> models) {
for (final String parent : parentModels) {
final CodegenModel parentModel = modelUtils.getModelByName(parent, models);
final CodegenModel parentModel = ModelUtils.getModelByName(parent, models);
final Collection<CodegenModel> childrenModels = childrenByParent.get(parent);
for (final CodegenModel child : childrenModels) {
processParentPropertiesInChildModel(parentModel, child);

View File

@@ -345,18 +345,18 @@ public class CppRestbedServerCodegen extends AbstractCppCodegen {
public String getTypeDeclaration(Schema p) {
String openAPIType = getSchemaType(p);
if (modelUtils.isArraySchema(p)) {
if (ModelUtils.isArraySchema(p)) {
ArraySchema ap = (ArraySchema) p;
Schema inner = ap.getItems();
return getSchemaType(p) + "<" + getTypeDeclaration(inner) + ">";
} else if (modelUtils.isMapSchema(p)) {
} else if (ModelUtils.isMapSchema(p)) {
Schema inner = getAdditionalProperties(p);
return getSchemaType(p) + "<std::string, " + getTypeDeclaration(inner) + ">";
} else if (modelUtils.isByteArraySchema(p)) {
} else if (ModelUtils.isByteArraySchema(p)) {
return "std::string";
} else if (modelUtils.isStringSchema(p)
|| modelUtils.isDateSchema(p)
|| modelUtils.isDateTimeSchema(p) || modelUtils.isFileSchema(p)
} else if (ModelUtils.isStringSchema(p)
|| ModelUtils.isDateSchema(p)
|| ModelUtils.isDateTimeSchema(p) || ModelUtils.isFileSchema(p)
|| languageSpecificPrimitives.contains(openAPIType)) {
return toModelName(openAPIType);
}
@@ -366,32 +366,32 @@ public class CppRestbedServerCodegen extends AbstractCppCodegen {
@Override
public String toDefaultValue(Schema p) {
if (modelUtils.isStringSchema(p)) {
if (ModelUtils.isStringSchema(p)) {
if (p.getDefault() != null) {
return "\"" + p.getDefault().toString() + "\"";
} else {
return "\"\"";
}
} else if (modelUtils.isBooleanSchema(p)) {
} else if (ModelUtils.isBooleanSchema(p)) {
if (p.getDefault() != null) {
return p.getDefault().toString();
} else {
return "false";
}
} else if (modelUtils.isDateSchema(p)) {
} else if (ModelUtils.isDateSchema(p)) {
if (p.getDefault() != null) {
return "\"" + p.getDefault().toString() + "\"";
} else {
return "\"\"";
}
} else if (modelUtils.isDateTimeSchema(p)) {
} else if (ModelUtils.isDateTimeSchema(p)) {
if (p.getDefault() != null) {
return "\"" + p.getDefault().toString() + "\"";
} else {
return "\"\"";
}
} else if (modelUtils.isNumberSchema(p)) {
if (modelUtils.isFloatSchema(p)) { // float
} else if (ModelUtils.isNumberSchema(p)) {
if (ModelUtils.isFloatSchema(p)) { // float
if (p.getDefault() != null) {
return p.getDefault().toString() + "f";
} else {
@@ -404,8 +404,8 @@ public class CppRestbedServerCodegen extends AbstractCppCodegen {
return "0.0";
}
}
} else if (modelUtils.isIntegerSchema(p)) {
if (modelUtils.isLongSchema(p)) { // long
} else if (ModelUtils.isIntegerSchema(p)) {
if (ModelUtils.isLongSchema(p)) { // long
if (p.getDefault() != null) {
return p.getDefault().toString() + "L";
} else {
@@ -418,16 +418,16 @@ public class CppRestbedServerCodegen extends AbstractCppCodegen {
return "0";
}
}
} else if (modelUtils.isByteArraySchema(p)) {
} else if (ModelUtils.isByteArraySchema(p)) {
if (p.getDefault() != null) {
return "\"" + p.getDefault().toString() + "\"";
} else {
return "\"\"";
}
} else if (modelUtils.isMapSchema(p)) {
} else if (ModelUtils.isMapSchema(p)) {
String inner = getSchemaType(getAdditionalProperties(p));
return "std::map<std::string, " + inner + ">()";
} else if (modelUtils.isArraySchema(p)) {
} else if (ModelUtils.isArraySchema(p)) {
ArraySchema ap = (ArraySchema) p;
String inner = getSchemaType(ap.getItems());
if (!languageSpecificPrimitives.contains(inner)) {
@@ -435,7 +435,7 @@ public class CppRestbedServerCodegen extends AbstractCppCodegen {
}
return "std::vector<" + inner + ">()";
} else if (!StringUtils.isEmpty(p.get$ref())) {
return "std::make_shared<" + toModelName(modelUtils.getSimpleRef(p.get$ref())) + ">()";
return "std::make_shared<" + toModelName(ModelUtils.getSimpleRef(p.get$ref())) + ">()";
}
return "nullptr";

View File

@@ -161,9 +161,9 @@ public class CppTizenClientCodegen extends AbstractCppCodegen implements Codegen
@Override
public String toInstantiationType(Schema p) {
if (modelUtils.isMapSchema(p)) {
if (ModelUtils.isMapSchema(p)) {
return instantiationTypes.get("map");
} else if (modelUtils.isArraySchema(p)) {
} else if (ModelUtils.isArraySchema(p)) {
return instantiationTypes.get("array");
} else {
return null;
@@ -232,28 +232,28 @@ public class CppTizenClientCodegen extends AbstractCppCodegen implements Codegen
//Might not be needed
@Override
public String toDefaultValue(Schema p) {
if (modelUtils.isBooleanSchema(p)) {
if (ModelUtils.isBooleanSchema(p)) {
return "bool(false)";
} else if (modelUtils.isNumberSchema(p)) {
} else if (ModelUtils.isNumberSchema(p)) {
if (SchemaTypeUtil.FLOAT_FORMAT.equals(p.getFormat())) {
return "float(0)";
}
return "double(0)";
} else if (modelUtils.isIntegerSchema(p)) {
} else if (ModelUtils.isIntegerSchema(p)) {
if (SchemaTypeUtil.INTEGER64_FORMAT.equals(p.getFormat())) {
return "long(0)";
}
return "int(0)";
} else if (modelUtils.isMapSchema(p)) {
} else if (ModelUtils.isMapSchema(p)) {
return "new std::map()";
} else if (modelUtils.isArraySchema(p)) {
} else if (ModelUtils.isArraySchema(p)) {
return "new std::list()";
} else if (!StringUtils.isEmpty(p.get$ref())) {
return "new " + toModelName(modelUtils.getSimpleRef(p.get$ref())) + "()";
} else if (modelUtils.isDateSchema(p) || modelUtils.isDateTimeSchema(p)) {
return "new " + toModelName(ModelUtils.getSimpleRef(p.get$ref())) + "()";
} else if (ModelUtils.isDateSchema(p) || ModelUtils.isDateTimeSchema(p)) {
return "null";
} else if (modelUtils.isStringSchema(p)) {
} else if (ModelUtils.isStringSchema(p)) {
return "std::string()";
}
return "null";

View File

@@ -379,11 +379,11 @@ public class CppUE4ClientCodegen extends AbstractCppCodegen {
public String getTypeDeclaration(Schema p) {
String openAPIType = getSchemaType(p);
if (modelUtils.isArraySchema(p)) {
if (ModelUtils.isArraySchema(p)) {
ArraySchema ap = (ArraySchema) p;
String inner = getSchemaType(ap.getItems());
return getSchemaType(p) + "<" + getTypeDeclaration(inner) + ">";
} else if (modelUtils.isMapSchema(p)) {
} else if (ModelUtils.isMapSchema(p)) {
String inner = getSchemaType(getAdditionalProperties(p));
return getSchemaType(p) + "<FString, " + getTypeDeclaration(inner) + ">";
}
@@ -404,41 +404,41 @@ public class CppUE4ClientCodegen extends AbstractCppCodegen {
@Override
public String toDefaultValue(Schema p) {
if (modelUtils.isStringSchema(p)) {
if (ModelUtils.isStringSchema(p)) {
if (p.getDefault() != null) {
return "TEXT(\"" + p.getDefault().toString() + "\")";
} else {
return null;
}
} else if (modelUtils.isBooleanSchema(p)) {
} else if (ModelUtils.isBooleanSchema(p)) {
if (p.getDefault() != null) {
return p.getDefault().toString();
} else {
return "false";
}
} else if (modelUtils.isDateSchema(p)) {
} else if (ModelUtils.isDateSchema(p)) {
return "FDateTime(0)";
} else if (modelUtils.isDateTimeSchema(p)) {
} else if (ModelUtils.isDateTimeSchema(p)) {
return "FDateTime(0)";
} else if (modelUtils.isDoubleSchema(p)) {
} else if (ModelUtils.isDoubleSchema(p)) {
if (p.getDefault() != null) {
return p.getDefault().toString();
} else {
return "0.0";
}
} else if (modelUtils.isFloatSchema(p)) {
} else if (ModelUtils.isFloatSchema(p)) {
if (p.getDefault() != null) {
return p.getDefault().toString();
} else {
return "0.0f";
}
} else if (modelUtils.isIntegerSchema(p)) {
} else if (ModelUtils.isIntegerSchema(p)) {
if (p.getDefault() != null) {
return p.getDefault().toString();
} else {
return "0";
}
} else if (modelUtils.isLongSchema(p)) {
} else if (ModelUtils.isLongSchema(p)) {
if (p.getDefault() != null) {
return p.getDefault().toString();
} else {

View File

@@ -412,14 +412,14 @@ public class DartClientCodegen extends DefaultCodegen implements CodegenConfig {
@Override
public String toDefaultValue(Schema schema) {
if (modelUtils.isMapSchema(schema)) {
if (ModelUtils.isMapSchema(schema)) {
return "const {}";
} else if (modelUtils.isArraySchema(schema)) {
} else if (ModelUtils.isArraySchema(schema)) {
return "const []";
}
if (schema.getDefault() != null) {
if (modelUtils.isStringSchema(schema)) {
if (ModelUtils.isStringSchema(schema)) {
return "'" + schema.getDefault().toString().replaceAll("'", "\\'") + "'";
}
return schema.getDefault().toString();
@@ -430,11 +430,11 @@ public class DartClientCodegen extends DefaultCodegen implements CodegenConfig {
@Override
public String getTypeDeclaration(Schema p) {
if (modelUtils.isArraySchema(p)) {
if (ModelUtils.isArraySchema(p)) {
ArraySchema ap = (ArraySchema) p;
Schema inner = ap.getItems();
return getSchemaType(p) + "<" + getTypeDeclaration(inner) + ">";
} else if (modelUtils.isMapSchema(p)) {
} else if (ModelUtils.isMapSchema(p)) {
Schema inner = getAdditionalProperties(p);
return getSchemaType(p) + "<String, " + getTypeDeclaration(inner) + ">";
@@ -617,7 +617,7 @@ public class DartClientCodegen extends DefaultCodegen implements CodegenConfig {
return; // skip if DART_POST_PROCESS_FILE env variable is not defined
}
// only process the following type (or we can simply rely on the file extension to check if it's a Dart file)
// only procees the following type (or we can simply rely on the file extension to check if it's a Dart file)
Set<String> supportedFileType = Sets.newHashSet(
"supporting-mustache",
"model-test",

View File

@@ -51,7 +51,7 @@ public class DartDioClientCodegen extends DartClientCodegen {
private static final String IS_FORMAT_JSON = "jsonFormat";
private static final String CLIENT_NAME = "clientName";
private static final Set<String> modelToIgnore = new HashSet<>();
private static Set<String> modelToIgnore = new HashSet<>();
static {
modelToIgnore.add("datetime");
@@ -71,6 +71,10 @@ public class DartDioClientCodegen extends DartClientCodegen {
embeddedTemplateDir = "dart-dio";
this.setTemplateDir(embeddedTemplateDir);
//no tests at this time
modelTestTemplateFiles.clear();
apiTestTemplateFiles.clear();
cliOptions.add(new CliOption(NULLABLE_FIELDS, "Is the null fields should be in the JSON payload"));
CliOption dateLibrary = new CliOption(DATE_LIBRARY, "Option. Date library to use").defaultValue(this.getDateLibrary());
Map<String, String> dateOptions = new HashMap<>();
@@ -84,7 +88,6 @@ public class DartDioClientCodegen extends DartClientCodegen {
typeMapping.put("AnyType", "Object");
importMapping.put("BuiltList", "package:built_collection/built_collection.dart");
importMapping.put("BuiltSet", "package:built_collection/built_collection.dart");
importMapping.put("BuiltMap", "package:built_collection/built_collection.dart");
importMapping.put("JsonObject", "package:built_value/json_object.dart");
importMapping.put("Uint8List", "dart:typed_data");
@@ -106,6 +109,7 @@ public class DartDioClientCodegen extends DartClientCodegen {
this.nullableFields = nullableFields;
}
@Override
public String getName() {
return "dart-dio";
@@ -118,14 +122,14 @@ public class DartDioClientCodegen extends DartClientCodegen {
@Override
public String toDefaultValue(Schema schema) {
if (modelUtils.isMapSchema(schema)) {
if (ModelUtils.isMapSchema(schema)) {
return "const {}";
} else if (modelUtils.isArraySchema(schema)) {
} else if (ModelUtils.isArraySchema(schema)) {
return "const []";
}
if (schema.getDefault() != null) {
if (modelUtils.isStringSchema(schema)) {
if (ModelUtils.isStringSchema(schema)) {
return "'" + schema.getDefault().toString().replaceAll("'", "\\'") + "'";
}
return schema.getDefault().toString();
@@ -312,11 +316,6 @@ public class DartDioClientCodegen extends DartClientCodegen {
if (property.dataType.contains("JsonObject")) {
model.imports.add("JsonObject");
}
if (property.isEnum) {
// enums are generated with built_value and make use of BuiltSet
model.imports.add("BuiltSet");
}
}
@Override
@@ -379,4 +378,5 @@ public class DartDioClientCodegen extends DartClientCodegen {
return objs;
}
}

View File

@@ -132,14 +132,14 @@ public class DartJaguarClientCodegen extends DartClientCodegen {
@Override
public String toDefaultValue(Schema schema) {
if (modelUtils.isMapSchema(schema)) {
if (ModelUtils.isMapSchema(schema)) {
return "const {}";
} else if (modelUtils.isArraySchema(schema)) {
} else if (ModelUtils.isArraySchema(schema)) {
return "const []";
}
if (schema.getDefault() != null) {
if (modelUtils.isStringSchema(schema)) {
if (ModelUtils.isStringSchema(schema)) {
return "'" + schema.getDefault().toString().replaceAll("'", "\\'") + "'";
}
return schema.getDefault().toString();

View File

@@ -264,7 +264,7 @@ public class ElixirClientCodegen extends DefaultCodegen implements CodegenConfig
}
@Override
public void preprocessOpenAPI() {
public void preprocessOpenAPI(OpenAPI openAPI) {
Info info = openAPI.getInfo();
if (moduleName == null) {
if (info.getTitle() != null) {
@@ -490,42 +490,42 @@ public class ElixirClientCodegen extends DefaultCodegen implements CodegenConfig
*/
@Override
public String getTypeDeclaration(Schema p) {
if (modelUtils.isArraySchema(p)) {
if (ModelUtils.isArraySchema(p)) {
ArraySchema ap = (ArraySchema) p;
Schema inner = ap.getItems();
return "[" + getTypeDeclaration(inner) + "]";
} else if (modelUtils.isMapSchema(p)) {
} else if (ModelUtils.isMapSchema(p)) {
Schema inner = getAdditionalProperties(p);
return "%{optional(String.t) => " + getTypeDeclaration(inner) + "}";
} else if (modelUtils.isPasswordSchema(p)) {
} else if (ModelUtils.isPasswordSchema(p)) {
return "String.t";
} else if (modelUtils.isEmailSchema(p)) {
} else if (ModelUtils.isEmailSchema(p)) {
return "String.t";
} else if (modelUtils.isByteArraySchema(p)) {
} else if (ModelUtils.isByteArraySchema(p)) {
return "binary()";
} else if (modelUtils.isUUIDSchema(p)) {
} else if (ModelUtils.isUUIDSchema(p)) {
return "String.t";
} else if (modelUtils.isDateSchema(p)) {
} else if (ModelUtils.isDateSchema(p)) {
return "Date.t";
} else if (modelUtils.isDateTimeSchema(p)) {
} else if (ModelUtils.isDateTimeSchema(p)) {
return "DateTime.t";
} else if (modelUtils.isObjectSchema(p)) {
} else if (ModelUtils.isObjectSchema(p)) {
// TODO How to map it?
return super.getTypeDeclaration(p);
} else if (modelUtils.isIntegerSchema(p)) {
} else if (ModelUtils.isIntegerSchema(p)) {
return "integer()";
} else if (modelUtils.isNumberSchema(p)) {
} else if (ModelUtils.isNumberSchema(p)) {
return "float()";
} else if (modelUtils.isBinarySchema(p) || modelUtils.isFileSchema(p)) {
} else if (ModelUtils.isBinarySchema(p) || ModelUtils.isFileSchema(p)) {
return "String.t";
} else if (modelUtils.isBooleanSchema(p)) {
} else if (ModelUtils.isBooleanSchema(p)) {
return "boolean()";
} else if (!StringUtils.isEmpty(p.get$ref())) { // model
// How to map it?
return super.getTypeDeclaration(p);
} else if (modelUtils.isFileSchema(p)) {
} else if (ModelUtils.isFileSchema(p)) {
return "String.t";
} else if (modelUtils.isStringSchema(p)) {
} else if (ModelUtils.isStringSchema(p)) {
return "String.t";
}
return super.getTypeDeclaration(p);

View File

@@ -23,7 +23,6 @@ import com.samskivert.mustache.Mustache.Lambda;
import com.samskivert.mustache.Template;
import io.swagger.v3.oas.models.media.ArraySchema;
import io.swagger.v3.oas.models.media.Schema;
import org.apache.commons.lang3.StringUtils;
import org.openapitools.codegen.*;
import org.openapitools.codegen.meta.features.*;
import org.openapitools.codegen.utils.ModelUtils;
@@ -38,7 +37,6 @@ import java.util.function.Predicate;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import static org.openapitools.codegen.utils.StringUtils.camelize;
public class ElmClientCodegen extends DefaultCodegen implements CodegenConfig {
@@ -176,31 +174,6 @@ public class ElmClientCodegen extends DefaultCodegen implements CodegenConfig {
return input.replace("\"", "");
}
@Override
public String toOperationId(String operationId) {
// throw exception if method name is empty
if (StringUtils.isEmpty(operationId)) {
throw new RuntimeException("Empty method/operation name (operationId) not allowed");
}
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 sname. Renamed to " + camelize("call_" + operationId), true);
operationId = camelize("call_" + operationId, true);
}
return operationId;
}
@Override
public String toApiName(String name) {
if (name.length() == 0) {
@@ -238,7 +211,7 @@ public class ElmClientCodegen extends DefaultCodegen implements CodegenConfig {
@Override
public String toInstantiationType(Schema p) {
if (modelUtils.isArraySchema(p)) {
if (ModelUtils.isArraySchema(p)) {
ArraySchema ap = (ArraySchema) p;
String inner = getSchemaType(ap.getItems());
return instantiationTypes.get("array") + " " + inner;
@@ -414,19 +387,19 @@ public class ElmClientCodegen extends DefaultCodegen implements CodegenConfig {
@Override
public String toDefaultValue(Schema p) {
if (modelUtils.isStringSchema(p)) {
if (ModelUtils.isStringSchema(p)) {
if (p.getDefault() != null) {
return "\"" + p.getDefault().toString() + "\"";
}
} else if (modelUtils.isBooleanSchema(p)) {
} else if (ModelUtils.isBooleanSchema(p)) {
if (p.getDefault() != null) {
return Boolean.valueOf(p.getDefault().toString()) ? "True" : "False";
}
} else if (modelUtils.isNumberSchema(p)) {
} else if (ModelUtils.isNumberSchema(p)) {
if (p.getDefault() != null) {
return p.getDefault().toString();
}
} else if (modelUtils.isIntegerSchema(p)) {
} else if (ModelUtils.isIntegerSchema(p)) {
if (p.getDefault() != null) {
return p.getDefault().toString();
}
@@ -450,11 +423,11 @@ public class ElmClientCodegen extends DefaultCodegen implements CodegenConfig {
@Override
public String getTypeDeclaration(Schema p) {
if (modelUtils.isArraySchema(p)) {
if (ModelUtils.isArraySchema(p)) {
ArraySchema ap = (ArraySchema) p;
Schema inner = ap.getItems();
return getTypeDeclaration(inner);
} else if (modelUtils.isMapSchema(p)) {
} else if (ModelUtils.isMapSchema(p)) {
Schema inner = getAdditionalProperties(p);
return getTypeDeclaration(inner);
}

View File

@@ -137,7 +137,7 @@ public class ErlangProperCodegen extends DefaultCodegen implements CodegenConfig
@Override
public CodegenModel fromModel(String name, Schema model) {
CodegenModel cm = super.fromModel(name, model);
if(modelUtils.isArraySchema(model)) {
if(ModelUtils.isArraySchema(model)) {
return new CodegenArrayModel(cm, (ArraySchema) model);
} else {
return cm;
@@ -152,7 +152,7 @@ public class ErlangProperCodegen extends DefaultCodegen implements CodegenConfig
@Override
public String getTypeDeclaration(Schema schema) {
String typeDeclaration = super.getSchemaType(schema);
if(modelUtils.isArraySchema(schema)) {
if(ModelUtils.isArraySchema(schema)) {
ArraySchema arraySchema = (ArraySchema) schema;
String complexType = getSchemaType(arraySchema.getItems());
@@ -170,7 +170,7 @@ public class ErlangProperCodegen extends DefaultCodegen implements CodegenConfig
@Override
public String getSchemaType(Schema schema) {
String schemaType = super.getSchemaType(schema);
if(modelUtils.isArraySchema(schema)) {
if(ModelUtils.isArraySchema(schema)) {
ArraySchema arraySchema = (ArraySchema) schema;
String complexType = getSchemaType(arraySchema.getItems());
@@ -183,7 +183,7 @@ public class ErlangProperCodegen extends DefaultCodegen implements CodegenConfig
if(minItems != null && maxItems != null) sb.append(", ").append(maxItems);
return sb.append(")").toString();
} else if(modelUtils.isIntegerSchema(schema)) {
} else if(ModelUtils.isIntegerSchema(schema)) {
StringBuilder sb = new StringBuilder("integer(");
BigDecimal min = schema.getMinimum();
@@ -192,9 +192,9 @@ public class ErlangProperCodegen extends DefaultCodegen implements CodegenConfig
if(min != null && max != null) sb.append(", ").append(max);
return sb.append(")").toString();
} else if(modelUtils.isDateSchema(schema) || modelUtils.isDateTimeSchema(schema)) {
} else if(ModelUtils.isDateSchema(schema) || ModelUtils.isDateTimeSchema(schema)) {
return typeMapping.get(schemaType);
} else if(modelUtils.isStringSchema(schema)) {
} else if(ModelUtils.isStringSchema(schema)) {
StringBuilder sb = new StringBuilder("binary(");
Integer min = schema.getMinLength();
Integer max = schema.getMaxLength();

View File

@@ -235,7 +235,7 @@ public class FlashClientCodegen extends DefaultCodegen implements CodegenConfig
@Override
public String getTypeDeclaration(Schema p) {
if (modelUtils.isArraySchema(p) || modelUtils.isMapSchema(p)) {
if (ModelUtils.isArraySchema(p) || ModelUtils.isMapSchema(p)) {
return getSchemaType(p);
}
return super.getTypeDeclaration(p);
@@ -258,27 +258,27 @@ public class FlashClientCodegen extends DefaultCodegen implements CodegenConfig
@Override
public String toDefaultValue(Schema p) {
if (modelUtils.isBooleanSchema(p)) {
if (ModelUtils.isBooleanSchema(p)) {
return "false";
} else if (modelUtils.isDateSchema(p)) {
} else if (ModelUtils.isDateSchema(p)) {
return "null";
} else if (modelUtils.isDateTimeSchema(p)) {
} else if (ModelUtils.isDateTimeSchema(p)) {
return "null";
} else if (modelUtils.isNumberSchema(p)) {
} else if (ModelUtils.isNumberSchema(p)) {
if (p.getDefault() != null) {
return p.getDefault().toString();
}
return "0.0";
} else if (modelUtils.isIntegerSchema(p)) {
} else if (ModelUtils.isIntegerSchema(p)) {
if (p.getDefault() != null) {
return p.getDefault().toString();
}
return "0";
} else if (modelUtils.isMapSchema(p)) {
} else if (ModelUtils.isMapSchema(p)) {
return "new Dictionary()";
} else if (modelUtils.isArraySchema(p)) {
} else if (ModelUtils.isArraySchema(p)) {
return "new Array()";
} else if (modelUtils.isStringSchema(p)) {
} else if (ModelUtils.isStringSchema(p)) {
return "null";
} else {
return "NaN";

View File

@@ -166,8 +166,8 @@ public class FsharpGiraffeServerCodegen extends AbstractFSharpCodegen {
}
@Override
public void preprocessOpenAPI() {
super.preprocessOpenAPI();
public void preprocessOpenAPI(OpenAPI openAPI) {
super.preprocessOpenAPI(openAPI);
URL url = URLPathUtils.getServerURL(openAPI, serverVariableOverrides());
additionalProperties.put("serverHost", url.getHost());
additionalProperties.put("serverPort", URLPathUtils.getPort(url, 8080));

View File

@@ -349,8 +349,8 @@ public class GoClientCodegen extends AbstractGoCodegen {
@Override
public String toDefaultValue(Schema p) {
p = modelUtils.getReferencedSchema(p);
if (modelUtils.isStringSchema(p)) {
p = ModelUtils.getReferencedSchema(this.openAPI, p);
if (ModelUtils.isStringSchema(p)) {
if (p.getDefault() != null) {
return "\"" + escapeText((String) p.getDefault()) + "\"";
}
@@ -448,17 +448,13 @@ public class GoClientCodegen extends AbstractGoCodegen {
for (CodegenParameter p : op.allParams) {
p.vendorExtensions.put("x-go-example", constructExampleCode(p, modelMaps, processedModelMaps));
}
processedModelMaps.clear();
}
processedModelMaps.clear();
for (CodegenOperation operation : operationList) {
for (CodegenParameter cp : operation.allParams) {
cp.vendorExtensions.put("x-go-example", constructExampleCode(cp, modelMaps, processedModelMaps));
}
if (processedModelMaps.containsKey("time.Time")) {
operation.vendorExtensions.put("x-go-import", " \"time\"");
}
processedModelMaps.clear();
}
return objs;
@@ -466,22 +462,12 @@ public class GoClientCodegen extends AbstractGoCodegen {
private String constructExampleCode(CodegenParameter codegenParameter, HashMap<String, CodegenModel> modelMaps, HashMap<String, Integer> processedModelMap) {
if (codegenParameter.isArray) { // array
String prefix = codegenParameter.dataType;
String dataType = StringUtils.removeStart(codegenParameter.dataType, "[]");
if (modelMaps.containsKey(dataType)) {
prefix = "[]" + goImportAlias + "." + dataType;
}
return prefix + "{" + constructExampleCode(codegenParameter.items, modelMaps, processedModelMap) + "}";
return codegenParameter.dataType + "{" + constructExampleCode(codegenParameter.items, modelMaps, processedModelMap) + "}";
} else if (codegenParameter.isMap) {
String prefix = codegenParameter.dataType;
String dataType = StringUtils.removeStart(codegenParameter.dataType, "map[string][]");
if (modelMaps.containsKey(dataType)) {
prefix = "map[string][]" + goImportAlias + "." + dataType;
}
return prefix + "{\"key\": " + constructExampleCode(codegenParameter.items, modelMaps, processedModelMap) + "}";
return codegenParameter.dataType + "{ \"key\": " + constructExampleCode(codegenParameter.items, modelMaps, processedModelMap) + "}";
} else if (codegenParameter.isPrimitiveType) { // primitive type
if (codegenParameter.isString) {
if (!StringUtils.isEmpty(codegenParameter.example) && !"null".equals(codegenParameter.example)) {
if (StringUtils.isEmpty(codegenParameter.example)) {
return "\"" + codegenParameter.example + "\"";
} else {
return "\"" + codegenParameter.paramName + "_example\"";
@@ -495,30 +481,18 @@ public class GoClientCodegen extends AbstractGoCodegen {
} else if (codegenParameter.isUri) { // URL
return "\"https://example.com\"";
} else if (codegenParameter.isDateTime || codegenParameter.isDate) { // datetime or date
processedModelMap.put("time.Time", 1);
return "time.Now()";
} else if (codegenParameter.isFile) {
return "os.NewFile(1234, \"some_file\")";
} else { // numeric
if (!StringUtils.isEmpty(codegenParameter.example) && !"null".equals(codegenParameter.example)) {
return codegenParameter.dataType + "(" + codegenParameter.example + ")";
if (StringUtils.isEmpty(codegenParameter.example)) {
return codegenParameter.example;
} else {
return codegenParameter.dataType + "(987)";
return "987";
}
}
} else { // model
// look up the model
if (modelMaps.containsKey(codegenParameter.dataType)) {
return constructExampleCode(modelMaps.get(codegenParameter.dataType), modelMaps, processedModelMap);
} else if (codegenParameter.isEmail) { // email
if (!StringUtils.isEmpty(codegenParameter.example) && !"null".equals(codegenParameter.example)) {
return "\"" + codegenParameter.example + "\"";
} else {
return "\"" + codegenParameter.paramName + "@example.com\"";
}
} else if (codegenParameter.isDateTime || codegenParameter.isDate) { // datetime or date
processedModelMap.put("time.Time", 1);
return "time.Now()";
} else {
//LOGGER.error("Error in constructing examples. Failed to look up the model " + codegenParameter.dataType);
return "TODO";
@@ -528,22 +502,12 @@ public class GoClientCodegen extends AbstractGoCodegen {
private String constructExampleCode(CodegenProperty codegenProperty, HashMap<String, CodegenModel> modelMaps, HashMap<String, Integer> processedModelMap) {
if (codegenProperty.isArray) { // array
String prefix = codegenProperty.dataType;
String dataType = StringUtils.removeStart(codegenProperty.dataType, "[]");
if (modelMaps.containsKey(dataType)) {
prefix = "[]" + goImportAlias + "." + dataType;
}
return prefix + "{" + constructExampleCode(codegenProperty.items, modelMaps, processedModelMap) + "}";
return codegenProperty.dataType + "{" + constructExampleCode(codegenProperty.items, modelMaps, processedModelMap) + ")";
} else if (codegenProperty.isMap) { // map
String prefix = codegenProperty.dataType;
String dataType = StringUtils.removeStart(codegenProperty.dataType, "map[string][]");
if (modelMaps.containsKey(dataType)) {
prefix = "map[string][]" + goImportAlias + "." + dataType;
}
return prefix + "{\"key\": " + constructExampleCode(codegenProperty.items, modelMaps, processedModelMap) + "}";
return codegenProperty.dataType + "{ \"key\": " + constructExampleCode(codegenProperty.items, modelMaps, processedModelMap) + "}";
} else if (codegenProperty.isPrimitiveType) { // primitive type
if (codegenProperty.isString) {
if (!StringUtils.isEmpty(codegenProperty.example) && !"null".equals(codegenProperty.example)) {
if (StringUtils.isEmpty(codegenProperty.example)) {
return "\"" + codegenProperty.example + "\"";
} else {
return "\"" + codegenProperty.name + "_example\"";
@@ -557,31 +521,25 @@ public class GoClientCodegen extends AbstractGoCodegen {
} else if (codegenProperty.isUri) { // URL
return "\"https://example.com\"";
} else if (codegenProperty.isDateTime || codegenProperty.isDate) { // datetime or date
processedModelMap.put("time.Time", 1);
return "time.Now()";
} else { // numeric
String example;
if (!StringUtils.isEmpty(codegenProperty.example) && !"null".equals(codegenProperty.example)) {
if (StringUtils.isEmpty(codegenProperty.example)) {
example = codegenProperty.example;
} else {
example = "123";
}
return codegenProperty.dataType + "(" + example + ")";
if (codegenProperty.isLong) {
return "int64(" + example + ")";
} else {
return example;
}
}
} else {
// look up the model
if (modelMaps.containsKey(codegenProperty.dataType)) {
return constructExampleCode(modelMaps.get(codegenProperty.dataType), modelMaps, processedModelMap);
} else if (codegenProperty.isEmail) { // email
if (!StringUtils.isEmpty(codegenProperty.example) && !"null".equals(codegenProperty.example)) {
return "\"" + codegenProperty.example + "\"";
} else {
return "\"" + codegenProperty.name + "@example.com\"";
}
} else if (codegenProperty.isDateTime || codegenProperty.isDate) { // datetime or date
processedModelMap.put("time.Time", 1);
return "time.Now()";
} else {
//LOGGER.error("Error in constructing examples. Failed to look up the model " + codegenProperty.dataType);
return "\"TODO\"";
@@ -590,6 +548,8 @@ public class GoClientCodegen extends AbstractGoCodegen {
}
private String constructExampleCode(CodegenModel codegenModel, HashMap<String, CodegenModel> modelMaps, HashMap<String, Integer> processedModelMap) {
String example;
// break infinite recursion. Return, in case a model is already processed in the current context.
String model = codegenModel.name;
if (processedModelMap.containsKey(model)) {
@@ -601,14 +561,6 @@ public class GoClientCodegen extends AbstractGoCodegen {
} else {
throw new RuntimeException("Invalid count when constructing example: " + count);
}
} else if (codegenModel.isEnum) {
Map<String, Object> allowableValues = codegenModel.allowableValues;
List<Object> values = (List<Object>) allowableValues.get("values");
return goImportAlias + "." + model + "(\"" + String.valueOf(values.get(0)) + "\")";
} else if (codegenModel.oneOf != null && !codegenModel.oneOf.isEmpty()) {
String subModel = (String) codegenModel.oneOf.toArray()[0];
String oneOf = constructExampleCode(modelMaps.get(subModel), modelMaps, processedModelMap).substring(1);
return goImportAlias + "." + model + "{" + subModel + ": " + oneOf + "}";
} else {
processedModelMap.put(model, 1);
}
@@ -617,6 +569,6 @@ public class GoClientCodegen extends AbstractGoCodegen {
for (CodegenProperty codegenProperty : codegenModel.requiredVars) {
propertyExamples.add(constructExampleCode(codegenProperty, modelMaps, processedModelMap));
}
return "*" + goImportAlias + ".New" + toModelName(model) + "(" + StringUtils.join(propertyExamples, ", ") + ")";
return "*" + goImportAlias + ".New" + codegenModel.name + "(" + StringUtils.join(propertyExamples, ", ") + ")";
}
}

View File

@@ -123,7 +123,7 @@ public class GraphQLNodeJSExpressServerCodegen extends AbstractGraphQLCodegen im
@Override
public String getTypeDeclaration(Schema p) {
if (modelUtils.isArraySchema(p)) {
if (ModelUtils.isArraySchema(p)) {
ArraySchema ap = (ArraySchema) p;
Schema inner = ap.getItems();
@@ -131,7 +131,7 @@ public class GraphQLNodeJSExpressServerCodegen extends AbstractGraphQLCodegen im
// between some specific types for GraphQL:
// return "[" + getTypeDeclaration(inner) + "]";
return getTypeDeclaration(inner);
} else if (modelUtils.isMapSchema(p)) {
} else if (ModelUtils.isMapSchema(p)) {
Schema inner = (Schema) p.getAdditionalProperties();
return getTypeDeclaration(inner);
@@ -139,7 +139,7 @@ public class GraphQLNodeJSExpressServerCodegen extends AbstractGraphQLCodegen im
// IMPORANT NOTE Not using the supertype invocation, because we want to UpperCamelize the type:
String schemaType = getSchemaType(p);
String nullable = modelUtils.isNullable(p) ? "" : "!";
String nullable = ModelUtils.isNullable(p) ? "" : "!";
if (typeMapping.containsKey(schemaType)) {
return typeMapping.get(schemaType) + nullable;

View File

@@ -519,7 +519,7 @@ public class HaskellHttpClientCodegen extends DefaultCodegen implements CodegenC
}
@Override
public void preprocessOpenAPI() {
public void preprocessOpenAPI(OpenAPI openAPI) {
String baseTitle = openAPI.getInfo().getTitle();
if (baseTitle == null) {
@@ -612,7 +612,7 @@ public class HaskellHttpClientCodegen extends DefaultCodegen implements CodegenC
additionalProperties.put(X_HAS_IMPORT_MAPPINGS, true);
}
super.preprocessOpenAPI();
super.preprocessOpenAPI(openAPI);
}
@Override
@@ -624,11 +624,11 @@ public class HaskellHttpClientCodegen extends DefaultCodegen implements CodegenC
@Override
public String getTypeDeclaration(Schema p) {
if (modelUtils.isArraySchema(p)) {
if (ModelUtils.isArraySchema(p)) {
ArraySchema ap = (ArraySchema) p;
Schema inner = ap.getItems();
return "[" + getTypeDeclaration(inner) + "]";
} else if (modelUtils.isMapSchema(p)) {
} else if (ModelUtils.isMapSchema(p)) {
Schema inner = getAdditionalProperties(p);
return "(Map.Map String " + getTypeDeclaration(inner) + ")";
}
@@ -650,7 +650,7 @@ public class HaskellHttpClientCodegen extends DefaultCodegen implements CodegenC
@Override
public String toInstantiationType(Schema p) {
if (modelUtils.isMapSchema(p)) {
if (ModelUtils.isMapSchema(p)) {
Schema additionalProperties2 = getAdditionalProperties(p);
String type = additionalProperties2.getType();
if (null == type) {
@@ -659,7 +659,7 @@ public class HaskellHttpClientCodegen extends DefaultCodegen implements CodegenC
}
String inner = getSchemaType(additionalProperties2);
return "(Map.Map Text " + inner + ")";
} else if (modelUtils.isArraySchema(p)) {
} else if (ModelUtils.isArraySchema(p)) {
ArraySchema ap = (ArraySchema) p;
return getSchemaType(ap.getItems());
} else {
@@ -1245,11 +1245,11 @@ public class HaskellHttpClientCodegen extends DefaultCodegen implements CodegenC
@Override
public String toDefaultValue(Schema p) {
if (modelUtils.isStringSchema(p)) {
if (ModelUtils.isStringSchema(p)) {
if (p.getDefault() != null) {
return "\"" + escapeText((String) p.getDefault()) + "\"";
}
} else if (modelUtils.isBooleanSchema(p)) {
} else if (ModelUtils.isBooleanSchema(p)) {
if (p.getDefault() != null) {
if (p.getDefault().toString().equalsIgnoreCase("false"))
return "False";

View File

@@ -268,7 +268,7 @@ public class HaskellServantCodegen extends DefaultCodegen implements CodegenConf
}
@Override
public void preprocessOpenAPI() {
public void preprocessOpenAPI(OpenAPI openAPI) {
// From the title, compute a reasonable name for the package and the API
String title = openAPI.getInfo().getTitle();
@@ -325,7 +325,7 @@ public class HaskellServantCodegen extends DefaultCodegen implements CodegenConf
// See docstring for setGenerateToSchema for why we do this
additionalProperties.put("generateToSchema", true);
super.preprocessOpenAPI();
super.preprocessOpenAPI(openAPI);
}
/**
@@ -368,11 +368,11 @@ public class HaskellServantCodegen extends DefaultCodegen implements CodegenConf
*/
@Override
public String getTypeDeclaration(Schema p) {
if (modelUtils.isArraySchema(p)) {
if (ModelUtils.isArraySchema(p)) {
ArraySchema ap = (ArraySchema) p;
Schema inner = ap.getItems();
return "[" + getTypeDeclaration(inner) + "]";
} else if (modelUtils.isMapSchema(p)) {
} else if (ModelUtils.isMapSchema(p)) {
Schema inner = getAdditionalProperties(p);
return "(Map.Map String " + getTypeDeclaration(inner) + ")";
}
@@ -407,7 +407,7 @@ public class HaskellServantCodegen extends DefaultCodegen implements CodegenConf
@Override
public String toInstantiationType(Schema p) {
if (modelUtils.isMapSchema(p)) {
if (ModelUtils.isMapSchema(p)) {
Schema additionalProperties2 = getAdditionalProperties(p);
String type = additionalProperties2.getType();
if (null == type) {
@@ -416,7 +416,7 @@ public class HaskellServantCodegen extends DefaultCodegen implements CodegenConf
}
String inner = getSchemaType(additionalProperties2);
return "(Map.Map Text " + inner + ")";
} else if (modelUtils.isArraySchema(p)) {
} else if (ModelUtils.isArraySchema(p)) {
ArraySchema ap = (ArraySchema) p;
String inner = getSchemaType(ap.getItems());
// Return only the inner type; the wrapping with QueryList is done

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