Compare commits

..

1 Commits

Author SHA1 Message Date
William Cheng
1ba38d6a5c add TS server 2020-07-14 22:44:25 +08:00
2589 changed files with 13146 additions and 39902 deletions

View File

@@ -45,13 +45,9 @@ please create a Gist (https://gist.github.com) or upload it somewhere else and
link it here.
-->
##### Generation Details
##### Command line used for generation
<!--
Prefer CLI steps, including the language, libraries and various options.
Providing config-based settings allows for simpler testing across CLI and plugins.
For examples, see https://github.com/OpenAPITools/openapi-generator/tree/master/bin/configs
-->
<!-- including the language, libraries and various options -->
##### Steps to reproduce

View File

@@ -4,8 +4,7 @@
### PR checklist
- [ ] Read the [contribution guidelines](https://github.com/openapitools/openapi-generator/blob/master/CONTRIBUTING.md).
- [ ] Pull Request title clearly describes the work in the pull request and Pull Request description provides details about how to validate the work. Missing information here may result in delayed response from the community.
- [ ] If contributing template-only or documentation-only changes which will change sample output, [build the project](https://github.com/OpenAPITools/openapi-generator#14---build-projects) beforehand.
- [ ] Run the shell script `./bin/generate-samples.sh`to update all Petstore samples related to your fix. This is important, as CI jobs will verify _all_ generator outputs of your HEAD commit as it would merge with master. These must match the expectations made by your contribution. You may regenerate an individual generator by passing the relevant config(s) as an argument to the script, for example `./bin/generate-samples.sh bin/configs/java*`. For Windows users, please run the script in [Git BASH](https://gitforwindows.org/).
- [ ] Run the shell script `./bin/generate-samples.sh`to update all Petstore samples related to your fix. This is important, as CI jobs will verify _all_ generator outputs of your HEAD commit as it would merge with master. These must match the expectations made by your contribution. You may regenerate an individual generator by passing the relevant config(s) as an argument to the script, for example `./bin/generate-samples.sh bin/config/java*`. For Windows users, please run the script in [Git BASH](https://gitforwindows.org/).
- [ ] File the PR against the [correct branch](https://github.com/OpenAPITools/openapi-generator/wiki/Git-Branches): `master`
- [ ] Copy the [technical committee](https://github.com/openapitools/openapi-generator/#62---openapi-generator-technical-committee) to review the pull request if your PR is targeting a particular programming language.

View File

@@ -1,80 +0,0 @@
name: Check Supported Java Versions
on:
push:
branches:
- master
jobs:
build:
name: Build on JDK ${{ matrix.java }} and ${{ matrix.os }}
runs-on: ${{ matrix.os }}
strategy:
matrix:
java: [8, 11]
os: [ubuntu-latest]
include:
- java: 8
os: windows-latest
- java: 13
os: ubuntu-latest
# Need to update to Gradle version with v13 support in modules/openapi-generator-gradle-plugin/pom.xml
flags: -am -pl modules/openapi-generator-cli
steps:
- name: Check out code
uses: actions/checkout@v2
- name: Set up JDK ${{ matrix.java }}
uses: actions/setup-java@v1
with:
java-version: ${{ matrix.java }}
- uses: actions/cache@v1
with:
path: ~/.m2/repository
key: ${{ runner.os }}-maven-${{ hashFiles('pom.xml', 'modules/**/pom.xml') }}
restore-keys: |
${{ runner.os }}-maven-
- uses: actions/cache@v2
with:
path: |
~/.gradle/caches
~/.gradle/wrapper
key: ${{ runner.os }}-gradle-${{ hashFiles('modules/openapi-generator-gradle-plugin/pom.xml') }}
restore-keys: |
${{ runner.os }}-gradle-
- name: Build with Maven
shell: bash
run: mvn -nsu -B --quiet -Djacoco.skip=true -Dorg.slf4j.simpleLogger.defaultLogLevel=error --no-transfer-progress clean install --file pom.xml ${{ matrix.flags }}
- name: Test gradle
shell: bash
run: gradle -b modules/openapi-generator-gradle-plugin/samples/local-spec/build.gradle buildGoSdk --stacktrace
- name: Upload Maven build artifact
uses: actions/upload-artifact@v1
if: matrix.java == '8'
with:
name: artifact
path: modules/openapi-generator-cli/target/openapi-generator-cli.jar
verify:
name: Verifies integrity of the commit on ${{ matrix.os }}
needs: build
runs-on: ${{ matrix.os }}
strategy:
matrix:
os: [ubuntu-latest, windows-latest]
steps:
- name: Check out code
uses: actions/checkout@v2
- name: Download build artifact
uses: actions/download-artifact@v1
with:
name: artifact
- name: Run Ensures Script
run: |
mkdir -p modules/openapi-generator-cli/target/
mv artifact/openapi-generator-cli.jar modules/openapi-generator-cli/target/
./bin/utils/ensure-up-to-date

4
.gitignore vendored
View File

@@ -173,14 +173,10 @@ samples/client/petstore/python-asyncio/.venv/
samples/client/petstore/python-asyncio/.pytest_cache/
samples/client/petstore/python-tornado/.venv/
# PHP
samples/server/petstore/php-lumen/lib/composer.lock
# ts
samples/client/petstore/typescript-angular2/npm/npm-debug.log
samples/client/petstore/typescript-node/npm/npm-debug.log
samples/client/petstore/typescript-angular/tsd-debug.log
samples/client/petstore/typescript-axios/tests/**/dist/
samples/client/petstore/typescript-fetch/tests/**/dist/
# aspnetcore

View File

@@ -77,13 +77,11 @@ before_install:
- docker pull swaggerapi/petstore
- docker run -d -e SWAGGER_HOST=http://petstore.swagger.io -e SWAGGER_BASE_PATH=/v2 -p 80:8080 swaggerapi/petstore
- docker ps -a
# -- skip bash test to shorten build time
# Add bats test framework and cURL for Bash script integration tests
#- sudo add-apt-repository ppa:duggan/bats --yes
#- sudo apt-get update -qq
#- sudo apt-get install -qq bats
#- sudo apt-get install -qq curl
# -- skip bash test end
- sudo add-apt-repository ppa:duggan/bats --yes
- sudo apt-get update -qq
- sudo apt-get install -qq bats
- sudo apt-get install -qq curl
# install dart
#- sudo apt-get update
#- sudo apt-get install apt-transport-https
@@ -95,6 +93,9 @@ before_install:
- phpenv versions
- phpenv global 7.2.15
- php -v
# install perl module
#- cpanm --local-lib=~/perl5 local::lib && eval $(perl -I ~/perl5/lib/perl5/ -Mlocal::lib)
#- cpanm Test::Exception Test::More Log::Any LWP::UserAgent JSON URI:Query Module::Runtime DateTime Module::Find Moose::Role
# comment out below as installation failed in travis
# Add rebar3 build tool and recent Erlang/OTP for Erlang petstore server tests.
# - Travis CI does not support rebar3 [yet](https://github.com/travis-ci/travis-ci/issues/6506#issuecomment-275189490).
@@ -106,11 +107,9 @@ before_install:
# install Qt5
- sudo apt install -y --no-install-recommends qt5-default
- cmake --version
# -- skip perl test to shorten build time
# perl dep
#- cpanm --local-lib=~/perl5 local::lib && eval $(perl -I ~/perl5/lib/perl5/ -Mlocal::lib)
#- cpanm --quiet --no-interactive Test::Exception Test::More Log::Any LWP::UserAgent URI::Query Module::Runtime DateTime Module::Find Moose::Role JSON || echo "Igorned failure from cpanm"
# -- skip perl test end
- cpanm --local-lib=~/perl5 local::lib && eval $(perl -I ~/perl5/lib/perl5/ -Mlocal::lib)
- cpanm --quiet --no-interactive Test::Exception Test::More Log::Any LWP::UserAgent URI::Query Module::Runtime DateTime Module::Find Moose::Role JSON || echo "Igorned failure from cpanm"
# show host table to confirm petstore.swagger.io is mapped to localhost
- cat /etc/hosts
# show java version
@@ -150,6 +149,14 @@ script:
# WARN: Travis will timeout after 10 minutes of no stdout/stderr activity, which is problematic with mvn --quiet.
- mvn --no-snapshot-updates --quiet --batch-mode --show-version clean install -Dorg.slf4j.simpleLogger.defaultLogLevel=error
- mvn --no-snapshot-updates --quiet --batch-mode --show-version verify -Psamples -Dorg.slf4j.simpleLogger.defaultLogLevel=error
# test maven plugin
- mvn --no-snapshot-updates --quiet clean compile -f modules/openapi-generator-maven-plugin/examples/java-client.xml -Dorg.slf4j.simpleLogger.defaultLogLevel=error
- mvn --no-snapshot-updates --quiet clean compile -f modules/openapi-generator-maven-plugin/examples/multi-module/pom.xml -Dorg.slf4j.simpleLogger.defaultLogLevel=error
- mvn --no-snapshot-updates --quiet clean compile -f modules/openapi-generator-maven-plugin/examples/kotlin.xml -Dorg.slf4j.simpleLogger.defaultLogLevel=error
- mvn --no-snapshot-updates --quiet clean compile -f modules/openapi-generator-maven-plugin/examples/spring.xml -Dorg.slf4j.simpleLogger.defaultLogLevel=error
# test gradle plugin
- (cd modules/openapi-generator-gradle-plugin/samples/local-spec && ./gradlew buildGoSdk)
- (cd modules/openapi-generator-gradle-plugin/samples/local-spec && ./gradlew openApiGenerate)
after_success:
# push to maven repo
- if [ $SONATYPE_USERNAME ] && [ "$TRAVIS_PULL_REQUEST" == "false" ]; then

View File

@@ -17,11 +17,15 @@ trap cleanup EXIT
if [ "$NODE_INDEX" = "1" ]; then
echo "Running node $NODE_INDEX to test 'samples.circleci' defined in pom.xml ..."
java -version
# Install golang version 1.14
go version
sudo mkdir /usr/local/go1.14
wget -c https://dl.google.com/go/go1.14.linux-amd64.tar.gz -O - | sudo tar -xz -C /usr/local/go1.14
export PATH="/usr/local/go1.14/go/bin:$PATH"
go version
mvn --no-snapshot-updates --quiet verify -Psamples.circleci -Dorg.slf4j.simpleLogger.defaultLogLevel=error
echo "show ivy2 cache"
ls -l /home/circleci/.ivy2/cache
mvn --no-snapshot-updates --quiet javadoc:javadoc -Psamples.circleci -Dorg.slf4j.simpleLogger.defaultLogLevel=error
elif [ "$NODE_INDEX" = "2" ]; then
# run ensure-up-to-date sample script on SNAPSHOT version only
@@ -36,6 +40,7 @@ elif [ "$NODE_INDEX" = "2" ]; then
# look for outdated samples
./bin/utils/ensure-up-to-date
fi
#elif [ "$NODE_INDEX" = "3" ]; then
echo "Running node $NODE_INDEX to test haskell"
# install haskell
curl -sSL https://get.haskellstack.org/ | sh
@@ -59,13 +64,6 @@ else
#sudo update-java-alternatives -s java-1.7.0-openjdk-amd64
java -version
# Install golang version 1.14
go version
sudo mkdir /usr/local/go1.14
wget -c https://dl.google.com/go/go1.14.linux-amd64.tar.gz -O - | sudo tar -xz -C /usr/local/go1.14
export PATH="/usr/local/go1.14/go/bin:$PATH"
go version
# install dart2
sudo apt-get update
sudo apt-get install apt-transport-https
@@ -76,7 +74,6 @@ else
export PATH="$PATH:/usr/lib/dart/bin"
mvn --no-snapshot-updates --quiet verify -Psamples.circleci.others -Dorg.slf4j.simpleLogger.defaultLogLevel=error
mvn --no-snapshot-updates --quiet javadoc:javadoc -Psamples.circleci -Dorg.slf4j.simpleLogger.defaultLogLevel=error
fi

View File

@@ -4,7 +4,7 @@
- If you're not using the latest master to generate API clients or server stubs, please give it another try by pulling the latest master as the issue may have already been addressed. Ref: [Getting Started](https://github.com/openapitools/openapi-generator#getting-started)
- Search the [open issue](https://github.com/openapitools/openapi-generator/issues) and [closed issue](https://github.com/openapitools/openapi-generator/issues?q=is%3Aissue+is%3Aclosed) to ensure no one else has reported something similar before.
- File an [issue ticket](https://github.com/openapitools/openapi-generator/issues/new) by providing all the required information. Failure to provide enough detail may result in slow response from the community.
- File an [issue ticket](https://github.com/openapitools/openapi-generator/issues/new) by providing all the required information.
- Test with the latest master by building the JAR locally to see if the issue has already been addressed.
- You can also make a suggestion or ask a question by opening an "issue".
@@ -87,7 +87,8 @@ To add test cases (optional) covering the change in the code generator, please r
To test the templates, please perform the following:
- Update the Petstore sample by running the shell scripts under the `bin` folder. For example, run `./bin/generate-samples.sh .
/bin/configs/python*` to update the Python-related samples under [`samples`](https://github.com/openapitools/openapi-generator/tree/master/samples). For Windows, please install [GIT bash](https://gitforwindows.org/). (If you find that there are new files g
/bin/configs/python*` to update the Python-related samples under [`samples`](https://github.com/openapitools/openapi-generator/t
ree/master/samples). For Windows, please install [GIT bash](https://gitforwindows.org/). (If you find that there are new files g
enerated or unexpected changes as a result of the update, that's not unusual as the test cases are added to the OpenAPI spec fro
m time to time. If you've questions or concerns, please open a ticket to start a discussion)
- During development it can be helpful to quickly regenerate the samples without recompiling all of openapi-generator, e.g. when you have only updated the mustache templates. This can be done by passing the `-t` parameter: `-t modules/openapi-generator/src/main/resources/python`.
@@ -109,8 +110,7 @@ See [OpenAPI Tools wiki](https://github.com/OpenAPITools/openapi-generator/wiki/
- Add test case(s) to cover the change
- Document the fix in the code to make the code more readable
- Make sure test cases passed after the change (one way is to leverage https://travis-ci.org/ to run the CI tests)
- File a PR with meaningful title, description and commit messages
- Make sure the option "Allow edits from maintainers" in the PR is selected so that the maintainers can update your PRs with minor fixes, if needed.
- File a PR with meaningful title, description and commit messages.
- Recommended git settings
- `git config core.autocrlf input` to tell Git convert CRLF to LF on commit but not the other way around
- To close an issue (e.g. issue 1542) automatically after a PR is merged, use keywords "fix", "close", "resolve" in the PR description, e.g. `fix #1542`. (Ref: [closing issues using keywords](https://help.github.com/articles/closing-issues-using-keywords/))

View File

@@ -8,7 +8,6 @@
[![Windows Test](https://ci.appveyor.com/api/projects/status/github/openapitools/openapi-generator?branch=master&svg=true&passingText=Windows%20Test%20-%20OK&failingText=Windows%20Test%20-%20Fails)](https://ci.appveyor.com/project/WilliamCheng/openapi-generator-wh2wu)
[![JDK11 Build](https://cloud.drone.io/api/badges/OpenAPITools/openapi-generator/status.svg?ref=refs/heads/master)](https://cloud.drone.io/OpenAPITools/openapi-generator)
[![iOS Build Status](https://app.bitrise.io/app/4a2b10a819d12b67/status.svg?token=859FMDR8QHwabCzwvZK6vQ&branch=master)](https://app.bitrise.io/app/4a2b10a819d12b67)
![Check Supported Java Versions](https://github.com/openapi-generator/openapi-generator/workflows/Check%20Supported%20Java%20Versions/badge.svg)
</div>
@@ -579,7 +578,6 @@ Here are some companies/projects (alphabetical order) using OpenAPI Generator in
- [Camptocamp](https://www.camptocamp.com/en)
- [Cisco](https://www.cisco.com/)
- [codecentric AG](https://www.codecentric.de/)
- [CoinAPI](https://www.coinapi.io/)
- [Commencis](https://www.commencis.com/)
- [Crossover Health](https://crossoverhealth.com/)
- [Cupix](https://www.cupix.com/)
@@ -616,8 +614,6 @@ Here are some companies/projects (alphabetical order) using OpenAPI Generator in
- [MoonVision](https://www.moonvision.io/)
- [Myworkout](https://myworkout.com)
- [NamSor](https://www.namsor.com/)
- [Nokia](https://www.nokia.com/)
- [Options Clearing Corporation (OCC)](https://www.theocc.com/)
- [Openet](https://www.openet.com/)
- [openVALIDATION](https://openvalidation.io/)
- [Oracle](https://www.oracle.com/)
@@ -760,15 +756,10 @@ Here are some companies/projects (alphabetical order) using OpenAPI Generator in
- 2020-05-19 - [Dead Simple APIs with Open API](https://www.youtube.com/watch?v=sIaXmR6xRAw) by [Chris Tankersley](https://github.com/dragonmantank) at [Nexmo](https://developer.nexmo.com/)
- 2020-05-22 - [TypeScript REST API Client](https://dev.to/unhurried/typescript-rest-api-client-4in3) by ["unhurried"](https://dev.to/unhurried)
- 2020-05-28 - [【使用 lotify + Swagger 建置可共用的 LINE Notify bot】 - #NiJia @ Chatbot Developer Taiwan 第 #19 小聚](https://www.youtube.com/watch?v=agYVz6dzh1I) by [Chatbot Developer Taiwan](https://www.youtube.com/channel/UCxeYUyZNnHmpX23YNF-ewvw)
- 2020-05-28 - [Building APIs with Laravel using OpenAPI](https://www.youtube.com/watch?v=xexLvQqAhiA) by [Chris Tankersley](https://github.com/dragonmantank) at [Laracon EU](https://laracon.eu/)
- 2020-06-23 - [新規サーバーアプリケーションにTypeScriptを採用してみた](https://www.cam-inc.co.jp/news/20200623) at [CAM Tech Blog](https://www.cam-inc.co.jp/news/tech-blog/)
- 2020-06-29 - [Artifact Abstract: Deployment of APIs on Android Mobile Devices and Microcontrollers](https://ieeexplore.ieee.org/document/9127353) by [Sergio Laso ; Marino Linaje ; Jose Garcia-Alonso ; Juan M. Murillo ; Javier Berrocal](https://ieeexplore.ieee.org/document/9127353/authors#authors) at [2020 IEEE International Conference on Pervasive Computing and Communications (PerCom)](https://ieeexplore.ieee.org/xpl/conhome/9125449/proceeding)
- 2020-07-07 - [5 Best API Documentation Tools](https://blog.dreamfactory.com/5-best-api-documentation-tools/) by Susanna Bouse at [DreamFactory Blog](https://blog.dreamfactory.com/)
- 2020-07-12 - [Open API 3.0の定義からgolangのサーバコードのスケルトンを作成する](https://qiita.com/professor/items/4cbd04ec084d13057bc2) by [@professor (Qiita Blog)](https://qiita.com/professor)
- 2020-07-20 - [Datadog API client libraries now available for Java and Go](https://www.datadoghq.com/blog/java-go-libraries/) by Jordan Obey at [Datadog Blog](https://www.datadoghq.com/blog)
- 2020-07-23 - [Generate Client SDK for .NET Core using Open Api](https://dev.to/no0law1/generate-client-sdk-for-net-core-using-open-api-2dgh) by [Nuno Reis](https://dev.to/no0law1)
- 2020-07-26 - [Dartのhttp_interceptorライブラリを使うと配列のクエリパラメータが消えてしまう件の応急処置](https://qiita.com/gyamoto/items/eeeff81b6770487319ed) by [@gyamoto](https://qiita.com/gyamoto)
- 2020-08-03 - [Criando Bibliotecas para APIs RESTful com OpenAPI, Swagger Editor e OpenAPI Generator](https://medium.com/@everisBrasil/criando-bibliotecas-para-apis-restful-com-openapi-swagger-editor-e-openapi-generator-75349a6420fd) by [everis Brasil (an NTT DATA Company)](https://medium.com/@everisBrasil)
## [6 - About Us](#table-of-contents)

View File

@@ -15,14 +15,14 @@ install:
# install gradle
- ps: |
Add-Type -AssemblyName System.IO.Compression.FileSystem
if (!(Test-Path -Path "C:\gradle\gradle-5.6.4" )) {
if (!(Test-Path -Path "C:\gradle" )) {
(new-object System.Net.WebClient).DownloadFile(
'https://services.gradle.org/distributions/gradle-5.6.4-bin.zip',
'https://services.gradle.org/distributions/gradle-5.3.1-bin.zip',
'C:\gradle-bin.zip'
)
[System.IO.Compression.ZipFile]::ExtractToDirectory("C:\gradle-bin.zip", "C:\gradle")
}
- cmd: SET PATH=C:\maven\apache-maven-3.2.5\bin;C:\gradle\gradle-5.6.4\bin;%JAVA_HOME%\bin;%PATH%
- cmd: SET PATH=C:\maven\apache-maven-3.2.5\bin;C:\gradle\gradle-5.3.1\bin;%JAVA_HOME%\bin;%PATH%
- cmd: SET MAVEN_OPTS=-Xmx4g
- cmd: SET JAVA_OPTS=-Xmx4g
- cmd: SET M2_HOME=C:\maven\apache-maven-3.2.5

View File

@@ -5,5 +5,4 @@ templateDir: modules/openapi-generator/src/main/resources/csharp-netcore
additionalProperties:
packageGuid: '{321C8C3F-0156-40C1-AE42-D59761FB9B6C}'
targetFramework: netcoreapp2.0
useCompareNetObjects: true
license: BSD-2-Clause OR MIT
useCompareNetObjects: "true"

View File

@@ -5,4 +5,3 @@ templateDir: modules/openapi-generator/src/main/resources/go-experimental
additionalProperties:
enumClassPrefix: "true"
packageName: petstore
disallowAdditionalPropertiesIfNotPresent: false

View File

@@ -1,15 +0,0 @@
generatorName: java
outputDir: samples/openapi3/client/petstore/java/jersey2-java8-special-characters
library: jersey2
inputSpec: modules/openapi-generator/src/test/resources/3_0/schema-with-special-characters.yaml
templateDir: modules/openapi-generator/src/main/resources/Java
additionalProperties:
artifactId: petstore-openapi3-jersey2-java8-special-characters
hideGenerationTimestamp: true
serverPort: "8082"
dateLibrary: java8
useOneOfDiscriminatorLookup: true
disallowAdditionalPropertiesIfNotPresent: false
systemProperties:
skipValidateSpec: "false"

View File

@@ -1,8 +0,0 @@
generatorName: kotlin
outputDir: samples/client/petstore/kotlin-retrofit2-rx3
library: jvm-retrofit2
inputSpec: modules/openapi-generator/src/test/resources/2_0/petstore.yaml
templateDir: modules/openapi-generator/src/main/resources/kotlin-client
additionalProperties:
artifactId: kotlin-petstore-retrofit2-rx3
useRxJava3: "true"

View File

@@ -1,4 +1,4 @@
generatorName: php-lumen
outputDir: samples/server/petstore/php-lumen
inputSpec: modules/openapi-generator/src/test/resources/3_0/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/php-lumen

View File

@@ -1,9 +0,0 @@
generatorName: typescript-angular
outputDir: samples/client/petstore/typescript-angular-v10-provided-in-root/builds/with-npm
inputSpec: modules/openapi-generator/src/test/resources/2_0/petstore.yaml
additionalProperties:
ngVersion: 10.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-v10-provided-in-root/builds/default
inputSpec: modules/openapi-generator/src/test/resources/2_0/petstore.yaml
additionalProperties:
ngVersion: 10.0.0

View File

@@ -1,9 +0,0 @@
generatorName: typescript-angular
outputDir: samples/client/petstore/typescript-angular-v9-provided-in-root/builds/with-npm
inputSpec: modules/openapi-generator/src/test/resources/2_0/petstore.yaml
additionalProperties:
ngVersion: 9.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-v9-provided-in-root/builds/default
inputSpec: modules/openapi-generator/src/test/resources/2_0/petstore.yaml
additionalProperties:
ngVersion: 9.0.0

View File

@@ -1,6 +0,0 @@
generatorName: typescript
outputDir: samples/openapi3/client/petstore/typescript/builds/deno
inputSpec: modules/openapi-generator/src/test/resources/3_0/petstore.yaml
additionalProperties:
platform: deno
npmName: ts-petstore-client

View File

@@ -1,7 +0,0 @@
generatorName: typescript
outputDir: samples/openapi3/client/petstore/typescript/builds/inversify
inputSpec: modules/openapi-generator/src/test/resources/3_0/petstore.yaml
additionalProperties:
platform: node
npmName: ts-petstore-client
useInversify: true

View File

@@ -1,6 +0,0 @@
generatorName: typescript
outputDir: samples/openapi3/client/petstore/typescript/builds/jquery
inputSpec: modules/openapi-generator/src/test/resources/3_0/petstore.yaml
additionalProperties:
framework: jquery
npmName: ts-petstore-client

View File

@@ -1,7 +0,0 @@
generatorName: typescript
outputDir: samples/openapi3/client/petstore/typescript/builds/object_params
inputSpec: modules/openapi-generator/src/test/resources/3_0/petstore.yaml
additionalProperties:
platform: node
npmName: ts-petstore-client
useObjectParameters: true

View File

@@ -1,6 +0,0 @@
generatorName: typescript
outputDir: samples/openapi3/client/petstore/typescript/builds/default
inputSpec: modules/openapi-generator/src/test/resources/3_0/petstore.yaml
additionalProperties:
platform: node
npmName: ts-petstore-client

View File

@@ -0,0 +1,32 @@
#!/bin/sh
SCRIPT="$0"
echo "# START SCRIPT: $SCRIPT"
while [ -h "$SCRIPT" ] ; do
ls=`ls -ld "$SCRIPT"`
link=`expr "$ls" : '.*-> \(.*\)$'`
if expr "$link" : '/.*' > /dev/null; then
SCRIPT="$link"
else
SCRIPT=`dirname "$SCRIPT"`/"$link"
fi
done
if [ ! -d "${APP_DIR}" ]; then
APP_DIR=`dirname "$SCRIPT"`/..
APP_DIR=`cd "${APP_DIR}"; pwd`
fi
executable="./modules/openapi-generator-cli/target/openapi-generator-cli.jar"
if [ ! -f "$executable" ]
then
mvn -B clean package
fi
# if you've executed sbt assembly previously it will use that instead.
export JAVA_OPTS="${JAVA_OPTS} -Xmx1024M -DloggerPath=conf/log4j.properties"
ags="generate -i modules/openapi-generator/src/test/resources/2_0/petstore.yaml -g typescript-server -o samples/server/petstore/typescript-server/ $@"
java $JAVA_OPTS -jar $executable $ags

51
bin/typescript.sh Executable file
View File

@@ -0,0 +1,51 @@
#!/bin/sh
SCRIPT="$0"
echo "# START SCRIPT: $SCRIPT"
while [ -h "$SCRIPT" ] ; do
ls=`ls -ld "$SCRIPT"`
link=`expr "$ls" : '.*-> \(.*\)$'`
if expr "$link" : '/.*' > /dev/null; then
SCRIPT="$link"
else
SCRIPT=`dirname "$SCRIPT"`/"$link"
fi
done
if [ ! -d "${APP_DIR}" ]; then
APP_DIR=`dirname "$SCRIPT"`/..
APP_DIR=`cd "${APP_DIR}"; pwd`
fi
executable="./modules/openapi-generator-cli/target/openapi-generator-cli.jar"
common_args="generate -i modules/openapi-generator/src/test/resources/3_0/petstore.yaml -g typescript"
samples="samples/openapi3/client/petstore/typescript/builds"
if [ ! -f "$executable" ]
then
mvn -B clean package
fi
# if you've executed sbt assembly previously it will use that instead.
export JAVA_OPTS="${JAVA_OPTS} -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties"
printf "\033[32m## Creating default (fetch) client!\033[0m\n"
args="-o $samples/default --additional-properties=platform=node,npmName=ts-petstore-client $@"
java $JAVA_OPTS -jar $executable $common_args $args
printf "\033[32m## Creating jquery client!\033[0m\n"
args="-o $samples/jquery --additional-properties=framework=jquery,npmName=ts-petstore-client $@"
java $JAVA_OPTS -jar $executable $common_args $args
printf "\033[32m## Creating fetch object client!\033[0m\n"
args="-o $samples/object_params --additional-properties=platform=node,npmName=ts-petstore-client,useObjectParameters=true $@"
java $JAVA_OPTS -jar $executable $common_args $args
printf "\033[32m## Creating fetch client with InversifyJS support!\033[0m\n"
args="-o $samples/inversify --additional-properties=platform=node,npmName=ts-petstore-client,useInversify=true $@"
java $JAVA_OPTS -jar $executable $common_args $args
printf "\033[32m## Creating Deno (fetch) client!\033[0m\n"
args="-o $samples/deno --additional-properties=platform=deno $@"
java $JAVA_OPTS -jar $executable $common_args $args

View File

@@ -0,0 +1,14 @@
@ECHO OFF
set executable=.\modules\openapi-generator-cli\target\openapi-generator-cli.jar
If Not Exist %executable% (
mvn clean package
)
REM set JAVA_OPTS=%JAVA_OPTS% -Xmx1024M
echo
set ags=generate -i modules\openapi-generator\src\test\resources\2_0\petstore.yaml -g typescript-server -o samples\server\petstore\typescript-server
java %JAVA_OPTS% -jar %executable% %ags%

View File

@@ -78,7 +78,6 @@ jobs:
- ~/virtualenvs
- ~/.m2
- ~/.ivy2
- ~/.sbt
- ~/.bundle
- ~/.go_workspace
- ~/.gradle

View File

@@ -8,7 +8,7 @@ sidebar_label: Guidelines
- If you're not using the latest master to generate API clients or server stubs, please give it another try by pulling the latest master as the issue may have already been addressed. Ref: [Getting Started](https://github.com/openapitools/openapi-generator#getting-started)
- Search the [open issue](https://github.com/openapitools/openapi-generator/issues) and [closed issue](https://github.com/openapitools/openapi-generator/issues?q=is%3Aissue+is%3Aclosed) to ensure no one else has reported something similar before.
- File an [issue ticket](https://github.com/openapitools/openapi-generator/issues/new) by providing all the required information. Failure to provide enough detail may result in slow response from the community.
- File an [issue ticket](https://github.com/openapitools/openapi-generator/issues/new) by providing all the required information.
- Test with the latest master by building the JAR locally to see if the issue has already been addressed.
- You can also make a suggestion or ask a question by opening an "issue".
@@ -91,7 +91,8 @@ To add test cases (optional) covering the change in the code generator, please r
To test the templates, please perform the following:
- Update the Petstore sample by running the shell scripts under the `bin` folder. For example, run `./bin/generate-samples.sh .
/bin/configs/python*` to update the Python-related samples under [`samples`](https://github.com/openapitools/openapi-generator/tree/master/samples). For Windows, please install [GIT bash](https://gitforwindows.org/). (If you find that there are new files g
/bin/configs/python*` to update the Python-related samples under [`samples`](https://github.com/openapitools/openapi-generator/t
ree/master/samples). For Windows, please install [GIT bash](https://gitforwindows.org/). (If you find that there are new files g
enerated or unexpected changes as a result of the update, that's not unusual as the test cases are added to the OpenAPI spec fro
m time to time. If you've questions or concerns, please open a ticket to start a discussion)
- During development it can be helpful to quickly regenerate the samples without recompiling all of openapi-generator, e.g. when you have only updated the mustache templates. This can be done by passing the `-t` parameter: `-t modules/openapi-generator/src/main/resources/python`.
@@ -113,8 +114,7 @@ See [OpenAPI Tools wiki](https://github.com/OpenAPITools/openapi-generator/wiki/
- Add test case(s) to cover the change
- Document the fix in the code to make the code more readable
- Make sure test cases passed after the change (one way is to leverage https://travis-ci.org/ to run the CI tests)
- File a PR with meaningful title, description and commit messages
- Make sure the option "Allow edits from maintainers" in the PR is selected so that the maintainers can update your PRs with minor fixes, if needed.
- File a PR with meaningful title, description and commit messages.
- Recommended git settings
- `git config core.autocrlf input` to tell Git convert CRLF to LF on commit but not the other way around
- To close an issue (e.g. issue 1542) automatically after a PR is merged, use keywords "fix", "close", "resolve" in the PR description, e.g. `fix #1542`. (Ref: [closing issues using keywords](https://help.github.com/articles/closing-issues-using-keywords/))

View File

@@ -18,7 +18,7 @@ sidebar_label: aspnetcore
|modelClassModifier|Model Class Modifier can be nothing or partial| |partial|
|newtonsoftVersion|Version for Microsoft.AspNetCore.Mvc.NewtonsoftJson for ASP.NET Core 3.0+| |3.0.0|
|operationIsAsync|Set methods to async or sync (default).| |false|
|operationModifier|Operation Modifier can be virtual or abstract| |virtual|
|operationModifier|Operation Modifier can be virtual, abstract or partial| |virtual|
|operationResultTask|Set methods result to Task&lt;&gt;.| |false|
|packageAuthors|Specifies Authors property in the .NET Core project file.| |OpenAPI|
|packageCopyright|Specifies an AssemblyCopyright for the .NET Framework global assembly attributes stored in the AssemblyInfo file.| |No Copyright|

View File

@@ -5,7 +5,6 @@ sidebar_label: go-server
| Option | Description | Values | Default |
| ------ | ----------- | ------ | ------- |
|enumClassPrefix|Prefix enum with class name| |false|
|featureCORS|Enable Cross-Origin Resource Sharing middleware| |false|
|hideGenerationTimestamp|Hides the generation timestamp when files are generated.| |true|
|packageName|Go package name (convention: lowercase).| |openapi|

View File

@@ -31,7 +31,7 @@ sidebar_label: java
|invokerPackage|root package for generated code| |org.openapitools.client|
|java8|Use Java8 classes instead of third party equivalents. Starting in 5.x, JDK8 is the default and the support for JDK7, JDK6 has been dropped|<dl><dt>**true**</dt><dd>Use Java 8 classes such as Base64</dd><dt>**false**</dt><dd>Various third party libraries as needed</dd></dl>|true|
|legacyDiscriminatorBehavior|This flag is used by OpenAPITools codegen to influence the processing of the discriminator attribute in OpenAPI documents. This flag has no impact if the OAS document does not use the discriminator attribute. The default value of this flag is set in each language-specific code generator (e.g. Python, Java, go...)using the method toModelName. Note to developers supporting a language generator in OpenAPITools; to fully support the discriminator attribute as defined in the OAS specification 3.x, language generators should set this flag to true by default; however this requires updating the mustache templates to generate a language-specific discriminator lookup function that iterates over {{#mappedModels}} and does not iterate over {{children}}, {{#anyOf}}, or {{#oneOf}}.|<dl><dt>**true**</dt><dd>The mapping in the discriminator includes descendent schemas that allOf inherit from self and the discriminator mapping schemas in the OAS document.</dd><dt>**false**</dt><dd>The mapping in the discriminator includes any descendent schemas that allOf inherit from self, any oneOf schemas, any anyOf schemas, any x-discriminator-values, and the discriminator mapping schemas in the OAS document AND Codegen validates that oneOf and anyOf schemas contain the required discriminator and throws an error if the discriminator is missing.</dd></dl>|true|
|library|library template (sub-template) to use|<dl><dt>**jersey1**</dt><dd>HTTP client: Jersey client 1.19.x. JSON processing: Jackson 2.9.x. Enable Java6 support using '-DsupportJava6=true'. Enable gzip request encoding using '-DuseGzipFeature=true'. IMPORTANT NOTE: jersey 1.x is no longer actively maintained so please upgrade to 'jersey2' or other HTTP libaries instead.</dd><dt>**jersey2**</dt><dd>HTTP client: Jersey client 2.25.1. JSON processing: Jackson 2.9.x</dd><dt>**feign**</dt><dd>HTTP client: OpenFeign 10.x. JSON processing: Jackson 2.9.x.</dd><dt>**okhttp-gson**</dt><dd>[DEFAULT] HTTP client: OkHttp 3.x. JSON processing: Gson 2.8.x. Enable Parcelable models on Android using '-DparcelableModel=true'. Enable gzip request encoding using '-DuseGzipFeature=true'.</dd><dt>**retrofit2**</dt><dd>HTTP client: OkHttp 3.x. JSON processing: Gson 2.x (Retrofit 2.3.0). Enable the RxJava adapter using '-DuseRxJava[2/3]=true'. (RxJava 1.x or 2.x or 3.x)</dd><dt>**resttemplate**</dt><dd>HTTP client: Spring RestTemplate 4.x. JSON processing: Jackson 2.9.x</dd><dt>**webclient**</dt><dd>HTTP client: Spring WebClient 5.x. JSON processing: Jackson 2.9.x</dd><dt>**resteasy**</dt><dd>HTTP client: Resteasy client 3.x. JSON processing: Jackson 2.9.x</dd><dt>**vertx**</dt><dd>HTTP client: VertX client 3.x. JSON processing: Jackson 2.9.x</dd><dt>**google-api-client**</dt><dd>HTTP client: Google API client 1.x. JSON processing: Jackson 2.9.x</dd><dt>**rest-assured**</dt><dd>HTTP client: rest-assured : 4.x. JSON processing: Gson 2.x or Jackson 2.10.x. Only for Java 8</dd><dt>**native**</dt><dd>HTTP client: Java native HttpClient. JSON processing: Jackson 2.9.x. Only for Java11+</dd><dt>**microprofile**</dt><dd>HTTP client: Microprofile client 1.x. JSON processing: Jackson 2.9.x</dd></dl>|okhttp-gson|
|library|library template (sub-template) to use|<dl><dt>**jersey1**</dt><dd>HTTP client: Jersey client 1.19.x. JSON processing: Jackson 2.9.x. Enable Java6 support using '-DsupportJava6=true'. Enable gzip request encoding using '-DuseGzipFeature=true'. IMPORTANT NOTE: jersey 1.x is no longer actively maintained so please upgrade to 'jersey2' or other HTTP libaries instead.</dd><dt>**jersey2**</dt><dd>HTTP client: Jersey client 2.25.1. JSON processing: Jackson 2.9.x</dd><dt>**feign**</dt><dd>HTTP client: OpenFeign 11.x. JSON processing: Jackson 2.9.x.</dd><dt>**okhttp-gson**</dt><dd>[DEFAULT] HTTP client: OkHttp 3.x. JSON processing: Gson 2.8.x. Enable Parcelable models on Android using '-DparcelableModel=true'. Enable gzip request encoding using '-DuseGzipFeature=true'.</dd><dt>**retrofit2**</dt><dd>HTTP client: OkHttp 3.x. JSON processing: Gson 2.x (Retrofit 2.3.0). Enable the RxJava adapter using '-DuseRxJava[2/3]=true'. (RxJava 1.x or 2.x or 3.x)</dd><dt>**resttemplate**</dt><dd>HTTP client: Spring RestTemplate 4.x. JSON processing: Jackson 2.9.x</dd><dt>**webclient**</dt><dd>HTTP client: Spring WebClient 5.x. JSON processing: Jackson 2.9.x</dd><dt>**resteasy**</dt><dd>HTTP client: Resteasy client 3.x. JSON processing: Jackson 2.9.x</dd><dt>**vertx**</dt><dd>HTTP client: VertX client 3.x. JSON processing: Jackson 2.9.x</dd><dt>**google-api-client**</dt><dd>HTTP client: Google API client 1.x. JSON processing: Jackson 2.9.x</dd><dt>**rest-assured**</dt><dd>HTTP client: rest-assured : 4.x. JSON processing: Gson 2.x or Jackson 2.10.x. Only for Java 8</dd><dt>**native**</dt><dd>HTTP client: Java native HttpClient. JSON processing: Jackson 2.9.x. Only for Java11+</dd><dt>**microprofile**</dt><dd>HTTP client: Microprofile client 1.x. JSON processing: Jackson 2.9.x</dd></dl>|okhttp-gson|
|licenseName|The name of the license| |Unlicense|
|licenseUrl|The URL of the license| |http://unlicense.org|
|modelPackage|package for generated models| |org.openapitools.client.model|
@@ -52,7 +52,6 @@ sidebar_label: java
|sortParamsByRequiredFlag|Sort method arguments to place required parameters before optional parameters.| |true|
|sourceFolder|source folder for generated code| |src/main/java|
|supportJava6|Whether to support Java6 with the Jersey1 library. This option has been deprecated and will be removed in the 5.x release| |false|
|useAbstractionForFiles|Use alternative types instead of java.io.File to allow passing bytes without a file on disk. Available on resttemplate library| |false|
|useBeanValidation|Use BeanValidation API annotations| |false|
|useGzipFeature|Send gzip-encoded requests| |false|
|usePlayWS|Use Play! Async HTTP client (Play WS API)| |false|

View File

@@ -25,7 +25,6 @@ sidebar_label: kotlin
|useCoroutines|Whether to use the Coroutines adapter with the retrofit2 library.| |false|
|useRxJava|Whether to use the RxJava adapter with the retrofit2 library.| |false|
|useRxJava2|Whether to use the RxJava2 adapter with the retrofit2 library.| |false|
|useRxJava3|Whether to use the RxJava3 adapter with the retrofit2 library.| |false|
## IMPORT MAPPING

View File

@@ -16,7 +16,7 @@ sidebar_label: typescript-angular
|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)| |10.0.0|
|ngVersion|The version of Angular. (At least 6.0.0)| |9.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|
@@ -64,7 +64,6 @@ sidebar_label: typescript-angular
<li>Map</li>
<li>Object</li>
<li>ReadonlyArray</li>
<li>Set</li>
<li>String</li>
<li>any</li>
<li>boolean</li>

View File

@@ -46,7 +46,6 @@ sidebar_label: typescript-angularjs-deprecated
<li>Map</li>
<li>Object</li>
<li>ReadonlyArray</li>
<li>Set</li>
<li>String</li>
<li>any</li>
<li>boolean</li>

View File

@@ -47,7 +47,6 @@ sidebar_label: typescript-angularjs
<li>Object</li>
<li>ReadonlyArray</li>
<li>String</li>
<li>Set</li>
<li>any</li>
<li>boolean</li>
<li>number</li>

View File

@@ -49,7 +49,6 @@ sidebar_label: typescript-aurelia
<li>Map</li>
<li>Object</li>
<li>ReadonlyArray</li>
<li>Set</li>
<li>String</li>
<li>any</li>
<li>boolean</li>

View File

@@ -54,7 +54,6 @@ sidebar_label: typescript-axios
<li>Map</li>
<li>Object</li>
<li>ReadonlyArray</li>
<li>Set</li>
<li>String</li>
<li>any</li>
<li>boolean</li>

View File

@@ -54,7 +54,6 @@ sidebar_label: typescript-fetch
<li>Map</li>
<li>Object</li>
<li>ReadonlyArray</li>
<li>Set</li>
<li>String</li>
<li>any</li>
<li>boolean</li>

View File

@@ -55,7 +55,6 @@ sidebar_label: typescript-inversify
<li>Map</li>
<li>Object</li>
<li>ReadonlyArray</li>
<li>Set</li>
<li>String</li>
<li>any</li>
<li>boolean</li>

View File

@@ -51,7 +51,6 @@ sidebar_label: typescript-jquery
<li>Map</li>
<li>Object</li>
<li>ReadonlyArray</li>
<li>Set</li>
<li>String</li>
<li>any</li>
<li>boolean</li>

View File

@@ -54,7 +54,6 @@ sidebar_label: typescript-node
<li>ReadonlyArray</li>
<li>RequestDetailedFile</li>
<li>RequestFile</li>
<li>Set</li>
<li>String</li>
<li>any</li>
<li>boolean</li>

View File

@@ -52,7 +52,6 @@ sidebar_label: typescript-redux-query
<li>Map</li>
<li>Object</li>
<li>ReadonlyArray</li>
<li>Set</li>
<li>String</li>
<li>any</li>
<li>boolean</li>

View File

@@ -52,7 +52,6 @@ sidebar_label: typescript-rxjs
<li>Map</li>
<li>Object</li>
<li>ReadonlyArray</li>
<li>Set</li>
<li>String</li>
<li>any</li>
<li>boolean</li>

View File

@@ -61,35 +61,6 @@ task validateBadSpec(type: org.openapitools.generator.gradle.plugin.tasks.Valida
task validateSpecs(dependsOn: ['validateGoodSpec', 'validateBadSpec'])
----
[NOTE]
====
The tasks support Gradle Up-To-Date checking and Gradle Cache. Enable caching globally by setting `org.gradle.caching=true` in the `gradle.settings`
file or by passing the command line property `--build-cache` when executing on the command line.
Disable up-to-date checks and caching by setting the following property when using the extension:
.Disable caching for extension
[source,groovy]
----
tasks.withType(org.openapitools.generator.gradle.plugin.tasks.GenerateTask) {
outputs.upToDateWhen { false }
outputs.cacheIf { false }
}
----
Disable up-to-date checks and caching for a custom task:
.Disable caching for custom task
[source,groovy]
----
task validateGoodSpec(type: org.openapitools.generator.gradle.plugin.tasks.ValidateTask){
outputs.upToDateWhen { false }
outputs.cacheIf { false }
inputSpec = "$rootDir/petstore-v3.0.yaml".toString()
}
----
====
== Plugin Setup
//# RELEASE_VERSION

View File

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

View File

@@ -1,18 +1,18 @@
# Local Spec Sample
This example assumes you have Gradle 5.6.4+ installed. No gradle wrapper is provided in samples.
This example assumes you have Gradle 4.7+ installed. No gradle wrapper is provided in samples.
First, publish the openapi-generator-gradle-plugin locally via `./gradlew assemble publishToMavenLocal` in the module directory.
First, publish the openapi-generator-gradle-plugin locally via `./gradlew assemble install` in the module directory.
Then, run the following tasks in this example directory.
```bash
gradle openApiGenerate # expected outcome: BUILD SCCESSFUL
gradle openApiMeta # expected outcome: BUILD SCCESSFUL
gradle openApiValidate # expected outcome: BUILD FAILED
gradle buildGoSdk # expected outcome: BUILD SCCESSFUL
gradle buildDotnetSdk # expected outcome: BUILD SCCESSFUL
gradle generateGoWithInvalidSpec # expected outcome: BUILD FAILED
gradle openApiGenerate
gradle openApiMeta
gradle openApiValidate
gradle buildGoSdk
gradle buildDotnetSdk
gradle generateGoWithInvalidSpec
```
The samples can be tested against other versions of the plugin using the `openApiGeneratorVersion` property. For example:

View File

@@ -19,14 +19,7 @@ package org.openapitools.generator.gradle.plugin.tasks
import org.gradle.api.DefaultTask
import org.gradle.api.GradleException
import org.gradle.api.provider.Property
import org.gradle.api.tasks.CacheableTask
import org.gradle.api.tasks.Input
import org.gradle.api.tasks.InputFile
import org.gradle.api.tasks.Internal
import org.gradle.api.tasks.Optional
import org.gradle.api.tasks.OutputDirectory
import org.gradle.api.tasks.PathSensitive
import org.gradle.api.tasks.PathSensitivity
import org.gradle.api.tasks.TaskAction
import org.gradle.api.tasks.options.Option
import org.gradle.internal.logging.text.StyledTextOutput
@@ -39,6 +32,7 @@ import org.openapitools.codegen.DefaultGenerator
import org.openapitools.codegen.config.CodegenConfigurator
import org.openapitools.codegen.config.GlobalSettings
/**
* A task which generates the desired code.
*
@@ -49,41 +43,35 @@ import org.openapitools.codegen.config.GlobalSettings
* @author Jim Schubert
*/
@Suppress("UnstableApiUsage")
@CacheableTask
open class GenerateTask : DefaultTask() {
/**
* The verbosity of generation
*/
@Optional
@Input
@get:Internal
val verbose = project.objects.property<Boolean>()
/**
* Whether or not an input specification should be validated upon generation.
*/
@Optional
@Input
@get:Internal
val validateSpec = project.objects.property<Boolean>()
/**
* The name of the generator which will handle codegen. (see "openApiGenerators" task)
*/
@Optional
@Input
@get:Internal
val generatorName = project.objects.property<String>()
/**
* The output target directory into which code will be generated.
*/
@Optional
@get:OutputDirectory
@get:Internal
val outputDir = project.objects.property<String>()
@Suppress("unused")
@get:Internal
@set:Option(option = "input", description = "The input specification.")
@Input
var input: String? = null
set(value) {
inputSpec.set(value)
@@ -92,30 +80,26 @@ open class GenerateTask : DefaultTask() {
/**
* The Open API 2.0/3.x specification location.
*/
@get:InputFile
@PathSensitive(PathSensitivity.RELATIVE)
@get:Internal
val inputSpec = project.objects.property<String>()
/**
* The template directory holding a custom template.
*/
@Optional
@Input
@get:Internal
val templateDir = project.objects.property<String?>()
/**
* Adds authorization headers when fetching the OpenAPI definitions remotely.
* Pass in a URL-encoded string of name:header with a comma separating multiple values
*/
@Optional
@Input
@get:Internal
val auth = project.objects.property<String>()
/**
* Sets specified global properties.
*/
@Optional
@Input
@get:Internal
val globalProperties = project.objects.mapProperty<String, String>()
/**
@@ -123,185 +107,159 @@ open class GenerateTask : DefaultTask() {
* File content should be in a json format { "optionKey":"optionValue", "optionKey1":"optionValue1"...}
* Supported options can be different for each language. Run config-help -g {generator name} command for language specific config options.
*/
@Optional
@Input
@get:Internal
val configFile = project.objects.property<String>()
/**
* Specifies if the existing files should be overwritten during the generation.
*/
@Optional
@Input
@get:Internal
val skipOverwrite = project.objects.property<Boolean?>()
/**
* Package for generated classes (where supported)
*/
@Optional
@Input
@get:Internal
val packageName = project.objects.property<String>()
/**
* Package for generated api classes
*/
@Optional
@Input
@get:Internal
val apiPackage = project.objects.property<String>()
/**
* Package for generated models
*/
@Optional
@Input
@get:Internal
val modelPackage = project.objects.property<String>()
/**
* Prefix that will be prepended to all model names. Default is the empty string.
*/
@Optional
@Input
@get:Internal
val modelNamePrefix = project.objects.property<String>()
/**
* Suffix that will be appended to all model names. Default is the empty string.
*/
@Optional
@Input
@get:Internal
val modelNameSuffix = project.objects.property<String>()
/**
* Sets instantiation type mappings.
*/
@Optional
@Input
@get:Internal
val instantiationTypes = project.objects.mapProperty<String, String>()
/**
* Sets mappings between OpenAPI spec types and generated code types.
*/
@Optional
@Input
@get:Internal
val typeMappings = project.objects.mapProperty<String, String>()
/**
* Sets additional properties that can be referenced by the mustache templates in the format of name=value,name=value.
* You can also have multiple occurrences of this option.
*/
@Optional
@Input
@get:Internal
val additionalProperties = project.objects.mapProperty<String, String>()
/**
* Sets server variable for server URL template substitution, in the format of name=value,name=value.
* You can also have multiple occurrences of this option.
*/
@Optional
@Input
@get:Internal
val serverVariables = project.objects.mapProperty<String, String>()
/**
* Specifies additional language specific primitive types in the format of type1,type2,type3,type3. For example: String,boolean,Boolean,Double.
*/
@Optional
@Input
@get:Internal
val languageSpecificPrimitives = project.objects.listProperty<String>()
/**
* Specifies mappings between a given class and the import that should be used for that class.
*/
@Optional
@Input
@get:Internal
val importMappings = project.objects.mapProperty<String, String>()
/**
* Root package for generated code.
*/
@Optional
@Input
@get:Internal
val invokerPackage = project.objects.property<String>()
/**
* GroupId in generated pom.xml/build.gradle or other build script. Language-specific conversions occur in non-jvm generators.
*/
@Optional
@Input
@get:Internal
val groupId = project.objects.property<String>()
/**
* ArtifactId in generated pom.xml/build.gradle or other build script. Language-specific conversions occur in non-jvm generators.
*/
@Optional
@Input
@get:Internal
val id = project.objects.property<String>()
/**
* Artifact version in generated pom.xml/build.gradle or other build script. Language-specific conversions occur in non-jvm generators.
*/
@Optional
@Input
@get:Internal
val version = project.objects.property<String>()
/**
* Reference the library template (sub-template) of a generator.
*/
@Optional
@Input
@get:Internal
val library = project.objects.property<String?>()
/**
* Git host, e.g. gitlab.com.
*/
@Optional
@Input
@get:Internal
val gitHost = project.objects.property<String?>()
/**
* Git user ID, e.g. openapitools.
*/
@Optional
@Input
@get:Internal
val gitUserId = project.objects.property<String?>()
/**
* Git repo ID, e.g. openapi-generator.
*/
@Optional
@Input
@get:Internal
val gitRepoId = project.objects.property<String?>()
/**
* Release note, default to 'Minor update'.
*/
@Optional
@Input
@get:Internal
val releaseNote = project.objects.property<String?>()
/**
* HTTP user agent, e.g. codegen_csharp_api_client, default to 'OpenAPI-Generator/{packageVersion}/{language}'
*/
@Optional
@Input
@get:Internal
val httpUserAgent = project.objects.property<String?>()
/**
* Specifies how a reserved name should be escaped to.
*/
@Optional
@Input
@get:Internal
val reservedWordsMappings = project.objects.mapProperty<String, String>()
/**
* Specifies an override location for the .openapi-generator-ignore file. Most useful on initial generation.
*/
@Optional
@Input
@get:Internal
val ignoreFileOverride = project.objects.property<String?>()
/**
* Remove prefix of operationId, e.g. config_getId => getId
*/
@Optional
@Input
@get:Internal
val removeOperationIdPrefix = project.objects.property<Boolean?>()
/**
@@ -313,8 +271,7 @@ open class GenerateTask : DefaultTask() {
* in others being disabled. That is, OpenAPI Generator considers any one of these to define a subset of generation.
* For more control over generation of individual files, configure an ignore file and refer to it via [ignoreFileOverride].
*/
@Optional
@Input
@get:Internal
val apiFilesConstrainedTo = project.objects.listProperty<String>()
/**
@@ -324,8 +281,7 @@ open class GenerateTask : DefaultTask() {
* in others being disabled. That is, OpenAPI Generator considers any one of these to define a subset of generation.
* For more control over generation of individual files, configure an ignore file and refer to it via [ignoreFileOverride].
*/
@Optional
@Input
@get:Internal
val modelFilesConstrainedTo = project.objects.listProperty<String>()
/**
@@ -338,8 +294,7 @@ open class GenerateTask : DefaultTask() {
* in others being disabled. That is, OpenAPI Generator considers any one of these to define a subset of generation.
* For more control over generation of individual files, configure an ignore file and refer to it via [ignoreFileOverride].
*/
@Optional
@Input
@get:Internal
val supportingFilesConstrainedTo = project.objects.listProperty<String>()
/**
@@ -350,8 +305,7 @@ open class GenerateTask : DefaultTask() {
* For more control over generation of individual files, configure an ignore file and
* refer to it via [ignoreFileOverride].
*/
@Optional
@Input
@get:Internal
val generateModelTests = project.objects.property<Boolean>()
/**
@@ -362,8 +316,7 @@ open class GenerateTask : DefaultTask() {
* For more control over generation of individual files, configure an ignore file and
* refer to it via [ignoreFileOverride].
*/
@Optional
@Input
@get:Internal
val generateModelDocumentation = project.objects.property<Boolean>()
/**
@@ -374,8 +327,7 @@ open class GenerateTask : DefaultTask() {
* For more control over generation of individual files, configure an ignore file and
* refer to it via [ignoreFileOverride].
*/
@Optional
@Input
@get:Internal
val generateApiTests = project.objects.property<Boolean>()
/**
@@ -386,23 +338,21 @@ open class GenerateTask : DefaultTask() {
* For more control over generation of individual files, configure an ignore file and
* refer to it via [ignoreFileOverride].
*/
@Optional
@Input
@get:Internal
val generateApiDocumentation = project.objects.property<Boolean>()
/**
* A special-case setting which configures some generators with XML support. In some cases,
* this forces json OR xml, so the default here is false.
*/
@Optional
@Input
@get:Internal
val withXml = project.objects.property<Boolean>()
/**
* To write all log messages (not just errors) to STDOUT
*/
@Optional
@Input
@get:Internal
val logToStderr = project.objects.property<Boolean>()
/**
@@ -411,15 +361,13 @@ open class GenerateTask : DefaultTask() {
* LANG_POST_PROCESS_FILE (e.g. GO_POST_PROCESS_FILE, SCALA_POST_PROCESS_FILE). Please open an issue if your target
* generator does not support this functionality.
*/
@Optional
@Input
@get:Internal
val enablePostProcessFile = project.objects.property<Boolean>()
/**
* To skip spec validation. When true, we will skip the default behavior of validating a spec before generation.
*/
@Optional
@Input
@get:Internal
val skipValidateSpec = project.objects.property<Boolean>()
/**
@@ -427,22 +375,19 @@ open class GenerateTask : DefaultTask() {
* definitions generated as top-level Array-of-items, List-of-items, Map-of-items definitions.
* When true, A model representation either containing or extending the array,list,map (depending on specific generator implementation) will be generated.
*/
@Optional
@Input
@get:Internal
val generateAliasAsModel = project.objects.property<Boolean>()
/**
* A dynamic map of options specific to a generator.
*/
@Optional
@Input
@get:Internal
val configOptions = project.objects.mapProperty<String, String>()
/**
* Templating engine: "mustache" (default) or "handlebars" (beta)
*/
@Optional
@Input
@get:Internal
val engine = project.objects.property<String?>()
private fun <T : Any?> Property<T>.ifNotEmpty(block: Property<T>.(T) -> Unit) {

View File

@@ -19,18 +19,15 @@ package org.openapitools.generator.gradle.plugin.tasks
import com.samskivert.mustache.Mustache
import org.gradle.api.DefaultTask
import org.gradle.api.GradleException
import org.gradle.api.tasks.CacheableTask
import org.gradle.api.tasks.Input
import org.gradle.api.tasks.OutputDirectory
import org.gradle.api.tasks.Internal
import org.gradle.api.tasks.TaskAction
import org.gradle.internal.logging.text.StyledTextOutput
import org.gradle.internal.logging.text.StyledTextOutputFactory
import org.gradle.kotlin.dsl.property
import org.openapitools.codegen.CodegenConfig
import org.openapitools.codegen.CodegenConstants
import org.openapitools.codegen.SupportingFile
import org.openapitools.codegen.TemplateManager
import org.openapitools.codegen.*
import org.openapitools.codegen.api.TemplatePathLocator
import org.openapitools.codegen.templating.CommonTemplateContentLocator
import org.openapitools.codegen.templating.GeneratorTemplateContentLocator
import org.openapitools.codegen.templating.MustacheEngineAdapter
import org.openapitools.codegen.templating.TemplateManagerOptions
import java.io.File
@@ -42,16 +39,15 @@ import java.nio.charset.Charset
*
* @author Jim Schubert
*/
@CacheableTask
open class MetaTask : DefaultTask() {
@get:Input
@get:Internal
val generatorName = project.objects.property<String>()
@get:Input
@get:Internal
val packageName = project.objects.property<String>()
@get:OutputDirectory
@get:Internal
val outputFolder = project.objects.property<String>()
@Suppress("unused")

View File

@@ -23,12 +23,7 @@ import io.swagger.v3.parser.core.models.ParseOptions
import org.gradle.api.DefaultTask
import org.gradle.api.GradleException
import org.gradle.api.logging.Logging
import org.gradle.api.tasks.Input
import org.gradle.api.tasks.InputFile
import org.gradle.api.tasks.Internal
import org.gradle.api.tasks.Optional
import org.gradle.api.tasks.PathSensitive
import org.gradle.api.tasks.PathSensitivity
import org.gradle.api.tasks.TaskAction
import org.gradle.api.tasks.options.Option
import org.gradle.internal.logging.text.StyledTextOutput
@@ -54,12 +49,10 @@ import org.openapitools.codegen.validations.oas.RuleConfiguration
* @author Jim Schubert
*/
open class ValidateTask : DefaultTask() {
@get:InputFile
@PathSensitive(PathSensitivity.RELATIVE)
@get:Internal
var inputSpec = project.objects.property<String>()
@Optional
@Input
@get:Internal
var recommend = project.objects.property<Boolean?>()
@Suppress("unused")
@@ -87,6 +80,7 @@ open class ValidateTask : DefaultTask() {
val messages = result.messages.toSet()
val out = services.get(StyledTextOutputFactory::class.java).create("openapi")
val ruleConfiguration = RuleConfiguration()
ruleConfiguration.isEnableRecommendations = recommendations

View File

@@ -67,61 +67,6 @@ class GenerateTaskDslTest : TestBase() {
"Expected a successful run, but found ${result.task(":openApiGenerate")?.outcome}")
}
@Test
fun `openApiGenerate should used up-to-date instead of regenerate`() {
// Arrange
val projectFiles = mapOf(
"spec.yaml" to javaClass.classLoader.getResourceAsStream("specs/petstore-v3.0.yaml")
)
withProject(defaultBuildGradle, projectFiles)
// Act
val resultFirstRun = GradleRunner.create()
.withProjectDir(temp)
.withArguments("openApiGenerate")
.withPluginClasspath()
.build()
val resultSecondRun = GradleRunner.create()
.withProjectDir(temp)
.withArguments("openApiGenerate")
.withPluginClasspath()
.build()
// Assert
assertTrue(resultFirstRun.output.contains("Task ':openApiGenerate' is not up-to-date"), "First run should not be up-to-date")
assertTrue(resultSecondRun.output.contains("Task :openApiGenerate UP-TO-DATE"), "Task of second run should be up-to-date")
}
@Test
fun `openApiGenerate should use cache instead of regenerate`() {
// Arrange
val projectFiles = mapOf(
"spec.yaml" to javaClass.classLoader.getResourceAsStream("specs/petstore-v3.0.yaml")
)
withProject(defaultBuildGradle, projectFiles)
// Act
val resultFirstRun = GradleRunner.create()
.withProjectDir(temp)
.withArguments("openApiGenerate", "--build-cache")
.withPluginClasspath()
.build()
// delete the build directory from the last run
File(temp, "build/kotlin").deleteRecursively()
// re-run
val resultSecondRun = GradleRunner.create()
.withProjectDir(temp)
.withArguments("openApiGenerate", "--build-cache")
.withPluginClasspath()
.build()
// Assert
assertTrue(resultFirstRun.output.contains("Task ':openApiGenerate' is not up-to-date"), "First run should not be up-to-date")
assertTrue(resultSecondRun.output.contains("Task :openApiGenerate FROM-CACHE"), "Task of second run should be from cache")
}
@Test
fun `openApiValidate should fail on invalid spec`() {
// Arrange

View File

@@ -185,7 +185,7 @@
<properties>
<swagger-annotations-version>1.5.8</swagger-annotations-version>
<jersey-version>2.27</jersey-version>
<jackson-version>2.9.10</jackson-version>
<jackson-version>2.8.9</jackson-version>
<jackson-databind-nullable-version>0.2.0</jackson-databind-nullable-version>
<jodatime-version>2.7</jodatime-version>
<maven-plugin-version>1.0.0</maven-plugin-version>

View File

@@ -224,7 +224,7 @@
<properties>
<swagger-annotations-version>1.5.8</swagger-annotations-version>
<jersey-version>2.27</jersey-version>
<jackson-version>2.9.10</jackson-version>
<jackson-version>2.8.9</jackson-version>
<jackson-databind-nullable-version>0.2.0</jackson-databind-nullable-version>
<jodatime-version>2.7</jodatime-version>
<maven-plugin-version>1.0.0</maven-plugin-version>

View File

@@ -15,7 +15,7 @@
<properties>
<swagger-annotations-version>1.5.8</swagger-annotations-version>
<jersey-version>2.27</jersey-version>
<jackson-version>2.9.10</jackson-version>
<jackson-version>2.8.9</jackson-version>
<jackson-databind-nullable-version>0.2.0</jackson-databind-nullable-version>
<jodatime-version>2.7</jodatime-version>
<maven-plugin-version>1.0.0</maven-plugin-version>

View File

@@ -15,8 +15,8 @@
<java.version>1.8</java.version>
<maven.compiler.source>${java.version}</maven.compiler.source>
<maven.compiler.target>${java.version}</maven.compiler.target>
<spring-boot-version>2.2.9.RELEASE</spring-boot-version>
<springfox-version>3.0.0</springfox-version>
<spring-boot-version>2.0.7.RELEASE</spring-boot-version>
<springfox-version>2.8.0</springfox-version>
<junit-version>4.13</junit-version>
<jackson-version>2.10.2</jackson-version>
</properties>
@@ -112,10 +112,6 @@
<groupId>io.swagger</groupId>
<artifactId>swagger-models</artifactId>
</exclusion>
<exclusion>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
</exclusion>
</exclusions>
</dependency>

View File

@@ -23,7 +23,6 @@ import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.web.filter.ForwardedHeaderFilter;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@@ -61,9 +60,4 @@ public class OpenAPI2SpringBoot implements CommandLineRunner {
}
};
}
@Bean
ForwardedHeaderFilter forwardedHeaderFilter() {
return new ForwardedHeaderFilter();
}
}

View File

@@ -22,7 +22,7 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.
@WebMvcTest(GenApiController.class)
public class GenApiControllerTest {
private static final String OPENAPI_URL = "https://raw.githubusercontent.com/OpenAPITools/openapi-generator/v4.3.1/modules/openapi-generator/src/test/resources/petstore.json";
private static final String OPENAPI_URL = "http://petstore.swagger.io/v2/swagger.json";
private static final String UUID_REGEX = "[a-fA-F0-9]{8}-[a-fA-F0-9]{4}-4[a-fA-F0-9]{3}-[89aAbB][a-fA-F0-9]{3}-[a-fA-F0-9]{12}";
@Autowired
@@ -43,7 +43,7 @@ public class GenApiControllerTest {
public void getLanguages(String type, String expected) throws Exception {
mockMvc.perform(get("/api/gen/" + type))
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON))
.andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8))
.andExpect(jsonPath("$.[*]").value(hasItem(expected)));
}
@@ -72,7 +72,7 @@ public class GenApiControllerTest {
private void getOptions(String type, String name) throws Exception {
mockMvc.perform(get("/api/gen/" + type + "/" + name))
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON))
.andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8))
.andExpect(jsonPath("$.sortParamsByRequiredFlag.opt").value("sortParamsByRequiredFlag"));
}
@@ -88,10 +88,10 @@ public class GenApiControllerTest {
private void generateAndDownload(String type, String name) throws Exception {
String result = mockMvc.perform(post("http://test.com:1234/api/gen/" + type + "/" + name)
.contentType(MediaType.APPLICATION_JSON)
.contentType(MediaType.APPLICATION_JSON_UTF8)
.content("{\"openAPIUrl\": \"" + OPENAPI_URL + "\"}"))
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON))
.andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8))
.andExpect(jsonPath("$.code").value(matchesPattern(UUID_REGEX)))
.andExpect(jsonPath("$.link").value(matchesPattern("http\\:\\/\\/test.com\\:1234\\/api\\/gen\\/download\\/" + UUID_REGEX)))
.andReturn().getResponse().getContentAsString();
@@ -107,13 +107,13 @@ public class GenApiControllerTest {
@Test
public void generateWIthForwardedHeaders() throws Exception {
String result = mockMvc.perform(post("http://test.com:1234/api/gen/clients/java")
.contentType(MediaType.APPLICATION_JSON)
.contentType(MediaType.APPLICATION_JSON_UTF8)
.header("X-Forwarded-Proto", "https")
.header("X-Forwarded-Host", "forwarded.com")
.header("X-Forwarded-Port", "5678")
.content("{\"openAPIUrl\": \"" + OPENAPI_URL + "\"}"))
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON))
.andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8))
.andExpect(jsonPath("$.code").value(matchesPattern(UUID_REGEX)))
.andExpect(jsonPath("$.link").value(matchesPattern("https\\:\\/\\/forwarded.com\\:5678\\/api\\/gen\\/download\\/" + UUID_REGEX)))
.andReturn().getResponse().getContentAsString();

View File

@@ -49,11 +49,9 @@ public class CodegenModel implements IJsonSchemaValidationProperties {
public Set<String> oneOf = new TreeSet<String>();
public Set<String> allOf = new TreeSet<String>();
// The schema name as written in the OpenAPI document.
public String name;
// The language-specific name of the class that implements this schema.
// The name of the class is derived from the OpenAPI schema name with formatting rules applied.
// The classname is derived from the OpenAPI schema name, with sanitization and escaping rules applied.
public String classname;
// The value of the 'title' attribute in the OpenAPI document.
public String title;
@@ -222,17 +220,6 @@ public class CodegenModel implements IJsonSchemaValidationProperties {
this.classVarName = classVarName;
}
/**
* Return true if the classname property is sanitized, false if it is the same as the OpenAPI schema name.
* The OpenAPI schema name may be any valid JSON schema name, including non-ASCII characters.
* The name of the class may have to be sanitized with character escaping.
*
* @return true if the classname property is sanitized
*/
public boolean getIsClassnameSanitized() {
return !classname.equals(name);
}
public String getClassname() {
return classname;
}

View File

@@ -1768,7 +1768,7 @@ public class DefaultCodegen implements CodegenConfig {
if (encoding != null) {
codegenParameter.contentType = encoding.getContentType();
} else {
LOGGER.debug("encoding not specified for {}", codegenParameter.baseName);
LOGGER.debug("encoding not specified for " + codegenParameter.baseName);
}
}
}
@@ -1790,9 +1790,6 @@ public class DefaultCodegen implements CodegenConfig {
/**
* Return the default value of the property
*
* Return null if you do NOT want a default value.
* Any non-null value will cause {{#defaultValue} check to pass.
*
* @param schema Property schema
* @return string presentation of the default value of the property
*/
@@ -1813,7 +1810,7 @@ public class DefaultCodegen implements CodegenConfig {
*/
@SuppressWarnings("squid:S3923")
private String getPropertyDefaultValue(Schema schema) {
/*
/**
* Although all branches return null, this is left intentionally as examples for new contributors
*/
if (ModelUtils.isBooleanSchema(schema)) {
@@ -1963,10 +1960,10 @@ public class DefaultCodegen implements CodegenConfig {
/**
* Return a string representation of the schema type, resolving aliasing and references if necessary.
*
* @param schema input
* @param schema
* @return the string representation of the schema type.
*/
protected String getSingleSchemaType(Schema schema) {
private String getSingleSchemaType(Schema schema) {
Schema unaliasSchema = ModelUtils.unaliasSchema(this.openAPI, schema, importMapping);
if (StringUtils.isNotBlank(unaliasSchema.get$ref())) { // reference to another definition/schema
@@ -5653,11 +5650,8 @@ public class DefaultCodegen implements CodegenConfig {
LOGGER.debug("debugging fromRequestBodyToFormParameters= " + body);
Schema schema = ModelUtils.getSchemaFromRequestBody(body);
schema = ModelUtils.getReferencedSchema(this.openAPI, schema);
List<String> allRequired = new ArrayList<String>();
Map<String, Schema> properties = new LinkedHashMap<>();
addProperties(properties, allRequired, schema);
if (!properties.isEmpty()) {
if (schema.getProperties() != null && !schema.getProperties().isEmpty()) {
Map<String, Schema> properties = schema.getProperties();
for (Map.Entry<String, Schema> entry : properties.entrySet()) {
CodegenParameter codegenParameter = CodegenModelFactory.newInstance(CodegenModelType.PARAMETER);
// key => property name
@@ -5912,7 +5906,7 @@ public class DefaultCodegen implements CodegenConfig {
if (ModelUtils.isMapSchema(schema)) {
// Schema with additionalproperties: true (including composed schemas with additionalproperties: true)
if (ModelUtils.isGenerateAliasAsModel(schema) && StringUtils.isNotBlank(name)) {
if (ModelUtils.isGenerateAliasAsModel() && StringUtils.isNotBlank(name)) {
this.addBodyModelSchema(codegenParameter, name, schema, imports, bodyParameterName, true);
} else {
Schema inner = getAdditionalProperties(schema);
@@ -5953,7 +5947,7 @@ public class DefaultCodegen implements CodegenConfig {
setParameterNullable(codegenParameter, codegenProperty);
}
} else if (ModelUtils.isArraySchema(schema)) {
if (ModelUtils.isGenerateAliasAsModel(schema) && StringUtils.isNotBlank(name)) {
if (ModelUtils.isGenerateAliasAsModel() && StringUtils.isNotBlank(name)) {
this.addBodyModelSchema(codegenParameter, name, schema, imports, bodyParameterName, true);
} else {
final ArraySchema arraySchema = (ArraySchema) schema;

View File

@@ -452,13 +452,13 @@ public class DefaultGenerator implements Generator {
// 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() && !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())) {
if (!ModelUtils.isGenerateAliasAsModel() && (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;

View File

@@ -17,10 +17,6 @@
package org.openapitools.codegen;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.util.DefaultPrettyPrinter;
import com.fasterxml.jackson.databind.MapperFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.swagger.v3.core.util.Json;
import io.swagger.v3.oas.models.*;
import io.swagger.v3.oas.models.callbacks.Callback;
@@ -29,7 +25,6 @@ import io.swagger.v3.oas.models.parameters.Parameter;
import io.swagger.v3.oas.models.parameters.RequestBody;
import io.swagger.v3.oas.models.responses.ApiResponse;
import io.swagger.v3.oas.models.responses.ApiResponses;
import org.apache.commons.lang3.StringUtils;
import org.openapitools.codegen.utils.ModelUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -41,17 +36,6 @@ public class InlineModelResolver {
private OpenAPI openapi;
private Map<String, Schema> addedModels = new HashMap<String, Schema>();
private Map<String, String> generatedSignature = new HashMap<String, String>();
// structure mapper sorts properties alphabetically on write to ensure models are
// serialized consistently for lookup of existing models
private static ObjectMapper structureMapper;
static {
structureMapper = Json.mapper().copy();
structureMapper.configure(MapperFeature.SORT_PROPERTIES_ALPHABETICALLY, true);
structureMapper.writer(new DefaultPrettyPrinter());
}
static Logger LOGGER = LoggerFactory.getLogger(InlineModelResolver.class);
void flatten(OpenAPI openapi) {
@@ -504,25 +488,15 @@ public class InlineModelResolver {
}
private String matchGenerated(Schema model) {
try {
String json = structureMapper.writeValueAsString(model);
String json = Json.pretty(model);
if (generatedSignature.containsKey(json)) {
return generatedSignature.get(json);
}
} catch (JsonProcessingException e) {
e.printStackTrace();
}
return null;
}
private void addGenerated(String name, Schema model) {
try {
String json = structureMapper.writeValueAsString(model);
generatedSignature.put(json, name);
} catch (JsonProcessingException e) {
e.printStackTrace();
}
generatedSignature.put(Json.pretty(model), name);
}
/**
@@ -646,45 +620,13 @@ public class InlineModelResolver {
}
XML xml = object.getXml();
Map<String, Schema> properties = object.getProperties();
// NOTE:
// No need to null check setters below. All defaults in the new'd Schema are null, so setting to null would just be a noop.
Schema model = new Schema();
model.setType(object.getType());
// Even though the `format` keyword typically applies to primitive types only,
// the JSON schema specification states `format` can be used for any model type instance
// including object types.
model.setFormat(object.getFormat());
model.setDescription(description);
model.setExample(example);
model.setName(object.getName());
model.setXml(xml);
model.setRequired(object.getRequired());
model.setNullable(object.getNullable());
model.setDiscriminator(object.getDiscriminator());
model.setWriteOnly(object.getWriteOnly());
model.setUniqueItems(object.getUniqueItems());
model.setTitle(object.getTitle());
model.setReadOnly(object.getReadOnly());
model.setPattern(object.getPattern());
model.setNot(object.getNot());
model.setMinProperties(object.getMinProperties());
model.setMinLength(object.getMinLength());
model.setMinItems(object.getMinItems());
model.setMinimum(object.getMinimum());
model.setMaxProperties(object.getMaxProperties());
model.setMaxLength(object.getMaxLength());
model.setMaxItems(object.getMaxItems());
model.setMaximum(object.getMaximum());
model.setExternalDocs(object.getExternalDocs());
model.setExtensions(object.getExtensions());
model.setExclusiveMinimum(object.getExclusiveMinimum());
model.setExclusiveMaximum(object.getExclusiveMaximum());
model.setExample(object.getExample());
model.setDeprecated(object.getDeprecated());
if (properties != null) {
flattenProperties(openAPI, properties, path);
model.setProperties(properties);

View File

@@ -469,7 +469,6 @@ public abstract class AbstractJavaCodegen extends DefaultCodegen implements Code
importMapping.put("JsonProperty", "com.fasterxml.jackson.annotation.JsonProperty");
importMapping.put("JsonSubTypes", "com.fasterxml.jackson.annotation.JsonSubTypes");
importMapping.put("JsonTypeInfo", "com.fasterxml.jackson.annotation.JsonTypeInfo");
importMapping.put("JsonTypeName", "com.fasterxml.jackson.annotation.JsonTypeName");
importMapping.put("JsonCreator", "com.fasterxml.jackson.annotation.JsonCreator");
importMapping.put("JsonValue", "com.fasterxml.jackson.annotation.JsonValue");
importMapping.put("JsonIgnore", "com.fasterxml.jackson.annotation.JsonIgnore");
@@ -798,7 +797,7 @@ public abstract class AbstractJavaCodegen extends DefaultCodegen implements Code
Schema<?> items = getSchemaItems((ArraySchema) schema);
String typeDeclaration = getTypeDeclaration(ModelUtils.unaliasSchema(this.openAPI, items));
String typeDeclaration = getTypeDeclaration(items);
Object java8obj = additionalProperties.get("java8");
if (java8obj != null) {
Boolean java8 = Boolean.valueOf(java8obj.toString());

View File

@@ -130,8 +130,7 @@ public abstract class AbstractTypeScriptClientCodegen extends DefaultCodegen imp
"File",
"Error",
"Map",
"object",
"Set"
"object"
));
languageGenericTypes = new HashSet<>(Collections.singletonList(
@@ -141,8 +140,6 @@ public abstract class AbstractTypeScriptClientCodegen extends DefaultCodegen imp
instantiationTypes.put("array", "Array");
typeMapping = new HashMap<String, String>();
typeMapping.put("Set", "Set");
typeMapping.put("set", "Set");
typeMapping.put("Array", "Array");
typeMapping.put("array", "Array");
typeMapping.put("boolean", "boolean");
@@ -849,7 +846,7 @@ public abstract class AbstractTypeScriptClientCodegen extends DefaultCodegen imp
*/
protected List<String> getTypesFromSchemas(List<Schema> schemas) {
List<Schema> filteredSchemas = schemas.size() > 1
? schemas.stream().filter(schema -> !"AnyType".equals(super.getSchemaType(schema))).collect(Collectors.toList())
? schemas.stream().filter(schema -> super.getSchemaType(schema) != "AnyType").collect(Collectors.toList())
: schemas;
return filteredSchemas.stream().map(schema -> {

View File

@@ -70,7 +70,7 @@ public class AspNetCoreServerCodegen extends AbstractCSharpCodegen {
protected CliOption swashbuckleVersion = new CliOption(SWASHBUCKLE_VERSION, "Swashbuckle version: 3.0.0, 4.0.0, 5.0.0");
protected CliOption aspnetCoreVersion = new CliOption(ASPNET_CORE_VERSION, "ASP.NET Core version: 3.1, 3.0, 2.2, 2.1, 2.0 (deprecated)");
private CliOption classModifier = new CliOption(CLASS_MODIFIER, "Class Modifier can be empty, abstract");
private CliOption operationModifier = new CliOption(OPERATION_MODIFIER, "Operation Modifier can be virtual or abstract");
private CliOption operationModifier = new CliOption(OPERATION_MODIFIER, "Operation Modifier can be virtual, abstract or partial");
private CliOption modelClassModifier = new CliOption(MODEL_CLASS_MODIFIER, "Model Class Modifier can be nothing or partial");
private boolean generateBody = true;
private CliOption buildTarget = new CliOption("buildTarget", "Target to build an application or library");

View File

@@ -476,7 +476,7 @@ public class CSharpNetCoreClientCodegen extends AbstractCSharpCodegen {
+ "/pattern/modifiers convention. " + pattern + " is not valid.");
}
String regex = pattern.substring(1, i).replace("'", "\'").replace("\"", "\"\"");
String regex = pattern.substring(1, i).replace("'", "\'");
List<String> modifiers = new ArrayList<String>();
// perl requires an explicit modifier to be culture specific and .NET is the reverse.

View File

@@ -335,7 +335,7 @@ public class CppUE4ClientCodegen extends AbstractCppCodegen {
public String modelFilename(String templateName, String modelName) {
String suffix = modelTemplateFiles().get(templateName);
String folder = privateFolder;
if (".h".equals(suffix)) {
if (suffix == ".h") {
folder = publicFolder;
}

View File

@@ -17,7 +17,6 @@
package org.openapitools.codegen.languages;
import com.google.common.collect.Sets;
import io.swagger.v3.oas.models.media.ArraySchema;
import io.swagger.v3.oas.models.media.Schema;
@@ -31,8 +30,9 @@ import org.slf4j.LoggerFactory;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.nio.charset.Charset;
import java.util.*;
import static org.openapitools.codegen.utils.StringUtils.camelize;
@@ -50,7 +50,6 @@ public class DartClientCodegen extends DefaultCodegen implements CodegenConfig {
public static final String PUB_HOMEPAGE = "pubHomepage";
public static final String USE_ENUM_EXTENSION = "useEnumExtension";
public static final String SUPPORT_DART2 = "supportDart2";
protected boolean browserClient = true;
protected String pubName = "openapi";
protected String pubVersion = "1.0.0";
@@ -107,11 +106,9 @@ public class DartClientCodegen extends DefaultCodegen implements CodegenConfig {
modelTestTemplateFiles.put("model_test.mustache", ".dart");
apiTestTemplateFiles.put("api_test.mustache", ".dart");
List<String> reservedWordsList = new ArrayList<>();
List<String> reservedWordsList = new ArrayList<String>();
try {
BufferedReader reader = new BufferedReader(
new InputStreamReader(DartClientCodegen.class.getResourceAsStream("/dart/dart-keywords.txt"),
StandardCharsets.UTF_8));
BufferedReader reader = new BufferedReader(new InputStreamReader(DartClientCodegen.class.getResourceAsStream("/dart/dart-keywords.txt"), Charset.forName("UTF-8")));
while (reader.ready()) {
reservedWordsList.add(reader.readLine());
}
@@ -121,17 +118,18 @@ public class DartClientCodegen extends DefaultCodegen implements CodegenConfig {
}
setReservedWordsLowerCase(reservedWordsList);
languageSpecificPrimitives = Sets.newHashSet(
languageSpecificPrimitives = new HashSet<String>(
Arrays.asList(
"String",
"bool",
"int",
"num",
"double"
"double")
);
instantiationTypes.put("array", "List");
instantiationTypes.put("map", "Map");
typeMapping = new HashMap<>();
typeMapping = new HashMap<String, String>();
typeMapping.put("Array", "List");
typeMapping.put("array", "List");
typeMapping.put("List", "List");
@@ -331,7 +329,7 @@ public class DartClientCodegen extends DefaultCodegen implements CodegenConfig {
// replace - with _ e.g. created-at => created_at
name = name.replaceAll("-", "_");
// if it's all upper case, do nothing
// if it's all uppper case, do nothing
if (name.matches("^[A-Z_]*$")) {
return name;
}
@@ -405,9 +403,9 @@ public class DartClientCodegen extends DefaultCodegen implements CodegenConfig {
@Override
public String toDefaultValue(Schema schema) {
if (ModelUtils.isMapSchema(schema)) {
return "const {}";
return "{}";
} else if (ModelUtils.isArraySchema(schema)) {
return "const []";
return "[]";
}
if (schema.getDefault() != null) {
@@ -416,7 +414,7 @@ public class DartClientCodegen extends DefaultCodegen implements CodegenConfig {
}
return schema.getDefault().toString();
} else {
return null;
return "null";
}
}
@@ -437,7 +435,7 @@ public class DartClientCodegen extends DefaultCodegen implements CodegenConfig {
@Override
public String getSchemaType(Schema p) {
String openAPIType = super.getSchemaType(p);
String type;
String type = null;
if (typeMapping.containsKey(openAPIType)) {
type = typeMapping.get(openAPIType);
if (languageSpecificPrimitives.contains(type)) {
@@ -497,16 +495,19 @@ public class DartClientCodegen extends DefaultCodegen implements CodegenConfig {
return false;
}
Object extension = cm.vendorExtensions.get("x-enum-values");
List<Map<String, Object>> values = (List<Map<String, Object>>) extension;
List<Map<String, String>> enumVars = new ArrayList<>();
List<Map<String, Object>> values =
(List<Map<String, Object>>) extension;
List<Map<String, String>> enumVars =
new ArrayList<Map<String, String>>();
for (Map<String, Object> value : values) {
Map<String, String> enumVar = new HashMap<>();
Map<String, String> enumVar = new HashMap<String, String>();
String name = camelize((String) value.get("identifier"), true);
if (isReservedWord(name)) {
name = escapeReservedWord(name);
}
enumVar.put("name", name);
enumVar.put("value", toEnumValue(value.get("numericValue").toString(), cm.dataType));
enumVar.put("value", toEnumValue(
value.get("numericValue").toString(), cm.dataType));
if (value.containsKey("description")) {
enumVar.put("description", value.get("description").toString());
}
@@ -610,12 +611,13 @@ public class DartClientCodegen extends DefaultCodegen implements CodegenConfig {
}
// 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(
Set<String> supportedFileType = new HashSet<String>(
Arrays.asList(
"supporting-mustache",
"model-test",
"model",
"api-test",
"api");
"api"));
if (!supportedFileType.contains(fileType)) {
return;
}
@@ -630,7 +632,7 @@ public class DartClientCodegen extends DefaultCodegen implements CodegenConfig {
if (exitValue != 0) {
LOGGER.error("Error running the command ({}). Exit code: {}", command, exitValue);
} else {
LOGGER.info("Successfully executed: {}", command);
LOGGER.info("Successfully executed: " + command);
}
} catch (Exception e) {
LOGGER.error("Error running the command ({}). Exception: {}", command, e.getMessage());

View File

@@ -130,21 +130,13 @@ public class DartDioClientCodegen extends DartClientCodegen {
}
@Override
public String toDefaultValue(Schema schema) {
if (ModelUtils.isMapSchema(schema)) {
public String toDefaultValue(Schema p) {
if (ModelUtils.isMapSchema(p)) {
return "const {}";
} else if (ModelUtils.isArraySchema(schema)) {
} else if (ModelUtils.isArraySchema(p)) {
return "const []";
}
if (schema.getDefault() != null) {
if (ModelUtils.isStringSchema(schema)) {
return "\"" + schema.getDefault().toString().replaceAll("\"", "\\\"") + "\"";
}
return schema.getDefault().toString();
} else {
return "null";
}
return super.toDefaultValue(p);
}
@Override

View File

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

View File

@@ -137,32 +137,44 @@ public class GoClientCodegen extends AbstractGoCodegen {
if (additionalProperties.containsKey(WITH_GO_CODEGEN_COMMENT)) {
setWithGoCodegenComment(Boolean.parseBoolean(additionalProperties.get(WITH_GO_CODEGEN_COMMENT).toString()));
additionalProperties.put(WITH_GO_CODEGEN_COMMENT, withGoCodegenComment);
if (withGoCodegenComment) {
additionalProperties.put(WITH_GO_CODEGEN_COMMENT, "true");
}
}
if (additionalProperties.containsKey(WITH_AWSV4_SIGNATURE)) {
setWithAWSV4Signature(Boolean.parseBoolean(additionalProperties.get(WITH_AWSV4_SIGNATURE).toString()));
additionalProperties.put(WITH_AWSV4_SIGNATURE, withAWSV4Signature);
if (withAWSV4Signature) {
additionalProperties.put(WITH_AWSV4_SIGNATURE, "true");
}
}
if (additionalProperties.containsKey(WITH_XML)) {
setWithXml(Boolean.parseBoolean(additionalProperties.get(WITH_XML).toString()));
additionalProperties.put(WITH_XML, withXml);
if (withXml) {
additionalProperties.put(WITH_XML, "true");
}
}
if (additionalProperties.containsKey(CodegenConstants.ENUM_CLASS_PREFIX)) {
setEnumClassPrefix(Boolean.parseBoolean(additionalProperties.get(CodegenConstants.ENUM_CLASS_PREFIX).toString()));
additionalProperties.put(CodegenConstants.ENUM_CLASS_PREFIX, enumClassPrefix);
if (enumClassPrefix) {
additionalProperties.put(CodegenConstants.ENUM_CLASS_PREFIX, "true");
}
}
if (additionalProperties.containsKey(CodegenConstants.IS_GO_SUBMODULE)) {
setIsGoSubmodule(Boolean.parseBoolean(additionalProperties.get(CodegenConstants.IS_GO_SUBMODULE).toString()));
additionalProperties.put(CodegenConstants.IS_GO_SUBMODULE, isGoSubmodule);
if (isGoSubmodule) {
additionalProperties.put(CodegenConstants.IS_GO_SUBMODULE, "true");
}
}
if (additionalProperties.containsKey(STRUCT_PREFIX)) {
setStructPrefix(Boolean.parseBoolean(additionalProperties.get(STRUCT_PREFIX).toString()));
additionalProperties.put(STRUCT_PREFIX, structPrefix);
if (structPrefix) {
additionalProperties.put(STRUCT_PREFIX, "true");
}
}
}

View File

@@ -242,13 +242,6 @@ public class GoClientExperimentalCodegen extends GoClientCodegen {
if (model.anyOf != null && !model.anyOf.isEmpty()) {
imports.add(createMapping("import", "fmt"));
}
// additionalProperties: true and parent
if (model.isAdditionalPropertiesTrue && model.parent != null && Boolean.FALSE.equals(model.isMapModel)) {
imports.add(createMapping("import", "reflect"));
imports.add(createMapping("import", "strings"));
}
}
}
return objs;

View File

@@ -17,7 +17,12 @@
package org.openapitools.codegen.languages;
import org.openapitools.codegen.*;
import org.openapitools.codegen.CliOption;
import org.openapitools.codegen.CodegenConstants;
import org.openapitools.codegen.CodegenOperation;
import org.openapitools.codegen.CodegenParameter;
import org.openapitools.codegen.CodegenType;
import org.openapitools.codegen.SupportingFile;
import org.openapitools.codegen.meta.features.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -78,8 +83,6 @@ public class GoServerCodegen extends AbstractGoCodegen {
optFeatureCORS.defaultValue(corsFeatureEnabled.toString());
cliOptions.add(optFeatureCORS);
cliOptions.add(CliOption.newBoolean(CodegenConstants.ENUM_CLASS_PREFIX, CodegenConstants.ENUM_CLASS_PREFIX_DESC));
/*
* Models. You can write model files using the modelTemplateFiles map.
* if you want to create one template for file, you can do so here.
@@ -167,7 +170,9 @@ public class GoServerCodegen extends AbstractGoCodegen {
try {
this.setServerPort(Integer.parseInt(additionalProperties.get("serverPort").toString()));
additionalProperties.put("serverPort", serverPort);
} catch (NumberFormatException e) {
}
catch (NumberFormatException e)
{
LOGGER.warn("serverPort is not a valid integer... defaulting to {}", serverPort);
additionalProperties.put("serverPort", serverPort);
}
@@ -180,13 +185,6 @@ public class GoServerCodegen extends AbstractGoCodegen {
additionalProperties.put("featureCORS", corsFeatureEnabled);
}
if (additionalProperties.containsKey(CodegenConstants.ENUM_CLASS_PREFIX)) {
setEnumClassPrefix(Boolean.parseBoolean(additionalProperties.get(CodegenConstants.ENUM_CLASS_PREFIX).toString()));
if (enumClassPrefix) {
additionalProperties.put(CodegenConstants.ENUM_CLASS_PREFIX, true);
}
}
modelPackage = packageName;
apiPackage = packageName;

View File

@@ -1400,7 +1400,7 @@ public class JavaCXFExtServerCodegen extends JavaCXFServerCodegen implements CXF
@Override
public String toDefaultValue(Schema p) {
if (ModelUtils.isGenerateAliasAsModel(p) && StringUtils.isNotEmpty(p.get$ref())) {
if (ModelUtils.isGenerateAliasAsModel() && StringUtils.isNotEmpty(p.get$ref())) {
Schema<?> ref = ModelUtils.getReferencedSchema(this.openAPI, p);
if (ModelUtils.isArraySchema(ref) || ModelUtils.isMapSchema(ref)) {
String typeDeclaration = getTypeDeclaration(p);

View File

@@ -60,7 +60,6 @@ public class JavaClientCodegen extends AbstractJavaCodegen
public static final String USE_RUNTIME_EXCEPTION = "useRuntimeException";
public static final String USE_REFLECTION_EQUALS_HASHCODE = "useReflectionEqualsHashCode";
public static final String CASE_INSENSITIVE_RESPONSE_HEADERS = "caseInsensitiveResponseHeaders";
public static final String USE_ABSTRACTION_FOR_FILES = "useAbstractionForFiles";
public static final String PLAY_24 = "play24";
public static final String PLAY_25 = "play25";
@@ -100,7 +99,6 @@ public class JavaClientCodegen extends AbstractJavaCodegen
protected boolean useRuntimeException = false;
protected boolean useReflectionEqualsHashCode = false;
protected boolean caseInsensitiveResponseHeaders = false;
protected boolean useAbstractionForFiles = false;
protected String authFolder;
protected String serializationLibrary = null;
@@ -142,11 +140,10 @@ public class JavaClientCodegen extends AbstractJavaCodegen
cliOptions.add(CliOption.newBoolean(ASYNC_NATIVE, "If true, async handlers will be used, instead of the sync version"));
cliOptions.add(CliOption.newBoolean(USE_REFLECTION_EQUALS_HASHCODE, "Use org.apache.commons.lang3.builder for equals and hashCode in the models. WARNING: This will fail under a security manager, unless the appropriate permissions are set up correctly and also there's potential performance impact."));
cliOptions.add(CliOption.newBoolean(CASE_INSENSITIVE_RESPONSE_HEADERS, "Make API response's headers case-insensitive. Available on " + OKHTTP_GSON + ", " + JERSEY2 + " libraries"));
cliOptions.add(CliOption.newBoolean(USE_ABSTRACTION_FOR_FILES, "Use alternative types instead of java.io.File to allow passing bytes without a file on disk. Available on " + RESTTEMPLATE + " library"));
supportedLibraries.put(JERSEY1, "HTTP client: Jersey client 1.19.x. JSON processing: Jackson 2.9.x. Enable Java6 support using '-DsupportJava6=true'. Enable gzip request encoding using '-DuseGzipFeature=true'. IMPORTANT NOTE: jersey 1.x is no longer actively maintained so please upgrade to 'jersey2' or other HTTP libaries instead.");
supportedLibraries.put(JERSEY2, "HTTP client: Jersey client 2.25.1. JSON processing: Jackson 2.9.x");
supportedLibraries.put(FEIGN, "HTTP client: OpenFeign 10.x. JSON processing: Jackson 2.9.x.");
supportedLibraries.put(FEIGN, "HTTP client: OpenFeign 11.x. JSON processing: Jackson 2.9.x.");
supportedLibraries.put(OKHTTP_GSON, "[DEFAULT] HTTP client: OkHttp 3.x. JSON processing: Gson 2.8.x. Enable Parcelable models on Android using '-DparcelableModel=true'. Enable gzip request encoding using '-DuseGzipFeature=true'.");
supportedLibraries.put(RETROFIT_2, "HTTP client: OkHttp 3.x. JSON processing: Gson 2.x (Retrofit 2.3.0). Enable the RxJava adapter using '-DuseRxJava[2/3]=true'. (RxJava 1.x or 2.x or 3.x)");
supportedLibraries.put(RESTTEMPLATE, "HTTP client: Spring RestTemplate 4.x. JSON processing: Jackson 2.9.x");
@@ -288,10 +285,6 @@ public class JavaClientCodegen extends AbstractJavaCodegen
this.setUseReflectionEqualsHashCode(convertPropertyToBooleanAndWriteBack(CASE_INSENSITIVE_RESPONSE_HEADERS));
}
if (additionalProperties.containsKey(USE_ABSTRACTION_FOR_FILES)) {
this.setUseAbstractionForFiles(convertPropertyToBooleanAndWriteBack(USE_ABSTRACTION_FOR_FILES));
}
final String invokerFolder = (sourceFolder + '/' + invokerPackage).replace(".", "/");
final String apiFolder = (sourceFolder + '/' + apiPackage).replace(".", "/");
authFolder = (sourceFolder + '/' + invokerPackage + ".auth").replace(".", "/");
@@ -399,7 +392,9 @@ public class JavaClientCodegen extends AbstractJavaCodegen
} else if (NATIVE.equals(getLibrary())) {
setJava8Mode(true);
additionalProperties.put("java8", "true");
if (!asyncNative) {
supportingFiles.add(new SupportingFile("ApiResponse.mustache", invokerFolder, "ApiResponse.java"));
}
forceSerializationLibrary(SERIALIZATION_LIBRARY_JACKSON);
} else if (RESTEASY.equals(getLibrary())) {
supportingFiles.add(new SupportingFile("JSON.mustache", invokerFolder, "JSON.java"));
@@ -687,7 +682,6 @@ public class JavaClientCodegen extends AbstractJavaCodegen
model.imports.add("JsonProperty");
model.imports.add("JsonValue");
model.imports.add("JsonInclude");
model.imports.add("JsonTypeName");
}
if (additionalProperties.containsKey(SERIALIZATION_LIBRARY_GSON)) {
model.imports.add("SerializedName");
@@ -871,10 +865,6 @@ public class JavaClientCodegen extends AbstractJavaCodegen
this.caseInsensitiveResponseHeaders = caseInsensitiveResponseHeaders;
}
public void setUseAbstractionForFiles(boolean useAbstractionForFiles) {
this.useAbstractionForFiles = useAbstractionForFiles;
}
/**
* Serialization library.
*

View File

@@ -51,7 +51,6 @@ public class KotlinClientCodegen extends AbstractKotlinCodegen {
public static final String USE_RX_JAVA = "useRxJava";
public static final String USE_RX_JAVA2 = "useRxJava2";
public static final String USE_RX_JAVA3 = "useRxJava3";
public static final String USE_COROUTINES = "useCoroutines";
public static final String DO_NOT_USE_RX_AND_COROUTINES = "doNotUseRxAndCoroutines";
@@ -66,7 +65,6 @@ public class KotlinClientCodegen extends AbstractKotlinCodegen {
protected String collectionType = CollectionType.LIST.value;
protected boolean useRxJava = false;
protected boolean useRxJava2 = false;
protected boolean useRxJava3 = false;
protected boolean useCoroutines = false;
// backwards compatibility for openapi configs that specify neither rx1 nor rx2
// (mustache does not allow for boolean operators so we need this extra field)
@@ -200,7 +198,6 @@ public class KotlinClientCodegen extends AbstractKotlinCodegen {
cliOptions.add(CliOption.newBoolean(USE_RX_JAVA, "Whether to use the RxJava adapter with the retrofit2 library."));
cliOptions.add(CliOption.newBoolean(USE_RX_JAVA2, "Whether to use the RxJava2 adapter with the retrofit2 library."));
cliOptions.add(CliOption.newBoolean(USE_RX_JAVA3, "Whether to use the RxJava3 adapter with the retrofit2 library."));
cliOptions.add(CliOption.newBoolean(USE_COROUTINES, "Whether to use the Coroutines adapter with the retrofit2 library."));
}
@@ -219,7 +216,6 @@ public class KotlinClientCodegen extends AbstractKotlinCodegen {
public void setUseRxJava(boolean useRxJava) {
if (useRxJava) {
this.useRxJava2 = false;
this.useRxJava3 = false;
this.doNotUseRxAndCoroutines = false;
this.useCoroutines = false;
}
@@ -229,28 +225,16 @@ public class KotlinClientCodegen extends AbstractKotlinCodegen {
public void setUseRxJava2(boolean useRxJava2) {
if (useRxJava2) {
this.useRxJava = false;
this.useRxJava3 = false;
this.doNotUseRxAndCoroutines = false;
this.useCoroutines = false;
}
this.useRxJava2 = useRxJava2;
}
public void setUseRxJava3(boolean useRxJava3) {
if (useRxJava3) {
this.useRxJava = false;
this.useRxJava2 = false;
this.doNotUseRxAndCoroutines = false;
this.useCoroutines = false;
}
this.useRxJava3 = useRxJava3;
}
public void setDoNotUseRxAndCoroutines(boolean doNotUseRxAndCoroutines) {
if (doNotUseRxAndCoroutines) {
this.useRxJava = false;
this.useRxJava2 = false;
this.useRxJava3 = false;
this.useCoroutines = false;
}
this.doNotUseRxAndCoroutines = doNotUseRxAndCoroutines;
@@ -260,7 +244,6 @@ public class KotlinClientCodegen extends AbstractKotlinCodegen {
if (useCoroutines) {
this.useRxJava = false;
this.useRxJava2 = false;
this.useRxJava3 = false;
this.doNotUseRxAndCoroutines = false;
}
this.useCoroutines = useCoroutines;
@@ -290,7 +273,6 @@ public class KotlinClientCodegen extends AbstractKotlinCodegen {
boolean hasRx = additionalProperties.containsKey(USE_RX_JAVA);
boolean hasRx2 = additionalProperties.containsKey(USE_RX_JAVA2);
boolean hasRx3 = additionalProperties.containsKey(USE_RX_JAVA3);
boolean hasCoroutines = additionalProperties.containsKey(USE_COROUTINES);
int optionCount = 0;
if (hasRx) {
@@ -299,9 +281,6 @@ public class KotlinClientCodegen extends AbstractKotlinCodegen {
if (hasRx2) {
optionCount++;
}
if (hasRx3) {
optionCount++;
}
if (hasCoroutines) {
optionCount++;
}
@@ -309,18 +288,16 @@ public class KotlinClientCodegen extends AbstractKotlinCodegen {
// RxJava & Coroutines
if (hasConflict) {
LOGGER.warn("You specified RxJava versions 1 and 2 and 3 or Coroutines together, please choose one of them.");
LOGGER.warn("You specified both RxJava versions 1 and 2 or Coroutines together, please choose one them.");
} else if (hasRx) {
this.setUseRxJava(Boolean.valueOf(additionalProperties.get(USE_RX_JAVA).toString()));
} else if (hasRx2) {
this.setUseRxJava2(Boolean.valueOf(additionalProperties.get(USE_RX_JAVA2).toString()));
} else if (hasRx3) {
this.setUseRxJava3(Boolean.valueOf(additionalProperties.get(USE_RX_JAVA3).toString()));
} else if (hasCoroutines) {
this.setUseCoroutines(Boolean.valueOf(additionalProperties.get(USE_COROUTINES).toString()));
}
if (!hasRx && !hasRx2 && !hasRx3 && !hasCoroutines) {
if (!hasRx && !hasRx2 && !hasCoroutines) {
setDoNotUseRxAndCoroutines(true);
additionalProperties.put(DO_NOT_USE_RX_AND_COROUTINES, true);
}
@@ -627,13 +604,6 @@ public class KotlinClientCodegen extends AbstractKotlinCodegen {
}
}
// import okhttp3.MultipartBody if any parameter is a file
for (CodegenParameter param : operation.allParams) {
if (Boolean.TRUE.equals(param.isFile)) {
operations.put("x-kotlin-multipart-import", true);
}
}
if (usesRetrofit2Library() && StringUtils.isNotEmpty(operation.path) && operation.path.startsWith("/")) {
operation.path = operation.path.substring(1);
}

View File

@@ -1,18 +1,21 @@
package org.openapitools.codegen.languages;
import org.openapitools.codegen.CodegenConfig;
import org.openapitools.codegen.CodegenType;
import org.openapitools.codegen.DefaultCodegen;
import org.openapitools.codegen.SupportingFile;
import org.openapitools.codegen.*;
import io.swagger.models.properties.ArrayProperty;
import io.swagger.models.properties.MapProperty;
import io.swagger.models.properties.Property;
import io.swagger.models.parameters.Parameter;
import java.io.File;
import java.util.*;
import org.apache.commons.lang3.StringUtils;
import org.openapitools.codegen.meta.GeneratorMetadata;
import org.openapitools.codegen.meta.Stability;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import static org.openapitools.codegen.utils.StringUtils.escape;
public class MarkdownDocumentationCodegen extends DefaultCodegen implements CodegenConfig {
public static final String PROJECT_NAME = "projectName";
@@ -46,37 +49,4 @@ public class MarkdownDocumentationCodegen extends DefaultCodegen implements Code
supportingFiles.add(new SupportingFile("README.mustache", "", "README.md"));
// TODO: Fill this out.
}
@Override
protected void initalizeSpecialCharacterMapping() {
// escape only those symbols that can mess up markdown
specialCharReplacements.put("\\", "\\\\");
specialCharReplacements.put("/", "\\/");
specialCharReplacements.put("`", "\\`");
specialCharReplacements.put("*", "\\*");
specialCharReplacements.put("_", "\\_");
specialCharReplacements.put("[", "\\[");
specialCharReplacements.put("]", "\\]");
// todo Current markdown api and model mustache templates display properties and parameters in tables. Pipe
// symbol in a table can be commonly escaped with a backslash (e.g. GFM supports this). However, in some cases
// it may be necessary to choose a different approach.
specialCharReplacements.put("|", "\\|");
}
/**
* Works identically to {@link DefaultCodegen#toParamName(String)} but doesn't camelize.
*
* @param name Codegen property object
* @return the sanitized parameter name
*/
@Override
public String toParamName(String name) {
if (reservedWords.contains(name)) {
return escapeReservedWord(name);
} else if (((CharSequence) name).chars().anyMatch(character -> specialCharReplacements.keySet().contains("" + ((char) character)))) {
return escape(name, specialCharReplacements, null, null);
}
return name;
}
}

View File

@@ -105,18 +105,6 @@ public class PhpLumenServerCodegen extends AbstractPhpCodegen {
* are available in models, apis, and supporting files
*/
additionalProperties.put("apiVersion", apiVersion);
}
@Override
public void processOpts() {
super.processOpts();
// reset supporting files defined in AbstractPhpCodegen
supportingFiles.clear();
// AbstractPhpCodegen generates .gitignore in output folder
// current build needs .gitignore in a "lib" folder which is srcBasePath
supportingFiles.add(new SupportingFile("gitignore", srcBasePath, ".gitignore"));
/*
* Supporting Files. You can write single files for the generator with the
@@ -124,11 +112,7 @@ public class PhpLumenServerCodegen extends AbstractPhpCodegen {
* it will be processed by the template engine. Otherwise, it will be copied
*/
supportingFiles.add(new SupportingFile(".env.example", srcBasePath, ".env.example"));
supportingFiles.add(new SupportingFile("storage_logs_gitignore", srcBasePath + File.separator + "storage" + File.separator + "logs", ".gitignore"));
supportingFiles.add(new SupportingFile("storage_logs_gitignore", srcBasePath + File.separator + "storage" + File.separator + "app", ".gitignore"));
supportingFiles.add(new SupportingFile("storage_logs_gitignore", srcBasePath + File.separator + "storage" + File.separator + "framework" + File.separator + "views", ".gitignore"));
supportingFiles.add(new SupportingFile("storage_framework_cache_gitignore", srcBasePath + File.separator + "storage" + File.separator + "framework" + File.separator + "cache", ".gitignore"));
supportingFiles.add(new SupportingFile("storage_logs_gitignore", srcBasePath + File.separator + "storage" + File.separator + "framework" + File.separator + "cache" + File.separator + "data", ".gitignore"));
supportingFiles.add(new SupportingFile("storage_logs_.gitignore", srcBasePath + File.separator + "storage" + File.separator + "logs", ".gitignore"));
supportingFiles.add(new SupportingFile("artisan", srcBasePath, "artisan"));
supportingFiles.add(new SupportingFile("composer.mustache", srcBasePath, "composer.json"));
supportingFiles.add(new SupportingFile("readme.md", srcBasePath, "readme.md"));
@@ -158,9 +142,6 @@ public class PhpLumenServerCodegen extends AbstractPhpCodegen {
supportingFiles.add(new SupportingFile("routes.mustache", srcBasePath + File.separator + "routes", "web.php"));
supportingFiles.add(new SupportingFile("ExampleTest.php", srcBasePath + File.separator + "tests", "ExampleTest.php"));
supportingFiles.add(new SupportingFile("TestCase.php", srcBasePath + File.separator + "tests", "TestCase.php"));
supportingFiles.add(new SupportingFile("editorconfig", srcBasePath, ".editorconfig"));
supportingFiles.add(new SupportingFile("styleci", srcBasePath, ".styleci.yml"));
supportingFiles.add(new SupportingFile("phpunit.xml", srcBasePath, "phpunit.xml"));
}
// override with any special post-processing

View File

@@ -203,16 +203,4 @@ public class PlantumlDocumentationCodegen extends DefaultCodegen implements Code
return value;
}
@Override
public String escapeQuotationMark(String input) {
// to surpress the warning message
return input;
}
@Override
public String escapeUnsafeCharacters(String input) {
// to surpress the warning message
return input;
}
}

View File

@@ -28,6 +28,7 @@ import org.openapitools.codegen.meta.Stability;
import org.openapitools.codegen.meta.features.DocumentationFeature;
import org.openapitools.codegen.meta.features.SecurityFeature;
import org.openapitools.codegen.meta.features.WireFormatFeature;
import org.openapitools.codegen.utils.ProcessUtils;
import org.openapitools.codegen.utils.ModelUtils;
import org.apache.commons.lang3.StringUtils;
@@ -215,12 +216,13 @@ public class ProtobufSchemaCodegen extends DefaultCodegen implements CodegenConf
public Map<String, Object> postProcessModels(Map<String, Object> objs) {
objs = postProcessModelsEnum(objs);
List<Object> models = (List<Object>) objs.get("models");
// add x-index to properties
ProcessUtils.addIndexToProperties(models, 1);
for (Object _mo : models) {
Map<String, Object> mo = (Map<String, Object>) _mo;
CodegenModel cm = (CodegenModel) mo.get("model");
int index = 1;
for (CodegenProperty var : cm.vars) {
// add x-protobuf-type: repeated if it's an array
if (Boolean.TRUE.equals(var.isListContainer)) {
@@ -245,10 +247,6 @@ public class ProtobufSchemaCodegen extends DefaultCodegen implements CodegenConf
enumIndex++;
}
}
// Add x-protobuf-index, unless already specified
var.vendorExtensions.putIfAbsent("x-protobuf-index", index);
index++;
}
}
return objs;
@@ -424,7 +422,7 @@ public class ProtobufSchemaCodegen extends DefaultCodegen implements CodegenConf
}
}
p.vendorExtensions.putIfAbsent("x-protobuf-index", index);
p.vendorExtensions.put("x-index", index);
index++;
}

View File

@@ -43,8 +43,8 @@ import java.util.*;
import static org.openapitools.codegen.utils.StringUtils.camelize;
import static org.openapitools.codegen.utils.StringUtils.underscore;
public abstract class AbstractPythonConnexionServerCodegen extends DefaultCodegen implements CodegenConfig {
private static final Logger LOGGER = LoggerFactory.getLogger(AbstractPythonConnexionServerCodegen.class);
public class PythonAbstractConnexionServerCodegen extends DefaultCodegen implements CodegenConfig {
private static final Logger LOGGER = LoggerFactory.getLogger(PythonAbstractConnexionServerCodegen.class);
public static final String CONTROLLER_PACKAGE = "controllerPackage";
public static final String DEFAULT_CONTROLLER = "defaultController";
@@ -64,7 +64,7 @@ public abstract class AbstractPythonConnexionServerCodegen extends DefaultCodege
protected boolean useNose = Boolean.FALSE;
protected String pythonSrcRoot;
public AbstractPythonConnexionServerCodegen(String templateDirectory, boolean fixBodyNameValue) {
public PythonAbstractConnexionServerCodegen(String templateDirectory, boolean fixBodyNameValue) {
super();
modifyFeatureSet(features -> features.includeDocumentationFeatures(DocumentationFeature.Readme));
@@ -248,7 +248,7 @@ public abstract class AbstractPythonConnexionServerCodegen extends DefaultCodege
pySrcRoot = val.replaceAll("[/\\\\]+$", "");
}
if (pySrcRoot.isEmpty() || ".".equals(pySrcRoot)) {
if (pySrcRoot.isEmpty() || pySrcRoot == ".") {
this.pythonSrcRoot = "";
} else {
this.pythonSrcRoot = pySrcRoot + File.separator;

View File

@@ -22,7 +22,7 @@ import org.slf4j.LoggerFactory;
import java.util.EnumSet;
public class PythonAiohttpConnexionServerCodegen extends AbstractPythonConnexionServerCodegen {
public class PythonAiohttpConnexionServerCodegen extends PythonAbstractConnexionServerCodegen {
private static final Logger LOGGER = LoggerFactory.getLogger(PythonAiohttpConnexionServerCodegen.class);
public PythonAiohttpConnexionServerCodegen() {

View File

@@ -24,7 +24,7 @@ import org.slf4j.LoggerFactory;
import java.io.File;
import java.util.EnumSet;
public class PythonBluePlanetServerCodegen extends AbstractPythonConnexionServerCodegen {
public class PythonBluePlanetServerCodegen extends PythonAbstractConnexionServerCodegen {
private static final Logger LOGGER = LoggerFactory.getLogger(PythonBluePlanetServerCodegen.class);
protected String modelDocPath = "";

View File

@@ -140,20 +140,6 @@ public class PythonClientExperimentalCodegen extends PythonClientCodegen {
supportingFiles.remove(new SupportingFile("__init__model.mustache", packagePath() + File.separatorChar + "models", "__init__.py"));
supportingFiles.add(new SupportingFile("python-experimental/__init__model.mustache", packagePath() + File.separatorChar + "model", "__init__.py"));
supportingFiles.remove(new SupportingFile("configuration.mustache", packagePath(), "configuration.py"));
supportingFiles.add(new SupportingFile("python-experimental/configuration.mustache", packagePath(), "configuration.py"));
supportingFiles.remove(new SupportingFile("__init__api.mustache", packagePath() + File.separatorChar + "api", "__init__.py"));
supportingFiles.add(new SupportingFile("python-experimental/__init__api.mustache", packagePath() + File.separatorChar + "api", "__init__.py"));
supportingFiles.remove(new SupportingFile("exceptions.mustache", packagePath(), "exceptions.py"));
supportingFiles.add(new SupportingFile("python-experimental/exceptions.mustache", packagePath(), "exceptions.py"));
if ("urllib3".equals(getLibrary())) {
supportingFiles.remove(new SupportingFile("rest.mustache", packagePath(), "rest.py"));
supportingFiles.add(new SupportingFile("python-experimental/rest.mustache", packagePath(), "rest.py"));
}
supportingFiles.remove(new SupportingFile("__init__package.mustache", packagePath(), "__init__.py"));
supportingFiles.add(new SupportingFile("python-experimental/__init__package.mustache", packagePath(), "__init__.py"));
@@ -190,12 +176,6 @@ public class PythonClientExperimentalCodegen extends PythonClientCodegen {
supportingFiles.add(new SupportingFile(readmeTemplate, "", readmePath));
if (!generateSourceCodeOnly) {
supportingFiles.remove(new SupportingFile("travis.mustache", "", ".travis.yml"));
supportingFiles.add(new SupportingFile("python-experimental/travis.mustache", "", ".travis.yml"));
supportingFiles.remove(new SupportingFile("gitlab-ci.mustache", "", ".gitlab-ci.yml"));
supportingFiles.add(new SupportingFile("python-experimental/gitlab-ci.mustache", "", ".gitlab-ci.yml"));
supportingFiles.remove(new SupportingFile("tox.mustache", "", "tox.ini"));
supportingFiles.add(new SupportingFile("python-experimental/tox.mustache", "", "tox.ini"));
supportingFiles.remove(new SupportingFile("setup.mustache", "", "setup.py"));
supportingFiles.add(new SupportingFile("python-experimental/setup.mustache", "", "setup.py"));
supportingFiles.remove(new SupportingFile("requirements.mustache", "", "requirements.txt"));
@@ -329,72 +309,133 @@ public class PythonClientExperimentalCodegen extends PythonClientCodegen {
@Override
public String toModelImport(String name) {
// name looks like Cat
return "from " + modelPackage() + "." + toModelFilename(name) + " import "+ name;
// name looks like cat.Cat
String moduleName = name.split("\\.")[0];
// https://exceptionshub.com/circular-or-cyclic-imports-in-python.html
return "from " + modelPackage() + " import "+ moduleName;
}
private String robustImport(String name) {
// name looks like cat.Cat
String moduleName = name.split("\\.")[0];
// https://exceptionshub.com/circular-or-cyclic-imports-in-python.html
String modelImport = "try:\n from " + modelPackage() +
" import " + moduleName+ "\nexcept ImportError:\n " +
moduleName + " = sys.modules[\n '" + modelPackage() + "." + moduleName + "']";
return modelImport;
}
private String getPythonClassName(String name) {
// name looks like cat.Cat or Cat
String[] pieces = name.split("\\.");
if (pieces.length == 1) {
return pieces[0];
}
return pieces[1];
}
private void fixOperationImports(Set<String> imports) {
if (imports.size() == 0) {
return;
}
String[] modelNames = imports.toArray(new String[0]);
imports.clear();
// loops through imports and converts them all from 'module.Class' to 'from models.module import module'
for (String modelName : modelNames) {
// if a modelName lacks the module (Pet) then we convert it to pet.Pet
if (modelName.indexOf(".") == -1) {
modelName = toModelName(modelName);
}
imports.add(toModelImport(modelName));
}
}
@Override
@SuppressWarnings("static-method")
public Map<String, Object> postProcessOperationsWithModels(Map<String, Object> objs, List<Object> allModels) {
// fix the imports that each model has, add the module reference to the model
// loops through imports and converts them all
// from 'Pet' to 'from petstore_api.model.pet import Pet'
HashMap<String, Object> val = (HashMap<String, Object>)objs.get("operations");
ArrayList<CodegenOperation> operations = (ArrayList<CodegenOperation>) val.get("operation");
ArrayList<HashMap<String, String>> imports = (ArrayList<HashMap<String, String>>)objs.get("imports");
imports.clear();
for (CodegenOperation operation : operations) {
if (operation.imports.size() == 0) {
continue;
fixOperationImports(operation.imports);
for (String thisImport : operation.imports) {
HashMap<String, String> higherImport = new HashMap<String, String>();
higherImport.put("import", thisImport);
if (!imports.contains(higherImport)) {
imports.add(higherImport);
}
String[] modelNames = operation.imports.toArray(new String[0]);
operation.imports.clear();
for (String modelName : modelNames) {
operation.imports.add(toModelImport(modelName));
}
}
return objs;
}
private void fixModelImports(Set<String> imports) {
// loops through imports and converts them all from 'module.Class' to 'import models.module as module'
if (imports.size() == 0) {
return;
}
String[] modelNames = imports.toArray(new String[0]);
imports.clear();
for (String modelName : modelNames) {
imports.add(robustImport(modelName));
}
}
/**
* Override with special post-processing for all models.
*/
@SuppressWarnings({"static-method", "unchecked"})
public Map<String, Object> postProcessAllModels(Map<String, Object> objs) {
super.postProcessAllModels(objs);
// loop through all models and delete ones where type!=object and the model has no validations and enums
// we will remove them because they are not needed
Map<String, Schema> modelSchemasToRemove = new HashMap<String, Schema>();
for (Map.Entry<String, Object> entry : objs.entrySet()) {
Map<String, Object> inner = (Map<String, Object>) entry.getValue();
List<Map<String, Object>> models = (List<Map<String, Object>>) inner.get("models");
for (Map<String, Object> mo : models) {
CodegenModel cm = (CodegenModel) mo.get("model");
for (Object objModel: objs.values()) {
HashMap<String, Object> hmModel = (HashMap<String, Object>) objModel;
List<Map<String, Object>> models = (List<Map<String, Object>>) hmModel.get("models");
for (Map<String, Object> model : models) {
CodegenModel cm = (CodegenModel) model.get("model");
// make sure discriminator models are included in imports
CodegenDiscriminator discriminator = cm.discriminator;
if (discriminator != null) {
Set<CodegenDiscriminator.MappedModel> mappedModels = discriminator.getMappedModels();
for (CodegenDiscriminator.MappedModel mappedModel : mappedModels) {
String otherModelName = mappedModel.getModelName();
cm.imports.add(otherModelName);
}
}
// add imports for anyOf, allOf, oneOf
ArrayList<Set<String>> composedSchemaSets = new ArrayList<Set<String>>();
composedSchemaSets.add(cm.allOf);
composedSchemaSets.add(cm.anyOf);
composedSchemaSets.add(cm.oneOf);
for (Set<String> importSet : composedSchemaSets) {
for (String otherModelName : importSet) {
if (!languageSpecificPrimitives.contains(otherModelName)) {
cm.imports.add(otherModelName);
}
}
}
// remove model if it is a primitive with no validations
if (cm.isEnum || cm.isAlias) {
Schema modelSchema = ModelUtils.getSchema(this.openAPI, cm.name);
CodegenProperty modelProperty = fromProperty("_value", modelSchema);
CodegenProperty modelProperty = fromProperty("value", modelSchema);
// import complex type from additional properties
if (cm.additionalPropertiesType != null && modelProperty.items != null && modelProperty.items.complexType != null) {
cm.imports.add(modelProperty.items.complexType);
}
// fix the imports that each model has, change them to absolute
fixModelImports(cm.imports);
if (cm.isEnum || cm.isAlias) {
if (!modelProperty.isEnum && !modelProperty.hasValidation && !cm.isArrayModel) {
// remove these models because they are aliases and do not have any enums or validations
modelSchemasToRemove.put(cm.name, modelSchema);
continue;
}
}
// fix model imports
if (cm.imports.size() == 0) {
continue;
}
String[] modelNames = cm.imports.toArray(new String[0]);
cm.imports.clear();
for (String modelName : modelNames) {
cm.imports.add(toModelImport(modelName));
String globalImportFixer = "globals()['" + modelName + "'] = " + modelName;
cm.imports.add(globalImportFixer);
}
}
}
@@ -488,7 +529,9 @@ public class PythonClientExperimentalCodegen extends PythonClientCodegen {
if (modelProp.isPrimitiveType && (modelProp.hasValidation || modelProp.isEnum)) {
String simpleDataType = result.dataType;
result.dataType = toModelName(modelName);
result.baseType = result.dataType;
result.baseType = getPythonClassName(result.dataType);
imports.remove(modelName);
imports.add(result.dataType);
// set the example value
if (modelProp.isEnum) {
String value = modelProp._enum.get(0).toString();
@@ -496,6 +539,9 @@ public class PythonClientExperimentalCodegen extends PythonClientCodegen {
} else {
result.example = result.dataType + "(" + result.example + ")";
}
} else if (!result.isPrimitiveType) {
// fix the baseType for the api docs so the .md link to the class's documentation file is correct
result.baseType = getPythonClassName(result.baseType);
}
return result;
}
@@ -524,7 +570,7 @@ public class PythonClientExperimentalCodegen extends PythonClientCodegen {
if (responseSchema != null) {
CodegenProperty cp = fromProperty("response", responseSchema);
if (cp.complexType != null) {
String modelName = cp.complexType;
String modelName = getPythonClassName(cp.complexType);
Schema modelSchema = ModelUtils.getSchema(this.openAPI, modelName);
if (modelSchema != null && !"object".equals(modelSchema.getType())) {
CodegenProperty modelProp = fromProperty("response", modelSchema);
@@ -537,16 +583,19 @@ public class PythonClientExperimentalCodegen extends PythonClientCodegen {
if (cp.isEnum == true || cp.hasValidation == true) {
// this model has validations and/or enums so we will generate it
Schema sc = ModelUtils.getSchemaFromResponse(response);
newBaseType = toModelName(ModelUtils.getSimpleRef(sc.get$ref()));
newBaseType = ModelUtils.getSimpleRef(sc.get$ref());
}
}
}
CodegenResponse result = super.fromResponse(responseCode, response);
if (newBaseType != null) {
result.dataType = newBaseType;
result.dataType = toModelName(newBaseType);
// baseType is used to set the link to the model .md documentation
result.baseType = newBaseType;
result.baseType = getPythonClassName(newBaseType);
} else if (!result.primitiveType) {
// fix the baseType for the api docs so the .md link to the class's documentation file is correct
result.baseType = getPythonClassName(result.baseType);
}
return result;
@@ -664,18 +713,28 @@ public class PythonClientExperimentalCodegen extends PythonClientCodegen {
public void postProcessModelProperty(CodegenModel model, CodegenProperty p) {
postProcessPattern(p.pattern, p.vendorExtensions);
// set property.complexType so the model docs will link to the ClassName.md
if (p.complexType == null && p.isListContainer && p.mostInnerItems.complexType != null && !languageSpecificPrimitives.contains(p.mostInnerItems.complexType)) {
if (p.complexType != null && !languageSpecificPrimitives.contains(p.complexType)) {
p.complexType = getPythonClassName(p.complexType);
} else if (p.isListContainer && p.mostInnerItems.complexType != null && !languageSpecificPrimitives.contains(p.mostInnerItems.complexType)) {
// fix ListContainers
p.complexType = p.mostInnerItems.complexType;
p.complexType = getPythonClassName(p.mostInnerItems.complexType);
}
// if a model has a property that is of type self, remove the module name from the dataType
if (p.complexType != null && p.dataType.contains(model.classname)) {
String classNameNoModule = getPythonClassName(model.classname);
p.dataType = p.dataType.replace(model.classname, classNameNoModule);
}
}
@Override
public void postProcessParameter(CodegenParameter p) {
postProcessPattern(p.pattern, p.vendorExtensions);
if (p.baseType != null && languageSpecificPrimitives.contains(p.baseType)){
// set baseType to null so the api docs will not point to a model for languageSpecificPrimitives
if (p.baseType != null && languageSpecificPrimitives.contains(p.baseType)){
p.baseType = null;
} else if (p.isListContainer && p.mostInnerItems.complexType != null && !languageSpecificPrimitives.contains(p.mostInnerItems.complexType)) {
// fix ListContainers
p.baseType = getPythonClassName(p.mostInnerItems.complexType);
}
}
@@ -730,18 +789,6 @@ public class PythonClientExperimentalCodegen extends PythonClientCodegen {
}
}
/**
* Sets the value of the 'model.parent' property in CodegenModel
* We have a custom version of this function so we can add the dataType on the ArrayModel
*/
@Override
protected void addParentContainer(CodegenModel model, String name, Schema schema) {
super.addParentContainer(model, name, schema);
List<String> referencedModelNames = new ArrayList<String>();
model.dataType = getTypeString(schema, "", "", referencedModelNames);
}
/**
* Convert OAS Model object to Codegen Model object
*
@@ -753,11 +800,9 @@ public class PythonClientExperimentalCodegen extends PythonClientCodegen {
public CodegenModel fromModel(String name, Schema schema) {
// we have a custom version of this function so we can produce
// models for components whose type != object and which have validations and enums
// this ensures that:
// - endpoint (operation) responses with validations and type!=(object or array)
// - oneOf $ref components with validations and type!=(object or array)
// when endpoints receive payloads of these models
// that they will be converted into instances of these models
// this ensures that endpoint (operation) responses with validations and enums
// will generate models, and when those endpoint responses are received in python
// the response is cast as a model, and the model will validate the response using the enums and validations
Map<String, String> propertyToModelName = new HashMap<String, String>();
Map<String, Schema> propertiesMap = schema.getProperties();
if (propertiesMap != null) {
@@ -775,7 +820,7 @@ public class PythonClientExperimentalCodegen extends PythonClientCodegen {
continue;
}
CodegenProperty modelProperty = fromProperty("_fake_name", refSchema);
if (modelProperty.isEnum == true || modelProperty.hasValidation == false) {
if (modelProperty.isEnum == false && modelProperty.hasValidation == false) {
continue;
}
String modelName = ModelUtils.getSimpleRef(ref);
@@ -783,94 +828,37 @@ public class PythonClientExperimentalCodegen extends PythonClientCodegen {
}
}
CodegenModel result = super.fromModel(name, schema);
// use this to store the model name like Cat
// we can't use result.name because that is used to lookup models in the spec
// we can't use result.classname because that stores cat.Cat
// we can't use result.classVarName because that stores the variable for making example instances
result.unescapedDescription = simpleModelName(name);
// have oneOf point to the correct model
if (ModelUtils.isComposedSchema(schema)) {
ComposedSchema cs = (ComposedSchema) schema;
Map<String, Integer> importCounts = new HashMap<String, Integer>();
List<Schema> oneOfSchemas = cs.getOneOf();
if (oneOfSchemas != null) {
for (int i = 0; i < oneOfSchemas.size(); i++) {
Schema oneOfSchema = oneOfSchemas.get(i);
String languageType = getTypeDeclaration(oneOfSchema);
String ref = oneOfSchema.get$ref();
if (ref == null) {
Integer currVal = importCounts.getOrDefault(languageType, 0);
importCounts.put(languageType, currVal+1);
continue;
}
Schema refSchema = ModelUtils.getReferencedSchema(this.openAPI, oneOfSchema);
String refType = refSchema.getType();
if (refType == null || refType.equals("object")) {
Integer currVal = importCounts.getOrDefault(languageType, 0);
importCounts.put(languageType, currVal+1);
continue;
}
CodegenProperty modelProperty = fromProperty("_oneOfSchema", refSchema);
if (modelProperty.isEnum == true) {
Integer currVal = importCounts.getOrDefault(languageType, 0);
importCounts.put(languageType, currVal+1);
continue;
}
languageType = getTypeDeclaration(refSchema);
if (modelProperty.hasValidation == false) {
Integer currVal = importCounts.getOrDefault(languageType, 0);
importCounts.put(languageType, currVal+1);
continue;
}
Integer currVal = importCounts.getOrDefault(languageType, 0);
importCounts.put(languageType, currVal);
String modelName = toModelName(ModelUtils.getSimpleRef(ref));
result.imports.add(modelName);
result.oneOf.add(modelName);
currVal = importCounts.getOrDefault(modelName, 0);
importCounts.put(modelName, currVal+1);
}
}
for (Map.Entry<String, Integer> entry : importCounts.entrySet()) {
String importName = entry.getKey();
Integer importCount = entry.getValue();
if (importCount == 0) {
result.oneOf.remove(importName);
}
}
}
// this block handles models which have the python base class ModelSimple
// which are responsible for storing validations, enums, and an unnamed value
// make non-object type models have one property so we can use it to store enums and validations
if (result.isAlias || result.isEnum || result.isArrayModel) {
Schema modelSchema = ModelUtils.getSchema(this.openAPI, result.name);
CodegenProperty modelProperty = fromProperty("_value", modelSchema);
Boolean isPythonModelSimpleModel = (result.isEnum || result.isArrayModel || result.isAlias && modelProperty.hasValidation);
if (isPythonModelSimpleModel) {
// In python, classes which inherit from our ModelSimple class store one value,
// like a str, int, list and extra data about that value like validations and enums
if (result.isEnum) {
// if there is only one allowed value then we know that it should be set, so value is optional
// -> hasRequired = false
// if there are more than one allowed value then value is positional and required so
// -> hasRequired = true
ArrayList values = (ArrayList) result.allowableValues.get("values");
if (values != null && values.size() > 1) {
result.hasRequired = true;
CodegenProperty modelProperty = fromProperty("value", modelSchema);
if (modelProperty.isEnum == true || modelProperty.hasValidation == true || result.isArrayModel) {
// these models are non-object models with enums and/or validations
// add a single property to the model so we can have a way to access validations
result.isAlias = true;
modelProperty.required = true;
List<CodegenProperty> theProperties = Arrays.asList(modelProperty);
result.setAllVars(theProperties);
result.setVars(theProperties);
result.setRequiredVars(theProperties);
// post process model properties
if (result.vars != null) {
for (CodegenProperty prop : result.vars) {
postProcessModelProperty(result, prop);
}
if (modelProperty.defaultValue != null && result.defaultValue == null) {
result.defaultValue = modelProperty.defaultValue;
}
} else {
if (result.defaultValue == null) {
result.hasRequired = true;
}
}
}
// fix all property references to ModelSimple models, make those properties non-primitive and
// set their dataType and complexType to the model name, so documentation will refer to the correct model
// set regex values, before it was only done on model.vars
// NOTE: this is done for models of type != object which are not enums and have validations
// fix all property references to non-object models, make those properties non-primitive and
// set their dataType and complexType to the model name, so documentation will refer to the correct model
ArrayList<List<CodegenProperty>> listOfLists = new ArrayList<List<CodegenProperty>>();
listOfLists.add(result.vars);
listOfLists.add(result.allVars);
@@ -888,14 +876,13 @@ public class PythonClientExperimentalCodegen extends PythonClientCodegen {
}
cp.isPrimitiveType = false;
String modelName = propertyToModelName.get(cp.name);
cp.complexType = modelName;
cp.complexType = getPythonClassName(modelName);
cp.dataType = modelName;
cp.isEnum = false;
cp.hasValidation = false;
result.imports.add(modelName);
}
}
// if a class has a property of type self, remove the self import from imports
if (result.imports.contains(result.classname)) {
result.imports.remove(result.classname);
@@ -908,60 +895,6 @@ public class PythonClientExperimentalCodegen extends PythonClientCodegen {
return result;
}
/**
* returns the OpenAPI type for the property. Use getAlias to handle $ref of primitive type
* We have a custom version of this function because for composed schemas we also want to return the model name
* In DefaultCodegen.java it returns a name built off of individual allOf/anyOf/oneOf which is not what
* python-experimental needs. Python-experimental needs the name of the composed schema
*
* @param schema property schema
* @return string presentation of the type
**/
@SuppressWarnings("static-method")
@Override
public String getSchemaType(Schema schema) {
if (schema instanceof ComposedSchema) { // composed schema
Schema unaliasSchema = ModelUtils.unaliasSchema(this.openAPI, schema, importMapping);
String ref = unaliasSchema.get$ref();
if (ref != null) {
String schemaName = ModelUtils.getSimpleRef(unaliasSchema.get$ref());
if (StringUtils.isNotEmpty(schemaName) && importMapping.containsKey(schemaName)) {
return schemaName;
}
return getAlias(schemaName);
} else {
// we may have be processing the component schema rather than a schema with a $ref
// to a component schema
// so loop through component schemas and use the found one's name if we match
Map<String, Schema> schemas = ModelUtils.getSchemas(openAPI);
for (String thisSchemaName : schemas.keySet()) {
Schema thisSchema = schemas.get(thisSchemaName);
if (!ModelUtils.isComposedSchema(thisSchema)) {
continue;
}
if (thisSchema == unaliasSchema) {
if (importMapping.containsKey(thisSchemaName)) {
return thisSchemaName;
}
return getAlias(thisSchemaName);
}
}
LOGGER.warn("Error obtaining the datatype from ref:" + unaliasSchema.get$ref() + ". Default to 'object'");
return "object";
}
}
String openAPIType = getSingleSchemaType(schema);
if (typeMapping.containsKey(openAPIType)) {
String type = typeMapping.get(openAPIType);
if (languageSpecificPrimitives.contains(type)) {
return type;
}
} else {
return toModelName(openAPIType);
}
return openAPIType;
}
/**
* Output the type declaration of the property
*
@@ -976,18 +909,6 @@ public class PythonClientExperimentalCodegen extends PythonClientCodegen {
return oasType;
}
public Boolean modelWillBeMade(Schema s) {
// only invoke this on $refed schemas
if (ModelUtils.isComposedSchema(s) || ModelUtils.isArraySchema(s) || ModelUtils.isObjectSchema(s)) {
return true;
}
CodegenProperty cp = fromProperty("_model", s);
if (cp.isEnum || cp.hasValidation) {
return true;
}
return false;
}
/**
* Return a string representation of the Python types for the specified OAS schema.
* Primitive types in the OAS specification are implemented in Python using the corresponding
@@ -1018,12 +939,12 @@ public class PythonClientExperimentalCodegen extends PythonClientCodegen {
// The input schema is a reference. If the resolved schema is
// a composed schema, convert the name to a Python class.
Schema s = ModelUtils.getReferencedSchema(this.openAPI, p);
if (modelWillBeMade(s)) {
String modelName = toModelName(ModelUtils.getSimpleRef(p.get$ref()));
if (s instanceof ComposedSchema) {
String modelName = ModelUtils.getSimpleRef(p.get$ref());
if (referencedModelNames != null) {
referencedModelNames.add(modelName);
}
return prefix + modelName + fullSuffix;
return prefix + toModelName(modelName) + fullSuffix;
}
}
if (isAnyTypeSchema(p)) {
@@ -1173,4 +1094,55 @@ public class PythonClientExperimentalCodegen extends PythonClientCodegen {
p.example = example;
}
private String simpleModelName(String name) {
// this returns a model name like Cat
String modelName = sanitizeName(name);
// remove dollar sign
modelName = modelName.replaceAll("$", "");
// model name cannot use reserved keyword, e.g. return
if (isReservedWord(modelName)) {
LOGGER.warn(modelName + " (reserved word) cannot be used as model name. Renamed to " + camelize("model_" + modelName));
modelName = "model_" + modelName; // e.g. return => ModelReturn (after camelize)
}
// model name starts with number
if (modelName.matches("^\\d.*")) {
LOGGER.warn(modelName + " (model name starts with number) cannot be used as model name. Renamed to " + camelize("model_" + modelName));
modelName = "model_" + modelName; // e.g. 200Response => Model200Response (after camelize)
}
if (!StringUtils.isEmpty(modelNamePrefix)) {
modelName = modelNamePrefix + "_" + modelName;
}
if (!StringUtils.isEmpty(modelNameSuffix)) {
modelName = modelName + "_" + modelNameSuffix;
}
// camelize the model name
// phone_number => PhoneNumber
return camelize(modelName);
}
@Override
public String toModelFilename(String name) {
// underscore the model file name
// PhoneNumber => phone_number
return underscore(dropDots(simpleModelName(name)));
}
@Override
public String toModelName(String name) {
// we have a custom version of this function so we can support circular references in python 2 and 3
return toModelFilename(name)+"."+simpleModelName(name);
}
@Override
public String toModelDocFilename(String name) {
// this is used to generate the model's .md documentation file
return simpleModelName(name);
}
}

View File

@@ -22,7 +22,7 @@ import org.slf4j.LoggerFactory;
import java.io.File;
public class PythonFlaskConnexionServerCodegen extends AbstractPythonConnexionServerCodegen {
public class PythonFlaskConnexionServerCodegen extends PythonAbstractConnexionServerCodegen {
private static final Logger LOGGER = LoggerFactory.getLogger(PythonFlaskConnexionServerCodegen.class);
public PythonFlaskConnexionServerCodegen() {

View File

@@ -34,10 +34,6 @@ import java.io.File;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.time.OffsetDateTime;
import java.time.Instant;
import java.time.temporal.ChronoField;
import java.util.concurrent.TimeUnit;
import static org.openapitools.codegen.utils.StringUtils.camelize;
@@ -624,19 +620,14 @@ public class Swift5ClientCodegen extends DefaultCodegen implements CodegenConfig
}
}
}
if (p.getDefault() != null) {
if (ModelUtils.isIntegerSchema(p) || ModelUtils.isNumberSchema(p) || ModelUtils.isBooleanSchema(p)) {
if (p.getDefault() != null) {
return p.getDefault().toString();
} else if (ModelUtils.isDateTimeSchema(p)) {
// Datetime time stamps in Swift are expressed as Seconds with Microsecond precision.
// In Java, we need to be creative to get the Timestamp in Microseconds as a long.
Instant instant = ((OffsetDateTime) p.getDefault()).toInstant();
long epochMicro = TimeUnit.SECONDS.toMicros(instant.getEpochSecond()) + ((long) instant.get(ChronoField.MICRO_OF_SECOND));
return "Date(timeIntervalSince1970: " + String.valueOf(epochMicro) + ".0 / 1_000_000)";
}
} else if (ModelUtils.isStringSchema(p)) {
if (p.getDefault() != null) {
return "\"" + escapeText((String) p.getDefault()) + "\"";
}
// TODO: Handle more cases from `ModelUtils`, such as Date
}
return null;
}

View File

@@ -61,7 +61,7 @@ public class TypeScriptAngularClientCodegen extends AbstractTypeScriptClientCode
public static final String STRING_ENUMS_DESC = "Generate string enums instead of objects for enum values.";
public static final String QUERY_PARAM_OBJECT_FORMAT = "queryParamObjectFormat";
protected String ngVersion = "10.0.0";
protected String ngVersion = "9.0.0";
protected String npmRepository = null;
private boolean useSingleRequestParameter = false;
protected String serviceSuffix = "Service";
@@ -129,7 +129,7 @@ public class TypeScriptAngularClientCodegen extends AbstractTypeScriptClientCode
@Override
public String getHelp() {
return "Generates a TypeScript Angular (6.x - 10.x) client library.";
return "Generates a TypeScript Angular (6.x - 9.x) client library.";
}
@Override
@@ -246,9 +246,7 @@ public class TypeScriptAngularClientCodegen extends AbstractTypeScriptClientCode
}
// Set the typescript version compatible to the Angular version
if (ngVersion.atLeast("10.0.0")) {
additionalProperties.put("tsVersion", ">=3.9.2 <4.0.0");
} else if (ngVersion.atLeast("9.0.0")) {
if (ngVersion.atLeast("9.0.0")) {
additionalProperties.put("tsVersion", ">=3.6.0 <3.8.0");
} else if (ngVersion.atLeast("8.0.0")) {
additionalProperties.put("tsVersion", ">=3.4.0 <3.6.0");
@@ -260,9 +258,7 @@ public class TypeScriptAngularClientCodegen extends AbstractTypeScriptClientCode
}
// Set the rxJS version compatible to the Angular version
if (ngVersion.atLeast("10.0.0")) {
additionalProperties.put("rxjsVersion", "6.6.0");
} else if (ngVersion.atLeast("9.0.0")) {
if (ngVersion.atLeast("9.0.0")) {
additionalProperties.put("rxjsVersion", "6.5.3");
} else if (ngVersion.atLeast("8.0.0")) {
additionalProperties.put("rxjsVersion", "6.5.0");
@@ -276,10 +272,7 @@ public class TypeScriptAngularClientCodegen extends AbstractTypeScriptClientCode
supportingFiles.add(new SupportingFile("ng-package.mustache", getIndexDirectory(), "ng-package.json"));
// Specific ng-packagr configuration
if (ngVersion.atLeast("10.0.0")) {
additionalProperties.put("ngPackagrVersion", "10.0.3");
additionalProperties.put("tsickleVersion", "0.39.1");
} else if (ngVersion.atLeast("9.0.0")) {
if (ngVersion.atLeast("9.0.0")) {
additionalProperties.put("ngPackagrVersion", "9.0.1");
additionalProperties.put("tsickleVersion", "0.38.0");
} else if (ngVersion.atLeast("8.0.0")) {

View File

@@ -839,10 +839,10 @@ public class TypeScriptClientCodegen extends DefaultCodegen implements CodegenCo
Schema inner;
if (ModelUtils.isArraySchema(p)) {
inner = ((ArraySchema) p).getItems();
return this.getSchemaType(p) + "<" + this.getTypeDeclaration(ModelUtils.unaliasSchema(this.openAPI, inner)) + ">";
return this.getSchemaType(p) + "<" + this.getTypeDeclaration(inner) + ">";
} else if (ModelUtils.isMapSchema(p)) {
inner = (Schema) p.getAdditionalProperties();
return "{ [key: string]: " + this.getTypeDeclaration(ModelUtils.unaliasSchema(this.openAPI, inner)) + "; }";
return "{ [key: string]: " + this.getTypeDeclaration(inner) + "; }";
} else if (ModelUtils.isFileSchema(p)) {
return "HttpFile";
} else if (ModelUtils.isBinarySchema(p)) {

View File

@@ -0,0 +1,201 @@
/*
* Copyright 2018 OpenAPI-Generator Contributors (https://openapi-generator.tech)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.openapitools.codegen.languages;
import io.swagger.v3.oas.models.media.ArraySchema;
import io.swagger.v3.oas.models.media.Schema;
import io.swagger.v3.parser.util.SchemaTypeUtil;
import org.openapitools.codegen.*;
import org.openapitools.codegen.utils.ModelUtils;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.TreeSet;
import java.util.Date;
import java.util.List;
import java.util.ArrayList;
import java.util.Locale;
import java.util.Map;
// TODO rename AbstractTypeScriptClientCodegen to AbstractTypeScriptCodegen later
public class TypeScriptServerCodegen extends AbstractTypeScriptClientCodegen {
public static final String NPM_REPOSITORY = "npmRepository";
public static final String WITH_INTERFACES = "withInterfaces";
protected String npmRepository = null;
public TypeScriptServerCodegen() {
super();
outputFolder = "generated-code/typescript-server";
embeddedTemplateDir = templateDir = "typescript-server";
this.apiPackage = "apis";
this.apiTemplateFiles.put("apis.mustache", ".ts");
this.modelPackage = "models";
this.modelTemplateFiles.put("models.mustache", ".ts");
this.cliOptions.add(new CliOption(NPM_REPOSITORY, "Use this property to set an url your private npmRepo in the package.json"));
this.cliOptions.add(new CliOption(WITH_INTERFACES, "Setting this property to true will generate interfaces next to the default class implementations.", SchemaTypeUtil.BOOLEAN_TYPE).defaultValue(Boolean.FALSE.toString()));
}
@Override
public String getName() {
return "typescript-server";
}
@Override
public String getHelp() {
return "Generates a TypeScript server stub (beta).";
}
public String getNpmRepository() {
return npmRepository;
}
public void setNpmRepository(String npmRepository) {
this.npmRepository = npmRepository;
}
@Override
public void processOpts() {
super.processOpts();
additionalProperties.put("isOriginalModelPropertyNaming", getModelPropertyNaming().equals("original"));
additionalProperties.put("modelPropertyNaming", getModelPropertyNaming());
supportingFiles.add(new SupportingFile("index.mustache", "", "index.ts"));
supportingFiles.add(new SupportingFile("runtime.mustache", "", "runtime.ts"));
supportingFiles.add(new SupportingFile("apis.index.mustache", apiPackage().replace('.', File.separatorChar), "index.ts"));
supportingFiles.add(new SupportingFile("models.index.mustache", modelPackage().replace('.', File.separatorChar), "index.ts"));
supportingFiles.add(new SupportingFile("tsconfig.mustache", "", "tsconfig.json"));
supportingFiles.add(new SupportingFile("gitignore", "", ".gitignore"));
if (additionalProperties.containsKey(NPM_NAME)) {
addNpmPackageGeneration();
}
}
@Override
public boolean isDataTypeFile(final String dataType) {
return dataType != null && dataType.equals("Blob");
}
@Override
public String getTypeDeclaration(Schema p) {
Schema inner;
if (ModelUtils.isArraySchema(p)) {
inner = ((ArraySchema) p).getItems();
return this.getSchemaType(p) + "<" + this.getTypeDeclaration(inner) + ">";
} else if (ModelUtils.isMapSchema(p)) {
inner = ModelUtils.getAdditionalProperties(p);
return "{ [key: string]: " + this.getTypeDeclaration(inner) + "; }";
} else if (ModelUtils.isFileSchema(p)) {
return "Blob";
} else if (ModelUtils.isBinarySchema(p)) {
return "Blob";
} else if (ModelUtils.isDateSchema(p)) {
return "Date";
} else if (ModelUtils.isDateTimeSchema(p)) {
return "Date";
}
return super.getTypeDeclaration(p);
}
@Override
protected void addAdditionPropertiesToCodeGenModel(CodegenModel codegenModel, Schema schema) {
codegenModel.additionalPropertiesType = getTypeDeclaration(ModelUtils.getAdditionalProperties(schema));
addImport(codegenModel, codegenModel.additionalPropertiesType);
}
@Override
public Map<String, Object> postProcessModels(Map<String, Object> objs) {
/* comment out the following as we're not sure if we need these in the TS Server generator
// process enum in models
List<Object> models = (List<Object>) postProcessModelsEnum(objs).get("models");
for (Object _mo : models) {
Map<String, Object> mo = (Map<String, Object>) _mo;
CodegenModel cm = (CodegenModel) mo.get("model");
cm.imports = new TreeSet(cm.imports);
// name enum with model name, e.g. StatusEnum => PetStatusEnum
for (CodegenProperty var : cm.vars) {
if (Boolean.TRUE.equals(var.isEnum)) {
// behaviour for enum names is specific for typescript to not use namespaces
var.datatypeWithEnum = var.datatypeWithEnum.replace(var.enumName, cm.classname + var.enumName);
}
}
if (cm.parent != null) {
for (CodegenProperty var : cm.allVars) {
if (Boolean.TRUE.equals(var.isEnum)) {
var.datatypeWithEnum = var.datatypeWithEnum
.replace(var.enumName, cm.classname + var.enumName);
}
}
}
}
*/
return objs;
}
@Override
public Map<String, Object> postProcessAllModels(Map<String, Object> objs) {
Map<String, Object> result = super.postProcessAllModels(objs);
/* comment out the following as we're not sure if we need these in the TS Server generator
for (Map.Entry<String, Object> entry : result.entrySet()) {
Map<String, Object> inner = (Map<String, Object>) entry.getValue();
List<Map<String, Object>> models = (List<Map<String, Object>>) inner.get("models");
for (Map<String, Object> model : models) {
CodegenModel codegenModel = (CodegenModel) model.get("model");
model.put("hasImports", codegenModel.imports.size() > 0);
}
}
*/
return result;
}
@Override
public String getSchemaType(Schema p) {
String openAPIType = super.getSchemaType(p);
if (isLanguagePrimitive(openAPIType)) {
return openAPIType;
}
applyLocalTypeMapping(openAPIType);
return openAPIType;
}
private String applyLocalTypeMapping(String type) {
if (typeMapping.containsKey(type)) {
type = typeMapping.get(type);
}
return type;
}
private boolean isLanguagePrimitive(String type) {
return languageSpecificPrimitives.contains(type);
}
private void addNpmPackageGeneration() {
if (additionalProperties.containsKey(NPM_REPOSITORY)) {
this.setNpmRepository(additionalProperties.get(NPM_REPOSITORY).toString());
}
// Files for building our lib
supportingFiles.add(new SupportingFile("README.mustache", "", "README.md"));
supportingFiles.add(new SupportingFile("package.mustache", "", "package.json"));
}
}

View File

@@ -88,10 +88,6 @@ public class ModelUtils {
return Boolean.parseBoolean(GlobalSettings.getProperty(generateAliasAsModelKey, "false"));
}
public static boolean isGenerateAliasAsModel(Schema schema) {
return isGenerateAliasAsModel() || (schema.getExtensions() != null && schema.getExtensions().getOrDefault("x-generate-alias-as-model", false).equals(true));
}
/**
* Searches for the model by name in the map of models and returns it
*
@@ -1041,7 +1037,7 @@ public class ModelUtils {
// top-level enum class
return schema;
} else if (isArraySchema(ref)) {
if (isGenerateAliasAsModel(ref)) {
if (isGenerateAliasAsModel()) {
return schema; // generate a model extending array
} else {
return unaliasSchema(openAPI, allSchemas.get(ModelUtils.getSimpleRef(schema.get$ref())),
@@ -1053,7 +1049,7 @@ public class ModelUtils {
if (ref.getProperties() != null && !ref.getProperties().isEmpty()) // has at least one property
return schema; // treat it as model
else {
if (isGenerateAliasAsModel(ref)) {
if (isGenerateAliasAsModel()) {
return schema; // generate a model extending map
} else {
// treat it as a typical map

View File

@@ -126,7 +126,7 @@ ext {
{{#threetenbp}}
jackson_threetenbp_version = "2.9.10"
{{/threetenbp}}
feign_version = "10.11"
feign_version = "11.0"
feign_form_version = "3.8.0"
junit_version = "4.13"
oltu_version = "1.0.1"

View File

@@ -10,9 +10,9 @@ lazy val root = (project in file(".")).
resolvers += Resolver.mavenLocal,
libraryDependencies ++= Seq(
"io.swagger" % "swagger-annotations" % "1.5.24" % "compile",
"io.github.openfeign" % "feign-core" % "10.11" % "compile",
"io.github.openfeign" % "feign-jackson" % "10.11" % "compile",
"io.github.openfeign" % "feign-slf4j" % "10.11" % "compile",
"io.github.openfeign" % "feign-core" % "11.0" % "compile",
"io.github.openfeign" % "feign-jackson" % "11.0" % "compile",
"io.github.openfeign" % "feign-slf4j" % "11.0" % "compile",
"io.github.openfeign.form" % "feign-form" % "3.8.0" % "compile",
"com.fasterxml.jackson.core" % "jackson-core" % "2.10.3" % "compile",
"com.fasterxml.jackson.core" % "jackson-annotations" % "2.10.3" % "compile",

View File

@@ -348,7 +348,7 @@
<maven.compiler.source>${java.version}</maven.compiler.source>
<maven.compiler.target>${java.version}</maven.compiler.target>
<swagger-annotations-version>1.5.24</swagger-annotations-version>
<feign-version>10.11</feign-version>
<feign-version>11.0</feign-version>
<feign-form-version>3.8.0</feign-form-version>
<jackson-version>2.10.3</jackson-version>
<jackson-databind-nullable-version>0.2.1</jackson-databind-nullable-version>

View File

@@ -874,17 +874,9 @@ public class ApiClient {
} else {
// We let jersey handle the serialization
if (isBodyNullable) { // payload is nullable
if (obj instanceof String) {
entity = Entity.entity(obj == null ? "null" : "\"" + ((String)obj).replaceAll("\"", Matcher.quoteReplacement("\\\"")) + "\"", contentType);
entity = Entity.entity(obj == null ? Entity.text("null") : obj, contentType);
} else {
entity = Entity.entity(obj == null ? "null" : obj, contentType);
}
} else {
if (obj instanceof String) {
entity = Entity.entity(obj == null ? "" : "\"" + ((String)obj).replaceAll("\"", Matcher.quoteReplacement("\\\"")) + "\"", contentType);
} else {
entity = Entity.entity(obj == null ? "" : obj, contentType);
}
entity = Entity.entity(obj == null ? Entity.text("") : obj, contentType);
}
}
return entity;
@@ -919,7 +911,7 @@ public class ApiClient {
if (isBodyNullable) {
return obj == null ? "null" : json.getMapper().writeValueAsString(obj);
} else {
return obj == null ? "" : json.getMapper().writeValueAsString(obj);
return json.getMapper().writeValueAsString(obj);
}
}
} catch (Exception ex) {

View File

@@ -34,7 +34,6 @@ public class JSON implements ContextResolver<ObjectMapper> {
public JSON() {
mapper = new ObjectMapper();
mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
mapper.configure(MapperFeature.ALLOW_COERCION_OF_SCALARS, false);
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, true);
mapper.configure(DeserializationFeature.FAIL_ON_INVALID_SUBTYPE, true);
mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);

View File

@@ -148,14 +148,6 @@ public class {{classname}} extends AbstractOpenApiSchema{{#vendorExtensions.x-im
return {{classname}}.schemas;
}
/**
* Set the instance that matches the anyOf child schema, check
* the instance parameter is valid against the anyOf child schemas:
* {{#anyOf}}{{{.}}}{{^-last}}, {{/-last}}{{/anyOf}}
*
* It could be an instance of the 'anyOf' schemas.
* The anyOf child schemas may themselves be a composed schema (allOf, anyOf, anyOf).
*/
@Override
public void setActualInstance(Object instance) {
{{#isNullable}}
@@ -174,29 +166,4 @@ public class {{classname}} extends AbstractOpenApiSchema{{#vendorExtensions.x-im
{{/anyOf}}
throw new RuntimeException("Invalid instance type. Must be {{#anyOf}}{{{.}}}{{^-last}}, {{/-last}}{{/anyOf}}");
}
/**
* Get the actual instance, which can be the following:
* {{#anyOf}}{{{.}}}{{^-last}}, {{/-last}}{{/anyOf}}
*
* @return The actual instance ({{#anyOf}}{{{.}}}{{^-last}}, {{/-last}}{{/anyOf}})
*/
@Override
public Object getActualInstance() {
return super.getActualInstance();
}
{{#anyOf}}
/**
* Get the actual instance of `{{{.}}}`. If the actual instanct is not `{{{.}}}`,
* the ClassCastException will be thrown.
*
* @return The actual instance of `{{{.}}}`
* @throws ClassCastException if the instance is not `{{{.}}}`
*/
public {{{.}}} get{{{.}}}() throws ClassCastException {
return ({{{.}}})super.getActualInstance();
}
{{/anyOf}}
}

View File

@@ -12,12 +12,10 @@ import java.security.Key;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Base64;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;
import java.util.Map;
import java.util.List;
import java.util.TimeZone;
import java.security.spec.AlgorithmParameterSpec;
import java.security.InvalidKeyException;
@@ -238,9 +236,7 @@ public class HttpSignatureAuth implements Authentication {
}
if (headers.contains("date")) {
SimpleDateFormat dateFormat = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss z", Locale.US);
dateFormat.setTimeZone(TimeZone.getTimeZone("GMT"));
headerParams.put("date", dateFormat.format(Calendar.getInstance().getTime()));
headerParams.put("date", new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss zzz", Locale.US).format(new Date()));
}
if (headers.contains("digest")) {
@@ -257,7 +253,7 @@ public class HttpSignatureAuth implements Authentication {
// Calling getRawPath and getRawQuery ensures the path is URL-encoded as it will be serialized
// on the wire. The HTTP signature must use the encode URL as it is sent on the wire.
String path = uri.getRawPath();
if (uri.getRawQuery() != null && !"".equals(uri.getRawQuery())) {
if (uri.getRawQuery() != "") {
path += "?" + uri.getRawQuery();
}

View File

@@ -137,9 +137,9 @@ ext {
{{#hasOAuthMethods}}
scribejava_apis_version = "6.9.0"
{{/hasOAuthMethods}}
{{#hasHttpSignatureMethods}}
tomitribe_http_signatures_version = "1.5"
{{/hasHttpSignatureMethods}}
{{#hasHttpBasicMethods}}
tomitribe_http_signatures_version = "1.3"
{{/hasHttpBasicMethods}}
}
dependencies {
@@ -161,9 +161,9 @@ dependencies {
{{#hasOAuthMethods}}
compile "com.github.scribejava:scribejava-apis:$scribejava_apis_version"
{{/hasOAuthMethods}}
{{#hasHttpSignatureMethods}}
{{#hasHttpBasicMethods}}
compile "org.tomitribe:tomitribe-http-signatures:$tomitribe_http_signatures_version"
{{/hasHttpSignatureMethods}}
{{/hasHttpBasicMethods}}
{{#supportJava6}}
compile "commons-io:commons-io:$commons_io_version"
compile "org.apache.commons:commons-lang3:$commons_lang3_version"

View File

@@ -28,9 +28,9 @@ lazy val root = (project in file(".")).
{{#hasOAuthMethods}}
"com.github.scribejava" % "scribejava-apis" % "6.9.0" % "compile",
{{/hasOAuthMethods}}
{{#hasHttpSignatureMethods}}
"org.tomitribe" % "tomitribe-http-signatures" % "1.5" % "compile",
{{/hasHttpSignatureMethods}}
{{#hasHttpBasicMethods}}
"org.tomitribe" % "tomitribe-http-signatures" % "1.3" % "compile",
{{/hasHttpBasicMethods}}
{{^java8}}
"com.brsanthu" % "migbase64" % "2.2",
{{/java8}}

View File

@@ -10,12 +10,10 @@ import java.util.HashSet;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.JsonToken;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.MapperFeature;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
@@ -75,34 +73,16 @@ public class {{classname}} extends AbstractOpenApiSchema{{#vendorExtensions.x-im
{{/discriminator}}
{{/useOneOfDiscriminatorLookup}}
boolean typeCoercion = ctxt.isEnabled(MapperFeature.ALLOW_COERCION_OF_SCALARS);
int match = 0;
JsonToken token = tree.traverse(jp.getCodec()).nextToken();
{{#oneOf}}
// deserialize {{{.}}}
try {
boolean attemptParsing = true;
// ensure that we respect type coercion as set on the client ObjectMapper
if ({{{.}}}.class.equals(Integer.class) || {{{.}}}.class.equals(Long.class) || {{{.}}}.class.equals(Float.class) || {{{.}}}.class.equals(Double.class) || {{{.}}}.class.equals(Boolean.class) || {{{.}}}.class.equals(String.class)) {
attemptParsing = typeCoercion;
if (!attemptParsing) {
attemptParsing |= (({{{.}}}.class.equals(Integer.class) || {{{.}}}.class.equals(Long.class)) && token == JsonToken.VALUE_NUMBER_INT);
attemptParsing |= (({{{.}}}.class.equals(Float.class) || {{{.}}}.class.equals(Double.class)) && token == JsonToken.VALUE_NUMBER_FLOAT);
attemptParsing |= ({{{.}}}.class.equals(Boolean.class) && (token == JsonToken.VALUE_FALSE || token == JsonToken.VALUE_TRUE));
attemptParsing |= ({{{.}}}.class.equals(String.class) && token == JsonToken.VALUE_STRING);
{{#isNullable}}
attemptParsing |= (token == JsonToken.VALUE_NULL);
{{/isNullable}}
}
}
if (attemptParsing) {
deserialized = tree.traverse(jp.getCodec()).readValueAs({{{.}}}.class);
// TODO: there is no validation against JSON schema constraints
// (min, max, enum, pattern...), this does not perform a strict JSON
// validation, which means the 'match' count may be higher than it should be.
match++;
log.log(Level.FINER, "Input data matches schema '{{{.}}}'");
}
} catch (Exception e) {
// deserialization failed, continue
log.log(Level.FINER, "Input data does not match schema '{{{.}}}'", e);
@@ -183,8 +163,7 @@ public class {{classname}} extends AbstractOpenApiSchema{{#vendorExtensions.x-im
/**
* Set the instance that matches the oneOf child schema, check
* the instance parameter is valid against the oneOf child schemas:
* {{#oneOf}}{{{.}}}{{^-last}}, {{/-last}}{{/oneOf}}
* the instance parameter is valid against the oneOf child schemas.
*
* It could be an instance of the 'oneOf' schemas.
* The oneOf child schemas may themselves be a composed schema (allOf, anyOf, oneOf).
@@ -208,28 +187,6 @@ public class {{classname}} extends AbstractOpenApiSchema{{#vendorExtensions.x-im
throw new RuntimeException("Invalid instance type. Must be {{#oneOf}}{{{.}}}{{^-last}}, {{/-last}}{{/oneOf}}");
}
/**
* Get the actual instance, which can be the following:
* {{#oneOf}}{{{.}}}{{^-last}}, {{/-last}}{{/oneOf}}
*
* @return The actual instance ({{#oneOf}}{{{.}}}{{^-last}}, {{/-last}}{{/oneOf}})
*/
@Override
public Object getActualInstance() {
return super.getActualInstance();
}
{{#oneOf}}
/**
* Get the actual instance of `{{{.}}}`. If the actual instanct is not `{{{.}}}`,
* the ClassCastException will be thrown.
*
* @return The actual instance of `{{{.}}}`
* @throws ClassCastException if the instance is not `{{{.}}}`
*/
public {{{.}}} get{{{.}}}() throws ClassCastException {
return ({{{.}}})super.getActualInstance();
}
{{/oneOf}}
}

View File

@@ -33,7 +33,6 @@ import javax.json.bind.annotation.JsonbProperty;
* {{{description}}}
**/
{{/description}}
{{>additionalModelTypeAnnotations}}
public class {{classname}} {{#parent}}extends {{{parent}}}{{/parent}}{{#serializableModel}} implements Serializable{{/serializableModel}} {
{{#vars}}{{#isEnum}}{{^isContainer}}
{{>enumClass}}{{/isContainer}}{{#isContainer}}{{#mostInnerItems}}

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