diff --git a/.travis.yml b/.travis.yml index 6787fd9fe590..3bb3c73cb7f8 100644 --- a/.travis.yml +++ b/.travis.yml @@ -178,9 +178,33 @@ after_success: fi; fi; ## docker: build and push openapi-generator-online to DockerHub - - if [ $DOCKER_HUB_USERNAME ]; then echo "$DOCKER_HUB_PASSWORD" | docker login --username=$DOCKER_HUB_USERNAME --password-stdin && docker build -t $DOCKER_GENERATOR_IMAGE_NAME ./modules/openapi-generator-online && if [ ! -z "$TRAVIS_TAG" ]; then docker tag $DOCKER_GENERATOR_IMAGE_NAME:latest $DOCKER_GENERATOR_IMAGE_NAME:$TRAVIS_TAG; fi && if [ ! -z "$TRAVIS_TAG" ] || [ "$TRAVIS_BRANCH" = "master" ]; then docker push $DOCKER_GENERATOR_IMAGE_NAME && echo "Pushed to $DOCKER_GENERATOR_IMAGE_NAME"; fi; fi + - if [ $DOCKER_HUB_USERNAME ]; then + echo "$DOCKER_HUB_PASSWORD" | docker login --username=$DOCKER_HUB_USERNAME --password-stdin; + export cli_version=$(\mvn -o org.apache.maven.plugins:maven-help-plugin:2.1.1:evaluate -Dexpression=project.version | grep -v '\['); + export build_date=$(date -u +"%Y-%m-%dT%H:%M:%SZ"); + docker build --label=org.opencontainers.image.created=$build_date --label=org.opencontainers.image.title=openapi-generator-online --label=org.opencontainers.image.revision=$TRAVIS_COMMIT --label=org.opencontainers.image.version=$cli_version -t $DOCKER_GENERATOR_IMAGE_NAME ./modules/openapi-generator-online; + if [ ! -z "$TRAVIS_TAG" ]; then + docker tag $DOCKER_GENERATOR_IMAGE_NAME:latest $DOCKER_GENERATOR_IMAGE_NAME:$TRAVIS_TAG; + fi; + if [ ! -z "$TRAVIS_TAG" ] || [ "$TRAVIS_BRANCH" = "master" ]; then + docker push $DOCKER_GENERATOR_IMAGE_NAME && echo "Pushed to $DOCKER_GENERATOR_IMAGE_NAME"; + fi; + fi; ## docker: build cli image and push to Docker Hub - - if [ $DOCKER_HUB_USERNAME ]; then echo "$DOCKER_HUB_PASSWORD" | docker login --username=$DOCKER_HUB_USERNAME --password-stdin && cp docker-entrypoint.sh ./modules/openapi-generator-cli && docker build -t $DOCKER_CODEGEN_CLI_IMAGE_NAME ./modules/openapi-generator-cli && if [ ! -z "$TRAVIS_TAG" ]; then docker tag $DOCKER_CODEGEN_CLI_IMAGE_NAME:latest $DOCKER_CODEGEN_CLI_IMAGE_NAME:$TRAVIS_TAG; fi && if [ ! -z "$TRAVIS_TAG" ] || [ "$TRAVIS_BRANCH" = "master" ]; then docker push $DOCKER_CODEGEN_CLI_IMAGE_NAME && echo "Pushed to $DOCKER_CODEGEN_CLI_IMAGE_NAME"; fi; fi + - if [ $DOCKER_HUB_USERNAME ]; then + echo "$DOCKER_HUB_PASSWORD" | docker login --username=$DOCKER_HUB_USERNAME --password-stdin; + cp docker-entrypoint.sh ./modules/openapi-generator-cli; + export cli_version=$(\mvn -o org.apache.maven.plugins:maven-help-plugin:2.1.1:evaluate -Dexpression=project.version | grep -v '\['); + export build_date=$(date -u +"%Y-%m-%dT%H:%M:%SZ"); + docker build --label=org.opencontainers.image.created=$build_date --label=org.opencontainers.image.title=openapi-generator-cli --label=org.opencontainers.image.revision=$TRAVIS_COMMIT --label=org.opencontainers.image.version=$cli_version -t $DOCKER_CODEGEN_CLI_IMAGE_NAME ./modules/openapi-generator-cli; + if [ ! -z "$TRAVIS_TAG" ]; then + docker tag $DOCKER_CODEGEN_CLI_IMAGE_NAME:latest $DOCKER_CODEGEN_CLI_IMAGE_NAME:$TRAVIS_TAG; + fi; + if [ ! -z "$TRAVIS_TAG" ] || [ "$TRAVIS_BRANCH" = "master" ]; then + docker push $DOCKER_CODEGEN_CLI_IMAGE_NAME; + echo "Pushed to $DOCKER_CODEGEN_CLI_IMAGE_NAME"; + fi; + fi; ## publish latest website, variables below are secure environment variables which are unavailable to PRs from forks. - if [ "$TRAVIS_BRANCH" = "master" ] && [ -z $TRAVIS_TAG ] && [ "$TRAVIS_PULL_REQUEST" == "false" ]; then cd website; diff --git a/CI/bitrise.yml b/CI/bitrise.yml index 4b07417c80b1..42ada2030a86 100644 --- a/CI/bitrise.yml +++ b/CI/bitrise.yml @@ -31,7 +31,7 @@ workflows: mvn package -Dorg.slf4j.simpleLogger.defaultLogLevel=error title: Build openapi-generator - script@1.1.5: - title: Update Swift4 samples + title: Update Swift samples inputs: - content: | #!/usr/bin/env bash @@ -39,6 +39,7 @@ workflows: set -e sh bin/swift4-all.sh + sh bin/swift5-all.sh - script@1.1.5: title: Run Swift4 tests inputs: @@ -49,15 +50,6 @@ workflows: ./samples/client/petstore/swift4/swift4_test_all.sh ./samples/client/test/swift4/swift4_test_all.sh - - script@1.1.5: - title: Update Swift5 samples - inputs: - - content: | - #!/usr/bin/env bash - - set -e - - sh bin/swift5-all.sh - script@1.1.5: title: Run Swift5 tests inputs: @@ -66,14 +58,15 @@ workflows: set -e - ./samples/client/petstore/swift5/swift5_test_all.sh ./samples/client/test/swift5/swift5_test_all.sh - - script@1.1.5: - title: Run all bin scripts - inputs: - - content: |- - #!/usr/bin/env bash - - set -e +# comment out the following as it's causing timeout +# - script@1.1.5: +# title: Run all bin scripts +# inputs: +# - content: |- +# #!/usr/bin/env bash +# +# set -e +# +# ./bin/run-all-petstore - ./bin/run-all-petstore diff --git a/CI/samples.ci/client/petstore/csharp/OpenAPIClient/src/Org.OpenAPITools.Test/Org.OpenAPITools.Test.csproj b/CI/samples.ci/client/petstore/csharp/OpenAPIClient/src/Org.OpenAPITools.Test/Org.OpenAPITools.Test.csproj index c7a19d07a9fc..9b5a34202cb4 100644 --- a/CI/samples.ci/client/petstore/csharp/OpenAPIClient/src/Org.OpenAPITools.Test/Org.OpenAPITools.Test.csproj +++ b/CI/samples.ci/client/petstore/csharp/OpenAPIClient/src/Org.OpenAPITools.Test/Org.OpenAPITools.Test.csproj @@ -4,7 +4,7 @@ OpenAPI Petstore This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ -OpenAPI spec version: 1.0.0 +The version of the OpenAPI document: 1.0.0 --> @@ -47,16 +47,16 @@ OpenAPI spec version: 1.0.0 - $(SolutionDir)\packages\Newtonsoft.Json.12.0.1\lib\net45\Newtonsoft.Json.dll - ..\packages\Newtonsoft.Json.12.0.1\lib\net45\Newtonsoft.Json.dll - ..\..\packages\Newtonsoft.Json.12.0.1\lib\net45\Newtonsoft.Json.dll - ..\..\vendor\Newtonsoft.Json.12.0.1\lib\net45\Newtonsoft.Json.dll + $(SolutionDir)\packages\Newtonsoft.Json.12.0.3\lib\net45\Newtonsoft.Json.dll + ..\packages\Newtonsoft.Json.12.0.3\lib\net45\Newtonsoft.Json.dll + ..\..\packages\Newtonsoft.Json.12.0.3\lib\net45\Newtonsoft.Json.dll + ..\..\vendor\Newtonsoft.Json.12.0.3\lib\net45\Newtonsoft.Json.dll - $(SolutionDir)\packages\JsonSubTypes.1.5.2\lib\net45\JsonSubTypes.dll - ..\packages\JsonSubTypes.1.5.2\lib\net45\JsonSubTypes.dll - ..\..\packages\JsonSubTypes.1.5.2\lib\net45\JsonSubTypes.dll - ..\..\vendor\JsonSubTypes.1.5.2\lib\net45\JsonSubTypes.dll + $(SolutionDir)\packages\JsonSubTypes.1.6.0\lib\net45\JsonSubTypes.dll + ..\packages\JsonSubTypes.1.6.0\lib\net45\JsonSubTypes.dll + ..\..\packages\JsonSubTypes.1.6.0\lib\net45\JsonSubTypes.dll + ..\..\vendor\JsonSubTypes.1.6.0\lib\net45\JsonSubTypes.dll $(SolutionDir)\packages\RestSharp.105.1.0\lib\net45\RestSharp.dll @@ -72,7 +72,8 @@ OpenAPI spec version: 1.0.0 - + diff --git a/bin/ci/java-rest-assured-jackson.json b/bin/ci/java-rest-assured-jackson.json new file mode 100644 index 000000000000..1ff56d80ea83 --- /dev/null +++ b/bin/ci/java-rest-assured-jackson.json @@ -0,0 +1,16 @@ +{ + "!include": "bin/java-petstore-rest-assured-jackson.json", + "generatorName": "java", + "inputSpec": "modules/openapi-generator/src/test/resources/2_0/petstore-with-fake-endpoints-models-for-testing.yaml", + "outputDir": "samples/client/petstore/java/rest-assured-jackson", + "templateDir": "modules/openapi-generator/src/main/resources/Java/libraries/rest-assured", + "additionalProperties": { + "hideGenerationTimestamp": true, + "booleanGetterPrefix": "is", + "java8": "true", + "dateLibrary": "java8", + "serializationLibrary": "jackson", + "useBeanValidation": "true", + "performBeanValidation": "true" + } +} diff --git a/bin/csharp-dotnet2-petstore.sh b/bin/csharp-dotnet2-petstore.sh index d3641ed1ce55..c953170bfaa0 100755 --- a/bin/csharp-dotnet2-petstore.sh +++ b/bin/csharp-dotnet2-petstore.sh @@ -27,6 +27,6 @@ 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 csharp-dotnet2 -o samples/client/petstore/csharp-dotnet2/OpenAPIClientTest/Lib/OpenAPIClient --additional-properties hideGenerationTimestamp=true $@" +ags="generate -i modules/openapi-generator/src/test/resources/2_0/petstore.yaml -g csharp-dotnet2 -t modules/openapi-generator/src/main/resources/csharp-dotnet2 -o samples/client/petstore/csharp-dotnet2/OpenAPIClientTest/Lib/OpenAPIClient --additional-properties hideGenerationTimestamp=true $@" java $JAVA_OPTS -jar $executable $ags diff --git a/bin/html2-petstore.sh b/bin/html2-petstore.sh index 3b82165d1034..d125551e1332 100755 --- a/bin/html2-petstore.sh +++ b/bin/html2-petstore.sh @@ -27,6 +27,6 @@ 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 html2 -o samples/documentation/html2 --additional-properties hideGenerationTimestamp=true $@" +ags="generate -i modules/openapi-generator/src/test/resources/2_0/petstore.yaml -g html2 -o samples/documentation/html2 -t modules/openapi-generator/src/main/resources/htmlDocs2/ --additional-properties hideGenerationTimestamp=true $@" java $JAVA_OPTS -jar $executable $ags diff --git a/bin/java-petstore-all.sh b/bin/java-petstore-all.sh index 6eed10ebe38b..05b50835c99d 100755 --- a/bin/java-petstore-all.sh +++ b/bin/java-petstore-all.sh @@ -12,6 +12,7 @@ ./bin/java-petstore-okhttp-gson-parcelable.sh ./bin/java-petstore-okhttp-gson.sh ./bin/java-petstore-rest-assured.sh +./bin/java-petstore-rest-assured-jackson.sh ./bin/java-petstore-resteasy.sh ./bin/java-petstore-resttemplate-withxml.sh ./bin/java-petstore-resttemplate.sh diff --git a/bin/java-petstore-jersey2-experimental.json b/bin/java-petstore-jersey2-experimental.json new file mode 100644 index 000000000000..156775302d4c --- /dev/null +++ b/bin/java-petstore-jersey2-experimental.json @@ -0,0 +1,4 @@ +{ + "library": "jersey2-experimental", + "artifactId": "petstore-jersey2-exp" +} diff --git a/bin/java-petstore-jersey2-experimental.sh b/bin/java-petstore-jersey2-experimental.sh new file mode 100755 index 000000000000..2bd023c97b47 --- /dev/null +++ b/bin/java-petstore-jersey2-experimental.sh @@ -0,0 +1,50 @@ +#!/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/3_0/petstore-with-fake-endpoints-models-for-testing.yaml -g java -c bin/java-petstore-jersey2-experimental.json -o samples/client/petstore/java/jersey2-experimental -t modules/openapi-generator/src/main/resources/Java/libraries/jersey2-experimental --additional-properties hideGenerationTimestamp=true $@" + +echo "Removing files and folders under samples/client/petstore/java/jersey2-experimental/src/main" +rm -rf samples/client/petstore/java/jersey2-experimental/src/main +find samples/client/petstore/java/jersey2-experimental -maxdepth 1 -type f ! -name "README.md" -exec rm {} + +java $JAVA_OPTS -jar $executable $ags + +#mvn com.coveo:fmt-maven-plugin:format -f samples/client/petstore/java/jersey2-experimental/pom.xml + +# copy additional manually written unit-tests +#mkdir samples/client/petstore/java/jersey2/src/test/java/org/openapitools/client +#mkdir samples/client/petstore/java/jersey2/src/test/java/org/openapitools/client/auth +#mkdir samples/client/petstore/java/jersey2/src/test/java/org/openapitools/client/model + +#cp CI/samples.ci/client/petstore/java/test-manual/common/StringUtilTest.java samples/client/petstore/java/jersey2/src/test/java/org/openapitools/client/StringUtilTest.java +#cp CI/samples.ci/client/petstore/java/test-manual/jersey2/ApiClientTest.java samples/client/petstore/java/jersey2/src/test/java/org/openapitools/client/ApiClientTest.java +#cp CI/samples.ci/client/petstore/java/test-manual/common/ConfigurationTest.java samples/client/petstore/java/jersey2/src/test/java/org/openapitools/client/ConfigurationTest.java +#cp CI/samples.ci/client/petstore/java/test-manual/jersey2/auth/ApiKeyAuthTest.java samples/client/petstore/java/jersey2/src/test/java/org/openapitools/client/auth/ApiKeyAuthTest.java +#cp CI/samples.ci/client/petstore/java/test-manual/jersey2/auth/HttpBasicAuthTest.java samples/client/petstore/java/jersey2/src/test/java/org/openapitools/client/auth/HttpBasicAuthTest.java +#cp CI/samples.ci/client/petstore/java/test-manual/jersey2/model/EnumValueTest.java samples/client/petstore/java/jersey2/src/test/java/org/openapitools/client/model/EnumValueTest.java +#cp CI/samples.ci/client/petstore/java/test-manual/jersey2/JSONTest.java samples/client/petstore/java/jersey2/src/test/java/org/openapitools/client/JSONTest.java diff --git a/bin/java-petstore-rest-assured-jackson.json b/bin/java-petstore-rest-assured-jackson.json new file mode 100644 index 000000000000..d6e6035df801 --- /dev/null +++ b/bin/java-petstore-rest-assured-jackson.json @@ -0,0 +1,4 @@ +{ + "library": "rest-assured", + "artifactId": "petstore-rest-assured-jackson" +} diff --git a/bin/java-petstore-rest-assured-jackson.sh b/bin/java-petstore-rest-assured-jackson.sh new file mode 100755 index 000000000000..eeffe6aaceed --- /dev/null +++ b/bin/java-petstore-rest-assured-jackson.sh @@ -0,0 +1,36 @@ +#!/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" +target_dir="./samples/client/petstore/java/rest-assured-jackson/" + +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" +args="generate -t modules/openapi-generator/src/main/resources/Java/libraries/rest-assured -i modules/openapi-generator/src/test/resources/2_0/petstore-with-fake-endpoints-models-for-testing.yaml -g java -c bin/java-petstore-rest-assured-jackson.json -o ${target_dir} --additional-properties hideGenerationTimestamp=true --additional-properties useBeanValidation=true --additional-properties performBeanValidation=true --additional-properties booleanGetterPrefix=is --additional-properties java8=true --additional-properties dateLibrary=java8 --additional-properties serializationLibrary=jackson $@" + +echo "Removing ${target_dir}" +rm -rf "${target_dir}" + +java $JAVA_OPTS -jar $executable $args diff --git a/bin/java-petstore-rest-assured.sh b/bin/java-petstore-rest-assured.sh index cacc3cf3c279..93de0703ed77 100755 --- a/bin/java-petstore-rest-assured.sh +++ b/bin/java-petstore-rest-assured.sh @@ -27,7 +27,7 @@ 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 -t modules/openapi-generator/src/main/resources/Java/libraries/rest-assured -i modules/openapi-generator/src/test/resources/2_0/petstore-with-fake-endpoints-models-for-testing.yaml -g java -c bin/java-petstore-rest-assured.json -o samples/client/petstore/java/rest-assured --additional-properties hideGenerationTimestamp=true --additional-properties booleanGetterPrefix=is $@" +ags="generate -t modules/openapi-generator/src/main/resources/Java/libraries/rest-assured -i modules/openapi-generator/src/test/resources/2_0/petstore-with-fake-endpoints-models-for-testing.yaml -g java -c bin/java-petstore-rest-assured.json -o samples/client/petstore/java/rest-assured --additional-properties hideGenerationTimestamp=true --additional-properties useBeanValidation=true --additional-properties performBeanValidation=true --additional-properties booleanGetterPrefix=is $@" echo "Removing files and folders under samples/client/petstore/java/rest-assured/src/main" rm -rf samples/client/petstore/java/rest-assured/src/main diff --git a/bin/openapi3/powershell-experimental-petstore.sh b/bin/openapi3/powershell-experimental-petstore.sh index 254fea356e73..148fd2690e5e 100755 --- a/bin/openapi3/powershell-experimental-petstore.sh +++ b/bin/openapi3/powershell-experimental-petstore.sh @@ -27,6 +27,6 @@ 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 -t modules/openapi-generator/src/main/resources/powershell-experimental -i modules/openapi-generator/src/test/resources/3_0/powershell/petstore.yaml -g powershell-experimental -o samples/client/petstore/powershell-experimental --additional-properties powershellGalleryUrl=https://www.powershellgallery.com/packages/PSPetstore,packageGuid=a27b908d-2a20-467f-bc32-af6f3a654ac5,packageName=PSPetstore,apiNamePrefix=PS,packageVersion=0.1.2 -c ./bin/powershell-config.json $@" +ags="generate -t modules/openapi-generator/src/main/resources/powershell-experimental -i modules/openapi-generator/src/test/resources/3_0/powershell/petstore.yaml -g powershell-experimental -o samples/client/petstore/powershell-experimental --additional-properties powershellGalleryUrl=https://www.powershellgallery.com/packages/PSPetstore,packageGuid=a27b908d-2a20-467f-bc32-af6f3a654ac5,packageName=PSPetstore,apiNamePrefix=PS,packageVersion=0.1.2,commonVerbs=Delete=Remove:Patch=Update $@" java ${JAVA_OPTS} -jar ${executable} ${ags} diff --git a/bin/openapi3/scala-akka-petstore.sh b/bin/openapi3/scala-akka-petstore.sh index 736fe0312464..5443c58f8fb7 100755 --- a/bin/openapi3/scala-akka-petstore.sh +++ b/bin/openapi3/scala-akka-petstore.sh @@ -27,6 +27,6 @@ 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 --artifact-id "scala-akka-petstore-client" -t modules/openapi-generator/src/main/resources/scala-akka-client -i modules/openapi-generator/src/test/resources/3_0/petstore.yaml -g scala-akka -o samples/openapi3/client/petstore/scala-akka $@" +ags="generate --artifact-id "scala-akka-petstore-client" -t modules/openapi-generator/src/main/resources/scala-akka-client -i modules/openapi-generator/src/test/resources/3_0/scala-akka/petstore.yaml -g scala-akka -o samples/openapi3/client/petstore/scala-akka $@" java $JAVA_OPTS -jar $executable $ags diff --git a/bin/python-server-aiohttp-srclayout-petstore.sh b/bin/python-server-aiohttp-srclayout-petstore.sh new file mode 100755 index 000000000000..126e2d9fcc13 --- /dev/null +++ b/bin/python-server-aiohttp-srclayout-petstore.sh @@ -0,0 +1,44 @@ +#!/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 + +generator=python-aiohttp +input=modules/openapi-generator/src/test/resources/2_0/petstore.yaml +out_folder=samples/server/petstore/${generator}-srclayout +resources=modules/openapi-generator/src/main/resources/${generator} + +# if you've executed sbt assembly previously it will use that instead. +export JAVA_OPTS="${JAVA_OPTS} -Xmx1024M -DloggerPath=conf/log4j.properties -Dservice" +ags="generate -t $resources -i $input -g $generator -o $out_folder --additional-properties pythonSrcRoot=src $@" + +rm -rf $out_folder/.openapi* +rm -rf $out_folder/openapi_server +rm -rf $out_folder/tests* +rm $out_folder/README.md +rm $out_folder/requirements.txt +rm $out_folder/test-requirements.txt + +java $JAVA_OPTS -jar $executable $ags diff --git a/bin/python-server-all.sh b/bin/python-server-all.sh index 5fe3176eed9e..c4fa204d1c6a 100755 --- a/bin/python-server-all.sh +++ b/bin/python-server-all.sh @@ -1,6 +1,7 @@ #!/bin/sh ./bin/python-server-aiohttp-petstore.sh +./bin/python-server-aiohttp-srclayout-petstore.sh ./bin/python-server-flask-petstore.sh ./bin/python-server-flask-petstore-python2.sh ./bin/python-server-blueplanet-petstore.sh diff --git a/bin/scala-akka-http-server-petstore.sh b/bin/scala-akka-http-server-petstore.sh new file mode 100755 index 000000000000..80d49b4e9336 --- /dev/null +++ b/bin/scala-akka-http-server-petstore.sh @@ -0,0 +1,31 @@ +#!/bin/sh + +SCRIPT="$0" + +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 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 scala-akka-http-server -o samples/server/petstore/scala-akka-http-server $@" + +java ${JAVA_OPTS} -jar ${executable} ${ags} diff --git a/bin/swift5-petstore-all.sh b/bin/swift5-petstore-all.sh index bce216fcb420..a4b54f49deff 100755 --- a/bin/swift5-petstore-all.sh +++ b/bin/swift5-petstore-all.sh @@ -9,4 +9,4 @@ ./bin/swift5-petstore-urlsession.sh ./bin/swift5-petstore-alamofire.sh ./bin/swift5-petstore-combine.sh - \ No newline at end of file +./bin/swift5-petstore-readonlyProperties.sh diff --git a/bin/swift5-petstore-readOnlyProperties.json b/bin/swift5-petstore-readOnlyProperties.json new file mode 100644 index 000000000000..3993a3c26aab --- /dev/null +++ b/bin/swift5-petstore-readOnlyProperties.json @@ -0,0 +1,7 @@ +{ + "podSummary": "PetstoreClient", + "podHomepage": "https://github.com/openapitools/openapi-generator", + "podAuthors": "", + "projectName": "PetstoreClient", + "readonlyProperties": true +} diff --git a/bin/swift5-petstore-readOnlyProperties.sh b/bin/swift5-petstore-readOnlyProperties.sh new file mode 100755 index 000000000000..fe838af1d3c6 --- /dev/null +++ b/bin/swift5-petstore-readOnlyProperties.sh @@ -0,0 +1,42 @@ +#!/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 -t modules/openapi-generator/src/main/resources/swift5 -i modules/openapi-generator/src/test/resources/2_0/swift/petstore-with-fake-endpoints-models-for-testing.yaml -g swift5 -c ./bin/swift5-petstore-readonlyProperties.json -o samples/client/petstore/swift5/readonlyProperties --generate-alias-as-model $@" + +java $JAVA_OPTS -jar $executable $ags + +if type "xcodegen" > /dev/null 2>&1; then + cd samples/client/petstore/swift5/readonlyProperties + xcodegen generate +fi + +if type "swiftlint" > /dev/null 2>&1; then + cd samples/client/petstore/swift5/readonlyProperties + swiftlint autocorrect +fi \ No newline at end of file diff --git a/bin/windows/csharp-dotnet2-petstore.bat b/bin/windows/csharp-dotnet2-petstore.bat index ec36de485a0c..f5bc77332e65 100755 --- a/bin/windows/csharp-dotnet2-petstore.bat +++ b/bin/windows/csharp-dotnet2-petstore.bat @@ -5,6 +5,6 @@ If Not Exist %executable% ( ) REM set JAVA_OPTS=%JAVA_OPTS% -Xmx1024M -set ags=generate -i modules/openapi-generator/src/test/resources/2_0/petstore.yaml -g csharp-dotnet2 -o samples/client/petstore/csharp-dotnet2/SwaggerClientTest/Lib/SwaggerClient --additional-properties hideGenerationTimestamp=true +set ags=generate -i modules/openapi-generator/src/test/resources/2_0/petstore.yaml -g csharp-dotnet2 -t modules/openapi-generator/src/main/resources/csharp-dotnet2 -o samples/client/petstore/csharp-dotnet2/OpenApiClientTest/Lib/OpenApiClient --additional-properties hideGenerationTimestamp=true java %JAVA_OPTS% -jar %executable% %ags% diff --git a/bin/windows/csharp-petstore-net-35.bat b/bin/windows/csharp-petstore-net-35.bat index c654ba61783a..555ff79cc358 100644 --- a/bin/windows/csharp-petstore-net-35.bat +++ b/bin/windows/csharp-petstore-net-35.bat @@ -5,6 +5,6 @@ If Not Exist %executable% ( ) REM set JAVA_OPTS=%JAVA_OPTS% -Xmx1024M -set ags=generate -i modules/openapi-generator/src/test/resources/2_0/petstore-with-fake-endpoints-models-for-testing.yaml -g csharp -o samples/client/petstore/csharp/SwaggerClientNet35 --additional-properties packageGuid={321C8C3F-0156-40C1-AE42-D59761FB9B6C} -c ./bin/csharp-petstore-net-35.json +set ags=generate -i modules/openapi-generator/src/test/resources/2_0/petstore-with-fake-endpoints-models-for-testing.yaml -g csharp -o samples/client/petstore/csharp/OpenApiClientNet35 --additional-properties packageGuid={321C8C3F-0156-40C1-AE42-D59761FB9B6C} -c ./bin/csharp-petstore-net-35.json java %JAVA_OPTS% -jar %executable% %ags% diff --git a/bin/windows/csharp-petstore-net-40.bat b/bin/windows/csharp-petstore-net-40.bat index f7722c8205ce..08f49c4c7669 100644 --- a/bin/windows/csharp-petstore-net-40.bat +++ b/bin/windows/csharp-petstore-net-40.bat @@ -5,6 +5,6 @@ If Not Exist %executable% ( ) REM set JAVA_OPTS=%JAVA_OPTS% -Xmx1024M -set ags=generate -i modules\openapi-generator\src\test\resources\2_0\petstore-with-fake-endpoints-models-for-testing.yaml -g csharp -o samples\client\petstore\csharp\SwaggerClientNet40 --additional-properties packageGuid={321C8C3F-0156-40C1-AE42-D59761FB9B6C} -c .\bin\csharp-petstore-net-40.json +set ags=generate -i modules\openapi-generator\src\test\resources\2_0\petstore-with-fake-endpoints-models-for-testing.yaml -g csharp -o samples\client\petstore\csharp\OpenApiClientNet40 --additional-properties packageGuid={321C8C3F-0156-40C1-AE42-D59761FB9B6C} -c .\bin\csharp-petstore-net-40.json java %JAVA_OPTS% -jar %executable% %ags% diff --git a/bin/windows/csharp-petstore-netcore-project.bat b/bin/windows/csharp-petstore-netcore-project.bat index 0ab98c86b4d3..5538f292b97e 100644 --- a/bin/windows/csharp-petstore-netcore-project.bat +++ b/bin/windows/csharp-petstore-netcore-project.bat @@ -5,6 +5,6 @@ If Not Exist %executable% ( ) REM set JAVA_OPTS=%JAVA_OPTS% -Xmx1024M -set ags=generate -i modules/openapi-generator/src/test/resources/2_0/petstore-with-fake-endpoints-models-for-testing.yaml -g csharp -o samples\client\petstore\csharp\SwaggerClientNetCoreProject --additional-properties targetFramework=v5.0,packageGuid={67035b31-f8e5-41a4-9673-954035084f7d},netCoreProjectFile=true +set ags=generate -i modules/openapi-generator/src/test/resources/2_0/petstore-with-fake-endpoints-models-for-testing.yaml -g csharp -o samples\client\petstore\csharp\OpenApiClientNetCoreProject --additional-properties targetFramework=v5.0,packageGuid={67035b31-f8e5-41a4-9673-954035084f7d},netCoreProjectFile=true java %JAVA_OPTS% -jar %executable% %ags% diff --git a/bin/windows/csharp-petstore-netstandard.bat b/bin/windows/csharp-petstore-netstandard.bat index 236071868c72..b2abd6bfa026 100644 --- a/bin/windows/csharp-petstore-netstandard.bat +++ b/bin/windows/csharp-petstore-netstandard.bat @@ -5,6 +5,6 @@ If Not Exist %executable% ( ) REM set JAVA_OPTS=%JAVA_OPTS% -Xmx1024M -set ags=generate -i modules\openapi-generator\src\test\resources\2_0\petstore-with-fake-endpoints-models-for-testing.yaml -g csharp -o samples\client\petstore\csharp\SwaggerClientNetStandard --additional-properties targetFramework=v5.0,packageGuid={3AB1F259-1769-484B-9411-84505FCCBD55} +set ags=generate -i modules\openapi-generator\src\test\resources\2_0\petstore-with-fake-endpoints-models-for-testing.yaml -g csharp -o samples\client\petstore\csharp\OpenApiClientNetStandard --additional-properties targetFramework=v5.0,packageGuid={3AB1F259-1769-484B-9411-84505FCCBD55} java %JAVA_OPTS% -jar %executable% %ags% diff --git a/bin/windows/csharp-property-changed-petstore.bat b/bin/windows/csharp-property-changed-petstore.bat index d4938f71400b..48cdf749f01e 100644 --- a/bin/windows/csharp-property-changed-petstore.bat +++ b/bin/windows/csharp-property-changed-petstore.bat @@ -5,6 +5,6 @@ If Not Exist %executable% ( ) REM set JAVA_OPTS=%JAVA_OPTS% -Xmx1024M -set ags=generate -i modules/openapi-generator/src/test/resources/2_0/petstore-with-fake-endpoints-models-for-testing.yaml -g csharp -o samples\client\petstore\csharp\SwaggerClientWithPropertyChanged --additional-properties=generatePropertyChanged=true,optionalEmitDefaultValues=true,packageGuid={5CD900DE-8266-412F-A758-28E1F9C623D5} +set ags=generate -i modules/openapi-generator/src/test/resources/2_0/petstore-with-fake-endpoints-models-for-testing.yaml -g csharp -o samples\client\petstore\csharp\OpenApiClientWithPropertyChanged --additional-properties=generatePropertyChanged=true,optionalEmitDefaultValues=true,packageGuid={5CD900DE-8266-412F-A758-28E1F9C623D5} java %JAVA_OPTS% -jar %executable% %ags% diff --git a/bin/windows/java-petstore-all.bat b/bin/windows/java-petstore-all.bat index dd357cfd56d1..816919bb8fd1 100644 --- a/bin/windows/java-petstore-all.bat +++ b/bin/windows/java-petstore-all.bat @@ -20,4 +20,5 @@ call .\bin\windows\java-petstore-webclient.bat call .\bin\windows\java-petstore-resteasy.bat call .\bin\windows\java-petstore-google-api-client.bat call .\bin\windows\java-petstore-rest-assured.bat +call .\bin\windows\java-petstore-rest-assured-jackson.bat call .\bin\windows\java-petstore-vertx.bat diff --git a/bin/windows/java-petstore-rest-assured-jackson.bat b/bin/windows/java-petstore-rest-assured-jackson.bat new file mode 100644 index 000000000000..8104df8b771d --- /dev/null +++ b/bin/windows/java-petstore-rest-assured-jackson.bat @@ -0,0 +1,10 @@ +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 +set ags=generate -t modules\openapi-generator\src\main\resources\Java\libraries\rest-assured -i modules\openapi-generator\src\test\resources\2_0\petstore-with-fake-endpoints-models-for-testing.yaml -g java -c bin\java-petstore-rest-assured-jackson.json -o samples\client\petstore\java\rest-assured-jackson --additional-properties hideGenerationTimestamp=true,booleanGetterPrefix=is,java8=true,dateLibrary=java8,serializationLibrary=jackson,useBeanValidation=true,performBeanValidation=true, + +java %JAVA_OPTS% -jar %executable% %ags% diff --git a/bin/windows/scala-akka-http-server-petstore.bat b/bin/windows/scala-akka-http-server-petstore.bat new file mode 100644 index 000000000000..d59f6fb47b6b --- /dev/null +++ b/bin/windows/scala-akka-http-server-petstore.bat @@ -0,0 +1,10 @@ +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 -DloggerPath=conf/log4j.properties +set ags=generate --artifact-id "scala-akka-http-petstore-server" -i modules\openapi-generator\src\test\resources\2_0\petstore.yaml -g scala-akka-http-server -o samples\server\petstore\scala-akka-http-server + +java %JAVA_OPTS% -jar %executable% %ags% diff --git a/bin/windows/swift5-petstore-all.bat b/bin/windows/swift5-petstore-all.bat index 1daaa1fee769..9d656b1437be 100755 --- a/bin/windows/swift5-petstore-all.bat +++ b/bin/windows/swift5-petstore-all.bat @@ -7,3 +7,4 @@ call .\bin\windows\swift5-petstore-nonPublicApi.bat call .\bin\windows\swift5-petstore-urlsession.bat call .\bin\windows\swift5-petstore-alamofire.bat call .\bin\windows\swift5-petstore-combine.bat +call .\bin\windows\swift5-petstore-readonlyProperties.bat diff --git a/bin/windows/swift5-petstore-readonlyProperties.bat b/bin/windows/swift5-petstore-readonlyProperties.bat new file mode 100644 index 000000000000..cc297bd1a4f2 --- /dev/null +++ b/bin/windows/swift5-petstore-readonlyProperties.bat @@ -0,0 +1,10 @@ +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 +set ags=generate -i modules\openapi-generator\src\test\resources\2_0\swift\petstore-with-fake-endpoints-models-for-testing.yaml -g swift5 -c bin\swift5-petstore-readonlyProperties.json -o samples\client\petstore\swift5\readonlyProperties + +java %JAVA_OPTS% -jar %executable% %ags% diff --git a/docs/customization.md b/docs/customization.md index 14fdd1a7f2c2..fbdc5a890cdb 100644 --- a/docs/customization.md +++ b/docs/customization.md @@ -248,7 +248,7 @@ CONFIG OPTIONS retrofit - HTTP client: OkHttp 2.4.0. JSON processing: Gson 2.3.1 (Retrofit 1.9.0) retrofit2 - HTTP client: OkHttp 2.5.0. JSON processing: Gson 2.4 (Retrofit 2.0.0-beta2) google-api-client - HTTP client: google-api-client 1.23.0. JSON processing: Jackson 2.8.9 - rest-assured - HTTP client: rest-assured : 4.0.0. JSON processing: Gson 2.8.5. Only for Java8 + rest-assured - HTTP client: rest-assured : 4.3.0. JSON processing: Gson 2.8.6. Only for Java8 ``` Your config file for Java can look like diff --git a/docs/generators.md b/docs/generators.md index 8e4995658a89..cc730aab7d88 100644 --- a/docs/generators.md +++ b/docs/generators.md @@ -120,6 +120,7 @@ The following generators are available: * [ruby-on-rails](generators/ruby-on-rails.md) * [ruby-sinatra](generators/ruby-sinatra.md) * [rust-server](generators/rust-server.md) +* [scala-akka-http-server (beta)](generators/scala-akka-http-server.md) * [scala-finch](generators/scala-finch.md) * [scala-lagom-server](generators/scala-lagom-server.md) * [scala-play-server](generators/scala-play-server.md) diff --git a/docs/generators/ada-server.md b/docs/generators/ada-server.md index 9a86032ec7e6..85bfb5b5d02c 100644 --- a/docs/generators/ada-server.md +++ b/docs/generators/ada-server.md @@ -7,6 +7,7 @@ sidebar_label: ada-server | ------ | ----------- | ------ | ------- | |allowUnicodeIdentifiers|boolean, toggles whether unicode identifiers are allowed in names or not, default is false| |false| |ensureUniqueParams|Whether to ensure parameter names are unique in an operation (rename parameters that are not).| |true| +|legacyDiscriminatorBehavior|This flag is used by OpenAPITools codegen to influence the processing of the discriminator attribute in OpenAPI documents. This flag has no impact if the OAS document does not use the discriminator attribute. The default value of this flag is set in each language-specific code generator (e.g. Python, Java, go...)using the method toModelName. Note to developers supporting a language generator in OpenAPITools; to fully support the discriminator attribute as defined in the OAS specification 3.x, language generators should set this flag to true by default; however this requires updating the mustache templates to generate a language-specific discriminator lookup function that iterates over {{#mappedModels}} and does not iterate over {{children}}, {{#anyOf}}, or {{#oneOf}}.|
**true**
The mapping in the discriminator includes descendent schemas that allOf inherit from self and the discriminator mapping schemas in the OAS document.
**false**
The mapping in the discriminator includes any descendent schemas that allOf inherit from self, any oneOf schemas, any anyOf schemas, any x-discriminator-values, and the discriminator mapping schemas in the OAS document AND Codegen validates that oneOf and anyOf schemas contain the required discriminator and throws an error if the discriminator is missing.
|true| |prependFormOrBodyParameters|Add form or body parameters to the beginning of the parameter list.| |false| |projectName|GNAT project name| |defaultProject| |sortModelPropertiesByRequiredFlag|Sort model properties to place required parameters before optional parameters.| |true| diff --git a/docs/generators/ada.md b/docs/generators/ada.md index 2b382b4c4fc2..66114165a03e 100644 --- a/docs/generators/ada.md +++ b/docs/generators/ada.md @@ -7,6 +7,7 @@ sidebar_label: ada | ------ | ----------- | ------ | ------- | |allowUnicodeIdentifiers|boolean, toggles whether unicode identifiers are allowed in names or not, default is false| |false| |ensureUniqueParams|Whether to ensure parameter names are unique in an operation (rename parameters that are not).| |true| +|legacyDiscriminatorBehavior|This flag is used by OpenAPITools codegen to influence the processing of the discriminator attribute in OpenAPI documents. This flag has no impact if the OAS document does not use the discriminator attribute. The default value of this flag is set in each language-specific code generator (e.g. Python, Java, go...)using the method toModelName. Note to developers supporting a language generator in OpenAPITools; to fully support the discriminator attribute as defined in the OAS specification 3.x, language generators should set this flag to true by default; however this requires updating the mustache templates to generate a language-specific discriminator lookup function that iterates over {{#mappedModels}} and does not iterate over {{children}}, {{#anyOf}}, or {{#oneOf}}.|
**true**
The mapping in the discriminator includes descendent schemas that allOf inherit from self and the discriminator mapping schemas in the OAS document.
**false**
The mapping in the discriminator includes any descendent schemas that allOf inherit from self, any oneOf schemas, any anyOf schemas, any x-discriminator-values, and the discriminator mapping schemas in the OAS document AND Codegen validates that oneOf and anyOf schemas contain the required discriminator and throws an error if the discriminator is missing.
|true| |prependFormOrBodyParameters|Add form or body parameters to the beginning of the parameter list.| |false| |projectName|GNAT project name| |defaultProject| |sortModelPropertiesByRequiredFlag|Sort model properties to place required parameters before optional parameters.| |true| diff --git a/docs/generators/android.md b/docs/generators/android.md index 4eeeec214b62..48cef4ce53c9 100644 --- a/docs/generators/android.md +++ b/docs/generators/android.md @@ -15,6 +15,7 @@ sidebar_label: android |ensureUniqueParams|Whether to ensure parameter names are unique in an operation (rename parameters that are not).| |true| |groupId|groupId for use in the generated build.gradle and pom.xml| |null| |invokerPackage|root package for generated code| |null| +|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}}.|
**true**
The mapping in the discriminator includes descendent schemas that allOf inherit from self and the discriminator mapping schemas in the OAS document.
**false**
The mapping in the discriminator includes any descendent schemas that allOf inherit from self, any oneOf schemas, any anyOf schemas, any x-discriminator-values, and the discriminator mapping schemas in the OAS document AND Codegen validates that oneOf and anyOf schemas contain the required discriminator and throws an error if the discriminator is missing.
|true| |library|library template (sub-template) to use|
**volley**
HTTP client: Volley 1.0.19 (default)
**httpclient**
HTTP client: Apache HttpClient 4.3.6. JSON processing: Gson 2.3.1. IMPORTANT: Android client using HttpClient is not actively maintained and will be depecreated in the next major release.
|null| |modelPackage|package for generated models| |null| |prependFormOrBodyParameters|Add form or body parameters to the beginning of the parameter list.| |false| diff --git a/docs/generators/apache2.md b/docs/generators/apache2.md index cfa9756c7d58..d097e39d84a9 100644 --- a/docs/generators/apache2.md +++ b/docs/generators/apache2.md @@ -7,6 +7,7 @@ sidebar_label: apache2 | ------ | ----------- | ------ | ------- | |allowUnicodeIdentifiers|boolean, toggles whether unicode identifiers are allowed in names or not, default is false| |false| |ensureUniqueParams|Whether to ensure parameter names are unique in an operation (rename parameters that are not).| |true| +|legacyDiscriminatorBehavior|This flag is used by OpenAPITools codegen to influence the processing of the discriminator attribute in OpenAPI documents. This flag has no impact if the OAS document does not use the discriminator attribute. The default value of this flag is set in each language-specific code generator (e.g. Python, Java, go...)using the method toModelName. Note to developers supporting a language generator in OpenAPITools; to fully support the discriminator attribute as defined in the OAS specification 3.x, language generators should set this flag to true by default; however this requires updating the mustache templates to generate a language-specific discriminator lookup function that iterates over {{#mappedModels}} and does not iterate over {{children}}, {{#anyOf}}, or {{#oneOf}}.|
**true**
The mapping in the discriminator includes descendent schemas that allOf inherit from self and the discriminator mapping schemas in the OAS document.
**false**
The mapping in the discriminator includes any descendent schemas that allOf inherit from self, any oneOf schemas, any anyOf schemas, any x-discriminator-values, and the discriminator mapping schemas in the OAS document AND Codegen validates that oneOf and anyOf schemas contain the required discriminator and throws an error if the discriminator is missing.
|true| |prependFormOrBodyParameters|Add form or body parameters to the beginning of the parameter list.| |false| |sortModelPropertiesByRequiredFlag|Sort model properties to place required parameters before optional parameters.| |true| |sortParamsByRequiredFlag|Sort method arguments to place required parameters before optional parameters.| |true| diff --git a/docs/generators/apex.md b/docs/generators/apex.md index 06c54e3b9722..9ead87c94e96 100644 --- a/docs/generators/apex.md +++ b/docs/generators/apex.md @@ -10,6 +10,7 @@ sidebar_label: apex |buildMethod|The build method for this package.| |null| |classPrefix|Prefix for generated classes. Set this to avoid overwriting existing classes in your org.| |null| |ensureUniqueParams|Whether to ensure parameter names are unique in an operation (rename parameters that are not).| |true| +|legacyDiscriminatorBehavior|This flag is used by OpenAPITools codegen to influence the processing of the discriminator attribute in OpenAPI documents. This flag has no impact if the OAS document does not use the discriminator attribute. The default value of this flag is set in each language-specific code generator (e.g. Python, Java, go...)using the method toModelName. Note to developers supporting a language generator in OpenAPITools; to fully support the discriminator attribute as defined in the OAS specification 3.x, language generators should set this flag to true by default; however this requires updating the mustache templates to generate a language-specific discriminator lookup function that iterates over {{#mappedModels}} and does not iterate over {{children}}, {{#anyOf}}, or {{#oneOf}}.|
**true**
The mapping in the discriminator includes descendent schemas that allOf inherit from self and the discriminator mapping schemas in the OAS document.
**false**
The mapping in the discriminator includes any descendent schemas that allOf inherit from self, any oneOf schemas, any anyOf schemas, any x-discriminator-values, and the discriminator mapping schemas in the OAS document AND Codegen validates that oneOf and anyOf schemas contain the required discriminator and throws an error if the discriminator is missing.
|true| |namedCredential|The named credential name for the HTTP callouts| |null| |prependFormOrBodyParameters|Add form or body parameters to the beginning of the parameter list.| |false| |sortModelPropertiesByRequiredFlag|Sort model properties to place required parameters before optional parameters.| |true| diff --git a/docs/generators/asciidoc.md b/docs/generators/asciidoc.md index 66a175518bc9..01683b0a323e 100644 --- a/docs/generators/asciidoc.md +++ b/docs/generators/asciidoc.md @@ -16,6 +16,7 @@ sidebar_label: asciidoc |infoEmail|an email address to contact for inquiries about the application| |null| |infoUrl|a URL where users can get more information about the application| |null| |invokerPackage|root package for generated code| |null| +|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}}.|
**true**
The mapping in the discriminator includes descendent schemas that allOf inherit from self and the discriminator mapping schemas in the OAS document.
**false**
The mapping in the discriminator includes any descendent schemas that allOf inherit from self, any oneOf schemas, any anyOf schemas, any x-discriminator-values, and the discriminator mapping schemas in the OAS document AND Codegen validates that oneOf and anyOf schemas contain the required discriminator and throws an error if the discriminator is missing.
|true| |licenseInfo|a short description of the license| |null| |licenseUrl|a URL pointing to the full license| |null| |prependFormOrBodyParameters|Add form or body parameters to the beginning of the parameter list.| |false| diff --git a/docs/generators/avro-schema.md b/docs/generators/avro-schema.md index 13ca849949a9..da33df520012 100644 --- a/docs/generators/avro-schema.md +++ b/docs/generators/avro-schema.md @@ -7,6 +7,7 @@ sidebar_label: avro-schema | ------ | ----------- | ------ | ------- | |allowUnicodeIdentifiers|boolean, toggles whether unicode identifiers are allowed in names or not, default is false| |false| |ensureUniqueParams|Whether to ensure parameter names are unique in an operation (rename parameters that are not).| |true| +|legacyDiscriminatorBehavior|This flag is used by OpenAPITools codegen to influence the processing of the discriminator attribute in OpenAPI documents. This flag has no impact if the OAS document does not use the discriminator attribute. The default value of this flag is set in each language-specific code generator (e.g. Python, Java, go...)using the method toModelName. Note to developers supporting a language generator in OpenAPITools; to fully support the discriminator attribute as defined in the OAS specification 3.x, language generators should set this flag to true by default; however this requires updating the mustache templates to generate a language-specific discriminator lookup function that iterates over {{#mappedModels}} and does not iterate over {{children}}, {{#anyOf}}, or {{#oneOf}}.|
**true**
The mapping in the discriminator includes descendent schemas that allOf inherit from self and the discriminator mapping schemas in the OAS document.
**false**
The mapping in the discriminator includes any descendent schemas that allOf inherit from self, any oneOf schemas, any anyOf schemas, any x-discriminator-values, and the discriminator mapping schemas in the OAS document AND Codegen validates that oneOf and anyOf schemas contain the required discriminator and throws an error if the discriminator is missing.
|true| |packageName|package for generated classes (where supported)| |null| |prependFormOrBodyParameters|Add form or body parameters to the beginning of the parameter list.| |false| |sortModelPropertiesByRequiredFlag|Sort model properties to place required parameters before optional parameters.| |true| diff --git a/docs/generators/bash.md b/docs/generators/bash.md index b91eb990a6d9..724e3d9a4704 100644 --- a/docs/generators/bash.md +++ b/docs/generators/bash.md @@ -13,6 +13,7 @@ sidebar_label: bash |generateBashCompletion|Whether to generate the Bash completion script| |false| |generateZshCompletion|Whether to generate the Zsh completion script| |false| |hostEnvironmentVariable|Name of environment variable where host can be defined (e.g. PETSTORE_HOST='http://api.openapitools.org:8080')| |null| +|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}}.|
**true**
The mapping in the discriminator includes descendent schemas that allOf inherit from self and the discriminator mapping schemas in the OAS document.
**false**
The mapping in the discriminator includes any descendent schemas that allOf inherit from self, any oneOf schemas, any anyOf schemas, any x-discriminator-values, and the discriminator mapping schemas in the OAS document AND Codegen validates that oneOf and anyOf schemas contain the required discriminator and throws an error if the discriminator is missing.
|true| |prependFormOrBodyParameters|Add form or body parameters to the beginning of the parameter list.| |false| |processMarkdown|Convert all Markdown Markup into terminal formatting| |false| |scriptName|The name of the script that will be generated (e.g. petstore-cli)| |null| diff --git a/docs/generators/c.md b/docs/generators/c.md index ee9b2586696e..80e50635f4c5 100644 --- a/docs/generators/c.md +++ b/docs/generators/c.md @@ -8,6 +8,7 @@ sidebar_label: c |allowUnicodeIdentifiers|boolean, toggles whether unicode identifiers are allowed in names or not, default is false| |false| |ensureUniqueParams|Whether to ensure parameter names are unique in an operation (rename parameters that are not).| |true| |hideGenerationTimestamp|Hides the generation timestamp when files are generated.| |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}}.|
**true**
The mapping in the discriminator includes descendent schemas that allOf inherit from self and the discriminator mapping schemas in the OAS document.
**false**
The mapping in the discriminator includes any descendent schemas that allOf inherit from self, any oneOf schemas, any anyOf schemas, any x-discriminator-values, and the discriminator mapping schemas in the OAS document AND Codegen validates that oneOf and anyOf schemas contain the required discriminator and throws an error if the discriminator is missing.
|true| |prependFormOrBodyParameters|Add form or body parameters to the beginning of the parameter list.| |false| |sortModelPropertiesByRequiredFlag|Sort model properties to place required parameters before optional parameters.| |true| |sortParamsByRequiredFlag|Sort method arguments to place required parameters before optional parameters.| |true| diff --git a/docs/generators/clojure.md b/docs/generators/clojure.md index b2f3a6a4d912..f2a755332bfb 100644 --- a/docs/generators/clojure.md +++ b/docs/generators/clojure.md @@ -8,6 +8,7 @@ sidebar_label: clojure |allowUnicodeIdentifiers|boolean, toggles whether unicode identifiers are allowed in names or not, default is false| |false| |baseNamespace|the base/top namespace (Default: generated from projectName)| |null| |ensureUniqueParams|Whether to ensure parameter names are unique in an operation (rename parameters that are not).| |true| +|legacyDiscriminatorBehavior|This flag is used by OpenAPITools codegen to influence the processing of the discriminator attribute in OpenAPI documents. This flag has no impact if the OAS document does not use the discriminator attribute. The default value of this flag is set in each language-specific code generator (e.g. Python, Java, go...)using the method toModelName. Note to developers supporting a language generator in OpenAPITools; to fully support the discriminator attribute as defined in the OAS specification 3.x, language generators should set this flag to true by default; however this requires updating the mustache templates to generate a language-specific discriminator lookup function that iterates over {{#mappedModels}} and does not iterate over {{children}}, {{#anyOf}}, or {{#oneOf}}.|
**true**
The mapping in the discriminator includes descendent schemas that allOf inherit from self and the discriminator mapping schemas in the OAS document.
**false**
The mapping in the discriminator includes any descendent schemas that allOf inherit from self, any oneOf schemas, any anyOf schemas, any x-discriminator-values, and the discriminator mapping schemas in the OAS document AND Codegen validates that oneOf and anyOf schemas contain the required discriminator and throws an error if the discriminator is missing.
|true| |prependFormOrBodyParameters|Add form or body parameters to the beginning of the parameter list.| |false| |projectDescription|description of the project (Default: using info.description or "Client library of <projectName>")| |null| |projectLicenseName|name of the license the project uses (Default: using info.license.name or not included in project.clj)| |null| diff --git a/docs/generators/cpp-qt5-client.md b/docs/generators/cpp-qt5-client.md index bc55db14523d..8e2bf7ab98b7 100644 --- a/docs/generators/cpp-qt5-client.md +++ b/docs/generators/cpp-qt5-client.md @@ -9,6 +9,7 @@ sidebar_label: cpp-qt5-client |contentCompression|Enable Compressed Content Encoding for requests and responses| |false| |cppNamespace|C++ namespace (convention: name::space::for::api).| |OpenAPI| |ensureUniqueParams|Whether to ensure parameter names are unique in an operation (rename parameters that are not).| |true| +|legacyDiscriminatorBehavior|This flag is used by OpenAPITools codegen to influence the processing of the discriminator attribute in OpenAPI documents. This flag has no impact if the OAS document does not use the discriminator attribute. The default value of this flag is set in each language-specific code generator (e.g. Python, Java, go...)using the method toModelName. Note to developers supporting a language generator in OpenAPITools; to fully support the discriminator attribute as defined in the OAS specification 3.x, language generators should set this flag to true by default; however this requires updating the mustache templates to generate a language-specific discriminator lookup function that iterates over {{#mappedModels}} and does not iterate over {{children}}, {{#anyOf}}, or {{#oneOf}}.|
**true**
The mapping in the discriminator includes descendent schemas that allOf inherit from self and the discriminator mapping schemas in the OAS document.
**false**
The mapping in the discriminator includes any descendent schemas that allOf inherit from self, any oneOf schemas, any anyOf schemas, any x-discriminator-values, and the discriminator mapping schemas in the OAS document AND Codegen validates that oneOf and anyOf schemas contain the required discriminator and throws an error if the discriminator is missing.
|true| |modelNamePrefix|Prefix that will be prepended to all model names.| |OAI| |optionalProjectFile|Generate client.pri.| |true| |prependFormOrBodyParameters|Add form or body parameters to the beginning of the parameter list.| |false| diff --git a/docs/generators/cpp-qt5-qhttpengine-server.md b/docs/generators/cpp-qt5-qhttpengine-server.md index 2b2cd4e9f15f..9e2f0e75e5c6 100644 --- a/docs/generators/cpp-qt5-qhttpengine-server.md +++ b/docs/generators/cpp-qt5-qhttpengine-server.md @@ -9,6 +9,7 @@ sidebar_label: cpp-qt5-qhttpengine-server |contentCompression|Enable Compressed Content Encoding for requests and responses| |false| |cppNamespace|C++ namespace (convention: name::space::for::api).| |OpenAPI| |ensureUniqueParams|Whether to ensure parameter names are unique in an operation (rename parameters that are not).| |true| +|legacyDiscriminatorBehavior|This flag is used by OpenAPITools codegen to influence the processing of the discriminator attribute in OpenAPI documents. This flag has no impact if the OAS document does not use the discriminator attribute. The default value of this flag is set in each language-specific code generator (e.g. Python, Java, go...)using the method toModelName. Note to developers supporting a language generator in OpenAPITools; to fully support the discriminator attribute as defined in the OAS specification 3.x, language generators should set this flag to true by default; however this requires updating the mustache templates to generate a language-specific discriminator lookup function that iterates over {{#mappedModels}} and does not iterate over {{children}}, {{#anyOf}}, or {{#oneOf}}.|
**true**
The mapping in the discriminator includes descendent schemas that allOf inherit from self and the discriminator mapping schemas in the OAS document.
**false**
The mapping in the discriminator includes any descendent schemas that allOf inherit from self, any oneOf schemas, any anyOf schemas, any x-discriminator-values, and the discriminator mapping schemas in the OAS document AND Codegen validates that oneOf and anyOf schemas contain the required discriminator and throws an error if the discriminator is missing.
|true| |modelNamePrefix|Prefix that will be prepended to all model names.| |OAI| |prependFormOrBodyParameters|Add form or body parameters to the beginning of the parameter list.| |false| |reservedWordPrefix|Prefix to prepend to reserved words in order to avoid conflicts| |r_| diff --git a/docs/generators/cpp-tizen.md b/docs/generators/cpp-tizen.md index f805721b5770..dd887f704784 100644 --- a/docs/generators/cpp-tizen.md +++ b/docs/generators/cpp-tizen.md @@ -7,6 +7,7 @@ sidebar_label: cpp-tizen | ------ | ----------- | ------ | ------- | |allowUnicodeIdentifiers|boolean, toggles whether unicode identifiers are allowed in names or not, default is false| |false| |ensureUniqueParams|Whether to ensure parameter names are unique in an operation (rename parameters that are not).| |true| +|legacyDiscriminatorBehavior|This flag is used by OpenAPITools codegen to influence the processing of the discriminator attribute in OpenAPI documents. This flag has no impact if the OAS document does not use the discriminator attribute. The default value of this flag is set in each language-specific code generator (e.g. Python, Java, go...)using the method toModelName. Note to developers supporting a language generator in OpenAPITools; to fully support the discriminator attribute as defined in the OAS specification 3.x, language generators should set this flag to true by default; however this requires updating the mustache templates to generate a language-specific discriminator lookup function that iterates over {{#mappedModels}} and does not iterate over {{children}}, {{#anyOf}}, or {{#oneOf}}.|
**true**
The mapping in the discriminator includes descendent schemas that allOf inherit from self and the discriminator mapping schemas in the OAS document.
**false**
The mapping in the discriminator includes any descendent schemas that allOf inherit from self, any oneOf schemas, any anyOf schemas, any x-discriminator-values, and the discriminator mapping schemas in the OAS document AND Codegen validates that oneOf and anyOf schemas contain the required discriminator and throws an error if the discriminator is missing.
|true| |prependFormOrBodyParameters|Add form or body parameters to the beginning of the parameter list.| |false| |reservedWordPrefix|Prefix to prepend to reserved words in order to avoid conflicts| |r_| |sortModelPropertiesByRequiredFlag|Sort model properties to place required parameters before optional parameters.| |true| diff --git a/docs/generators/csharp.md b/docs/generators/csharp.md index 9002b9f5a5ff..6928ef5f9e1b 100644 --- a/docs/generators/csharp.md +++ b/docs/generators/csharp.md @@ -23,7 +23,7 @@ sidebar_label: csharp |returnICollection|Return ICollection<T> instead of the concrete type.| |false| |sortParamsByRequiredFlag|Sort method arguments to place required parameters before optional parameters.| |true| |sourceFolder|source folder for generated code| |src| -|targetFramework|The target .NET framework version.|
**v3.5**
.NET Framework 3.5 compatible
**v4.0**
.NET Framework 4.0 compatible
**v4.5**
.NET Framework 4.5+ compatible
**v5.0**
.NET Standard 1.3 compatible (DEPRECATED. Please use `csharp-netcore` generator instead)
**uwp**
Universal Windows Platform (DEPRECATED. Please use `csharp-netcore` generator instead)
|v4.5| +|targetFramework|The target .NET framework version.|
**v3.5**
.NET Framework 3.5 compatible
**v4.0**
.NET Framework 4.0 compatible
**v4.5**
.NET Framework 4.5 compatible
**v4.5.2**
.NET Framework 4.5.2+ compatible
**v5.0**
.NET Standard 1.3 compatible (DEPRECATED. Please use `csharp-netcore` generator instead)
**uwp**
Universal Windows Platform (DEPRECATED. Please use `csharp-netcore` generator instead)
|v4.5| |useCollection|Deserialize array types to Collection<T> instead of List<T>.| |false| |useCompareNetObjects|Use KellermanSoftware.CompareNetObjects for deep recursive object comparison. WARNING: this option incurs potential performance impact.| |false| |useDateTimeOffset|Use DateTimeOffset to model date-time properties| |false| diff --git a/docs/generators/cwiki.md b/docs/generators/cwiki.md index f2d5342f8f36..2804a1bb2b8f 100644 --- a/docs/generators/cwiki.md +++ b/docs/generators/cwiki.md @@ -15,6 +15,7 @@ sidebar_label: cwiki |infoEmail|an email address to contact for inquiries about the application| |null| |infoUrl|a URL where users can get more information about the application| |null| |invokerPackage|root package for generated code| |null| +|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}}.|
**true**
The mapping in the discriminator includes descendent schemas that allOf inherit from self and the discriminator mapping schemas in the OAS document.
**false**
The mapping in the discriminator includes any descendent schemas that allOf inherit from self, any oneOf schemas, any anyOf schemas, any x-discriminator-values, and the discriminator mapping schemas in the OAS document AND Codegen validates that oneOf and anyOf schemas contain the required discriminator and throws an error if the discriminator is missing.
|true| |licenseInfo|a short description of the license| |null| |licenseUrl|a URL pointing to the full license| |null| |prependFormOrBodyParameters|Add form or body parameters to the beginning of the parameter list.| |false| diff --git a/docs/generators/dart-dio.md b/docs/generators/dart-dio.md index 05514b9a1e4e..5bab2b35a21d 100644 --- a/docs/generators/dart-dio.md +++ b/docs/generators/dart-dio.md @@ -9,6 +9,7 @@ sidebar_label: dart-dio |browserClient|Is the client browser based (for Dart 1.x only)| |null| |dateLibrary|Option. Date library to use|
**core**
Dart core library (DateTime)
**timemachine**
Time Machine is date and time library for Flutter, Web, and Server with support for timezones, calendars, cultures, formatting and parsing.
|core| |ensureUniqueParams|Whether to ensure parameter names are unique in an operation (rename parameters that are not).| |true| +|legacyDiscriminatorBehavior|This flag is used by OpenAPITools codegen to influence the processing of the discriminator attribute in OpenAPI documents. This flag has no impact if the OAS document does not use the discriminator attribute. The default value of this flag is set in each language-specific code generator (e.g. Python, Java, go...)using the method toModelName. Note to developers supporting a language generator in OpenAPITools; to fully support the discriminator attribute as defined in the OAS specification 3.x, language generators should set this flag to true by default; however this requires updating the mustache templates to generate a language-specific discriminator lookup function that iterates over {{#mappedModels}} and does not iterate over {{children}}, {{#anyOf}}, or {{#oneOf}}.|
**true**
The mapping in the discriminator includes descendent schemas that allOf inherit from self and the discriminator mapping schemas in the OAS document.
**false**
The mapping in the discriminator includes any descendent schemas that allOf inherit from self, any oneOf schemas, any anyOf schemas, any x-discriminator-values, and the discriminator mapping schemas in the OAS document AND Codegen validates that oneOf and anyOf schemas contain the required discriminator and throws an error if the discriminator is missing.
|true| |nullableFields|Is the null fields should be in the JSON payload| |null| |prependFormOrBodyParameters|Add form or body parameters to the beginning of the parameter list.| |false| |pubAuthor|Author name in generated pubspec| |null| diff --git a/docs/generators/dart-jaguar.md b/docs/generators/dart-jaguar.md index 5e81f82025f3..a23282c5095c 100644 --- a/docs/generators/dart-jaguar.md +++ b/docs/generators/dart-jaguar.md @@ -8,6 +8,7 @@ sidebar_label: dart-jaguar |allowUnicodeIdentifiers|boolean, toggles whether unicode identifiers are allowed in names or not, default is false| |false| |browserClient|Is the client browser based (for Dart 1.x only)| |null| |ensureUniqueParams|Whether to ensure parameter names are unique in an operation (rename parameters that are not).| |true| +|legacyDiscriminatorBehavior|This flag is used by OpenAPITools codegen to influence the processing of the discriminator attribute in OpenAPI documents. This flag has no impact if the OAS document does not use the discriminator attribute. The default value of this flag is set in each language-specific code generator (e.g. Python, Java, go...)using the method toModelName. Note to developers supporting a language generator in OpenAPITools; to fully support the discriminator attribute as defined in the OAS specification 3.x, language generators should set this flag to true by default; however this requires updating the mustache templates to generate a language-specific discriminator lookup function that iterates over {{#mappedModels}} and does not iterate over {{children}}, {{#anyOf}}, or {{#oneOf}}.|
**true**
The mapping in the discriminator includes descendent schemas that allOf inherit from self and the discriminator mapping schemas in the OAS document.
**false**
The mapping in the discriminator includes any descendent schemas that allOf inherit from self, any oneOf schemas, any anyOf schemas, any x-discriminator-values, and the discriminator mapping schemas in the OAS document AND Codegen validates that oneOf and anyOf schemas contain the required discriminator and throws an error if the discriminator is missing.
|true| |nullableFields|Is the null fields should be in the JSON payload| |null| |prependFormOrBodyParameters|Add form or body parameters to the beginning of the parameter list.| |false| |pubAuthor|Author name in generated pubspec| |null| diff --git a/docs/generators/dart.md b/docs/generators/dart.md index 993c31cf4477..b6ff9ba8eef8 100644 --- a/docs/generators/dart.md +++ b/docs/generators/dart.md @@ -8,6 +8,7 @@ sidebar_label: dart |allowUnicodeIdentifiers|boolean, toggles whether unicode identifiers are allowed in names or not, default is false| |false| |browserClient|Is the client browser based (for Dart 1.x only)| |null| |ensureUniqueParams|Whether to ensure parameter names are unique in an operation (rename parameters that are not).| |true| +|legacyDiscriminatorBehavior|This flag is used by OpenAPITools codegen to influence the processing of the discriminator attribute in OpenAPI documents. This flag has no impact if the OAS document does not use the discriminator attribute. The default value of this flag is set in each language-specific code generator (e.g. Python, Java, go...)using the method toModelName. Note to developers supporting a language generator in OpenAPITools; to fully support the discriminator attribute as defined in the OAS specification 3.x, language generators should set this flag to true by default; however this requires updating the mustache templates to generate a language-specific discriminator lookup function that iterates over {{#mappedModels}} and does not iterate over {{children}}, {{#anyOf}}, or {{#oneOf}}.|
**true**
The mapping in the discriminator includes descendent schemas that allOf inherit from self and the discriminator mapping schemas in the OAS document.
**false**
The mapping in the discriminator includes any descendent schemas that allOf inherit from self, any oneOf schemas, any anyOf schemas, any x-discriminator-values, and the discriminator mapping schemas in the OAS document AND Codegen validates that oneOf and anyOf schemas contain the required discriminator and throws an error if the discriminator is missing.
|true| |prependFormOrBodyParameters|Add form or body parameters to the beginning of the parameter list.| |false| |pubAuthor|Author name in generated pubspec| |null| |pubAuthorEmail|Email address of the author in generated pubspec| |null| diff --git a/docs/generators/dynamic-html.md b/docs/generators/dynamic-html.md index b252e414bdc8..9766b76b426f 100644 --- a/docs/generators/dynamic-html.md +++ b/docs/generators/dynamic-html.md @@ -11,6 +11,7 @@ sidebar_label: dynamic-html |ensureUniqueParams|Whether to ensure parameter names are unique in an operation (rename parameters that are not).| |true| |groupId|groupId in generated pom.xml| |null| |invokerPackage|root package for generated code| |null| +|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}}.|
**true**
The mapping in the discriminator includes descendent schemas that allOf inherit from self and the discriminator mapping schemas in the OAS document.
**false**
The mapping in the discriminator includes any descendent schemas that allOf inherit from self, any oneOf schemas, any anyOf schemas, any x-discriminator-values, and the discriminator mapping schemas in the OAS document AND Codegen validates that oneOf and anyOf schemas contain the required discriminator and throws an error if the discriminator is missing.
|true| |prependFormOrBodyParameters|Add form or body parameters to the beginning of the parameter list.| |false| |sortModelPropertiesByRequiredFlag|Sort model properties to place required parameters before optional parameters.| |true| |sortParamsByRequiredFlag|Sort method arguments to place required parameters before optional parameters.| |true| diff --git a/docs/generators/elixir.md b/docs/generators/elixir.md index 14afa95bc9fd..c13f447d0c89 100644 --- a/docs/generators/elixir.md +++ b/docs/generators/elixir.md @@ -8,6 +8,7 @@ sidebar_label: elixir |allowUnicodeIdentifiers|boolean, toggles whether unicode identifiers are allowed in names or not, default is false| |false| |ensureUniqueParams|Whether to ensure parameter names are unique in an operation (rename parameters that are not).| |true| |invokerPackage|The main namespace to use for all classes. e.g. Yay.Pets| |null| +|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}}.|
**true**
The mapping in the discriminator includes descendent schemas that allOf inherit from self and the discriminator mapping schemas in the OAS document.
**false**
The mapping in the discriminator includes any descendent schemas that allOf inherit from self, any oneOf schemas, any anyOf schemas, any x-discriminator-values, and the discriminator mapping schemas in the OAS document AND Codegen validates that oneOf and anyOf schemas contain the required discriminator and throws an error if the discriminator is missing.
|true| |licenseHeader|The license header to prepend to the top of all source files.| |null| |packageName|Elixir package name (convention: lowercase).| |null| |prependFormOrBodyParameters|Add form or body parameters to the beginning of the parameter list.| |false| diff --git a/docs/generators/fsharp-functions.md b/docs/generators/fsharp-functions.md index a7e28602b33e..07b7aa3ded2b 100644 --- a/docs/generators/fsharp-functions.md +++ b/docs/generators/fsharp-functions.md @@ -7,6 +7,7 @@ sidebar_label: fsharp-functions | ------ | ----------- | ------ | ------- | |allowUnicodeIdentifiers|boolean, toggles whether unicode identifiers are allowed in names or not, default is false| |false| |ensureUniqueParams|Whether to ensure parameter names are unique in an operation (rename parameters that are not).| |true| +|legacyDiscriminatorBehavior|This flag is used by OpenAPITools codegen to influence the processing of the discriminator attribute in OpenAPI documents. This flag has no impact if the OAS document does not use the discriminator attribute. The default value of this flag is set in each language-specific code generator (e.g. Python, Java, go...)using the method toModelName. Note to developers supporting a language generator in OpenAPITools; to fully support the discriminator attribute as defined in the OAS specification 3.x, language generators should set this flag to true by default; however this requires updating the mustache templates to generate a language-specific discriminator lookup function that iterates over {{#mappedModels}} and does not iterate over {{children}}, {{#anyOf}}, or {{#oneOf}}.|
**true**
The mapping in the discriminator includes descendent schemas that allOf inherit from self and the discriminator mapping schemas in the OAS document.
**false**
The mapping in the discriminator includes any descendent schemas that allOf inherit from self, any oneOf schemas, any anyOf schemas, any x-discriminator-values, and the discriminator mapping schemas in the OAS document AND Codegen validates that oneOf and anyOf schemas contain the required discriminator and throws an error if the discriminator is missing.
|true| |licenseName|The name of the license| |NoLicense| |licenseUrl|The URL of the license| |http://localhost| |packageAuthors|Specifies Authors property in the .NET Core project file.| |OpenAPI| diff --git a/docs/generators/groovy.md b/docs/generators/groovy.md index 0fd5f1222443..399aa7f5fcbb 100644 --- a/docs/generators/groovy.md +++ b/docs/generators/groovy.md @@ -18,12 +18,14 @@ sidebar_label: groovy |developerOrganization|developer organization in generated pom.xml| |OpenAPITools.org| |developerOrganizationUrl|developer organization URL in generated pom.xml| |http://openapitools.org| |disableHtmlEscaping|Disable HTML escaping of JSON strings when using gson (needed to avoid problems with byte[] fields)| |false| +|discriminatorCaseSensitive|Whether the discriminator value lookup should be case-sensitive or not. This option only works for Java API client| |true| |ensureUniqueParams|Whether to ensure parameter names are unique in an operation (rename parameters that are not).| |true| |fullJavaUtil|whether to use fully qualified name for classes under java.util. This option only works for Java API client| |false| |groupId|groupId in generated pom.xml| |org.openapitools| |hideGenerationTimestamp|Hides the generation timestamp when files are generated.| |false| |invokerPackage|root package for generated code| |org.openapitools.api| |java8|Option. Use Java8 classes instead of third party equivalents|
**true**
Use Java 8 classes such as Base64
**false**
Various third party libraries as needed
|false| +|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}}.|
**true**
The mapping in the discriminator includes descendent schemas that allOf inherit from self and the discriminator mapping schemas in the OAS document.
**false**
The mapping in the discriminator includes any descendent schemas that allOf inherit from self, any oneOf schemas, any anyOf schemas, any x-discriminator-values, and the discriminator mapping schemas in the OAS document AND Codegen validates that oneOf and anyOf schemas contain the required discriminator and throws an error if the discriminator is missing.
|true| |licenseName|The name of the license| |Unlicense| |licenseUrl|The URL of the license| |http://unlicense.org| |modelPackage|package for generated models| |org.openapitools.model| diff --git a/docs/generators/haskell-http-client.md b/docs/generators/haskell-http-client.md index 41163e8fa883..a1ecfc5a4b04 100644 --- a/docs/generators/haskell-http-client.md +++ b/docs/generators/haskell-http-client.md @@ -24,6 +24,7 @@ sidebar_label: haskell-http-client |generateModelConstructors|Generate smart constructors (only supply required fields) for models| |true| |hideGenerationTimestamp|Hides the generation timestamp when files are generated.| |true| |inlineMimeTypes|Inline (hardcode) the content-type and accept parameters on operations, when there is only 1 option| |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}}.|
**true**
The mapping in the discriminator includes descendent schemas that allOf inherit from self and the discriminator mapping schemas in the OAS document.
**false**
The mapping in the discriminator includes any descendent schemas that allOf inherit from self, any oneOf schemas, any anyOf schemas, any x-discriminator-values, and the discriminator mapping schemas in the OAS document AND Codegen validates that oneOf and anyOf schemas contain the required discriminator and throws an error if the discriminator is missing.
|true| |modelDeriving|Additional classes to include in the deriving() clause of Models| |null| |prependFormOrBodyParameters|Add form or body parameters to the beginning of the parameter list.| |false| |requestType|Set the name of the type used to generate requests| |null| diff --git a/docs/generators/haskell.md b/docs/generators/haskell.md index 2e35a073d890..1fef8d922d29 100644 --- a/docs/generators/haskell.md +++ b/docs/generators/haskell.md @@ -8,6 +8,7 @@ sidebar_label: haskell |allowUnicodeIdentifiers|boolean, toggles whether unicode identifiers are allowed in names or not, default is false| |false| |apiPackage|package for generated api classes| |null| |ensureUniqueParams|Whether to ensure parameter names are unique in an operation (rename parameters that are not).| |true| +|legacyDiscriminatorBehavior|This flag is used by OpenAPITools codegen to influence the processing of the discriminator attribute in OpenAPI documents. This flag has no impact if the OAS document does not use the discriminator attribute. The default value of this flag is set in each language-specific code generator (e.g. Python, Java, go...)using the method toModelName. Note to developers supporting a language generator in OpenAPITools; to fully support the discriminator attribute as defined in the OAS specification 3.x, language generators should set this flag to true by default; however this requires updating the mustache templates to generate a language-specific discriminator lookup function that iterates over {{#mappedModels}} and does not iterate over {{children}}, {{#anyOf}}, or {{#oneOf}}.|
**true**
The mapping in the discriminator includes descendent schemas that allOf inherit from self and the discriminator mapping schemas in the OAS document.
**false**
The mapping in the discriminator includes any descendent schemas that allOf inherit from self, any oneOf schemas, any anyOf schemas, any x-discriminator-values, and the discriminator mapping schemas in the OAS document AND Codegen validates that oneOf and anyOf schemas contain the required discriminator and throws an error if the discriminator is missing.
|true| |modelPackage|package for generated models| |null| |prependFormOrBodyParameters|Add form or body parameters to the beginning of the parameter list.| |false| |serveStatic|serve will serve files from the directory 'static'.| |true| diff --git a/docs/generators/html.md b/docs/generators/html.md index 78cef65b33b9..b5603e1888aa 100644 --- a/docs/generators/html.md +++ b/docs/generators/html.md @@ -15,6 +15,7 @@ sidebar_label: html |infoEmail|an email address to contact for inquiries about the application| |null| |infoUrl|a URL where users can get more information about the application| |null| |invokerPackage|root package for generated code| |null| +|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}}.|
**true**
The mapping in the discriminator includes descendent schemas that allOf inherit from self and the discriminator mapping schemas in the OAS document.
**false**
The mapping in the discriminator includes any descendent schemas that allOf inherit from self, any oneOf schemas, any anyOf schemas, any x-discriminator-values, and the discriminator mapping schemas in the OAS document AND Codegen validates that oneOf and anyOf schemas contain the required discriminator and throws an error if the discriminator is missing.
|true| |licenseInfo|a short description of the license| |null| |licenseUrl|a URL pointing to the full license| |null| |prependFormOrBodyParameters|Add form or body parameters to the beginning of the parameter list.| |false| diff --git a/docs/generators/html2.md b/docs/generators/html2.md index 51d39c72a7d4..6641bcfa3e49 100644 --- a/docs/generators/html2.md +++ b/docs/generators/html2.md @@ -15,6 +15,7 @@ sidebar_label: html2 |infoEmail|an email address to contact for inquiries about the application| |null| |infoUrl|a URL where users can get more information about the application| |null| |invokerPackage|root package for generated code| |null| +|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}}.|
**true**
The mapping in the discriminator includes descendent schemas that allOf inherit from self and the discriminator mapping schemas in the OAS document.
**false**
The mapping in the discriminator includes any descendent schemas that allOf inherit from self, any oneOf schemas, any anyOf schemas, any x-discriminator-values, and the discriminator mapping schemas in the OAS document AND Codegen validates that oneOf and anyOf schemas contain the required discriminator and throws an error if the discriminator is missing.
|true| |licenseInfo|a short description of the license| |null| |licenseUrl|a URL pointing to the full license| |null| |packageName|C# package name| |null| diff --git a/docs/generators/java-inflector.md b/docs/generators/java-inflector.md index 2201f355bd7c..47c60b6f501a 100644 --- a/docs/generators/java-inflector.md +++ b/docs/generators/java-inflector.md @@ -20,12 +20,14 @@ sidebar_label: java-inflector |developerOrganization|developer organization in generated pom.xml| |OpenAPITools.org| |developerOrganizationUrl|developer organization URL in generated pom.xml| |http://openapitools.org| |disableHtmlEscaping|Disable HTML escaping of JSON strings when using gson (needed to avoid problems with byte[] fields)| |false| +|discriminatorCaseSensitive|Whether the discriminator value lookup should be case-sensitive or not. This option only works for Java API client| |true| |ensureUniqueParams|Whether to ensure parameter names are unique in an operation (rename parameters that are not).| |true| |fullJavaUtil|whether to use fully qualified name for classes under java.util. This option only works for Java API client| |false| |groupId|groupId in generated pom.xml| |org.openapitools| |hideGenerationTimestamp|Hides the generation timestamp when files are generated.| |false| |invokerPackage|root package for generated code| |org.openapitools.controllers| |java8|Option. Use Java8 classes instead of third party equivalents|
**true**
Use Java 8 classes such as Base64
**false**
Various third party libraries as needed
|false| +|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}}.|
**true**
The mapping in the discriminator includes descendent schemas that allOf inherit from self and the discriminator mapping schemas in the OAS document.
**false**
The mapping in the discriminator includes any descendent schemas that allOf inherit from self, any oneOf schemas, any anyOf schemas, any x-discriminator-values, and the discriminator mapping schemas in the OAS document AND Codegen validates that oneOf and anyOf schemas contain the required discriminator and throws an error if the discriminator is missing.
|true| |licenseName|The name of the license| |Unlicense| |licenseUrl|The URL of the license| |http://unlicense.org| |modelPackage|package for generated models| |org.openapitools.model| diff --git a/docs/generators/java-msf4j.md b/docs/generators/java-msf4j.md index 054bf625590f..7b37f5dd9a6e 100644 --- a/docs/generators/java-msf4j.md +++ b/docs/generators/java-msf4j.md @@ -20,6 +20,7 @@ sidebar_label: java-msf4j |developerOrganization|developer organization in generated pom.xml| |OpenAPITools.org| |developerOrganizationUrl|developer organization URL in generated pom.xml| |http://openapitools.org| |disableHtmlEscaping|Disable HTML escaping of JSON strings when using gson (needed to avoid problems with byte[] fields)| |false| +|discriminatorCaseSensitive|Whether the discriminator value lookup should be case-sensitive or not. This option only works for Java API client| |true| |ensureUniqueParams|Whether to ensure parameter names are unique in an operation (rename parameters that are not).| |true| |fullJavaUtil|whether to use fully qualified name for classes under java.util. This option only works for Java API client| |false| |groupId|groupId in generated pom.xml| |org.openapitools| @@ -27,6 +28,7 @@ sidebar_label: java-msf4j |implFolder|folder for generated implementation code| |src/main/java| |invokerPackage|root package for generated code| |org.openapitools.api| |java8|Option. Use Java8 classes instead of third party equivalents|
**true**
Use Java 8 classes such as Base64
**false**
Various third party libraries as needed
|false| +|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}}.|
**true**
The mapping in the discriminator includes descendent schemas that allOf inherit from self and the discriminator mapping schemas in the OAS document.
**false**
The mapping in the discriminator includes any descendent schemas that allOf inherit from self, any oneOf schemas, any anyOf schemas, any x-discriminator-values, and the discriminator mapping schemas in the OAS document AND Codegen validates that oneOf and anyOf schemas contain the required discriminator and throws an error if the discriminator is missing.
|true| |library|library template (sub-template)|
**jersey1**
Jersey core 1.x
**jersey2**
Jersey core 2.x
|jersey2| |licenseName|The name of the license| |Unlicense| |licenseUrl|The URL of the license| |http://unlicense.org| diff --git a/docs/generators/java-pkmst.md b/docs/generators/java-pkmst.md index 5b547df3b052..a78d000aa76d 100644 --- a/docs/generators/java-pkmst.md +++ b/docs/generators/java-pkmst.md @@ -21,6 +21,7 @@ sidebar_label: java-pkmst |developerOrganization|developer organization in generated pom.xml| |OpenAPITools.org| |developerOrganizationUrl|developer organization URL in generated pom.xml| |http://openapitools.org| |disableHtmlEscaping|Disable HTML escaping of JSON strings when using gson (needed to avoid problems with byte[] fields)| |false| +|discriminatorCaseSensitive|Whether the discriminator value lookup should be case-sensitive or not. This option only works for Java API client| |true| |ensureUniqueParams|Whether to ensure parameter names are unique in an operation (rename parameters that are not).| |true| |eurekaUri|Eureka URI| |null| |fullJavaUtil|whether to use fully qualified name for classes under java.util. This option only works for Java API client| |false| @@ -28,6 +29,7 @@ sidebar_label: java-pkmst |hideGenerationTimestamp|Hides the generation timestamp when files are generated.| |false| |invokerPackage|root package for generated code| |com.prokarma.pkmst.controller| |java8|Option. Use Java8 classes instead of third party equivalents|
**true**
Use Java 8 classes such as Base64
**false**
Various third party libraries as needed
|false| +|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}}.|
**true**
The mapping in the discriminator includes descendent schemas that allOf inherit from self and the discriminator mapping schemas in the OAS document.
**false**
The mapping in the discriminator includes any descendent schemas that allOf inherit from self, any oneOf schemas, any anyOf schemas, any x-discriminator-values, and the discriminator mapping schemas in the OAS document AND Codegen validates that oneOf and anyOf schemas contain the required discriminator and throws an error if the discriminator is missing.
|true| |licenseName|The name of the license| |Unlicense| |licenseUrl|The URL of the license| |http://unlicense.org| |modelPackage|package for generated models| |com.prokarma.pkmst.model| diff --git a/docs/generators/java-play-framework.md b/docs/generators/java-play-framework.md index 923d2a16afaf..47dc598c83c2 100644 --- a/docs/generators/java-play-framework.md +++ b/docs/generators/java-play-framework.md @@ -23,6 +23,7 @@ sidebar_label: java-play-framework |developerOrganization|developer organization in generated pom.xml| |OpenAPITools.org| |developerOrganizationUrl|developer organization URL in generated pom.xml| |http://openapitools.org| |disableHtmlEscaping|Disable HTML escaping of JSON strings when using gson (needed to avoid problems with byte[] fields)| |false| +|discriminatorCaseSensitive|Whether the discriminator value lookup should be case-sensitive or not. This option only works for Java API client| |true| |ensureUniqueParams|Whether to ensure parameter names are unique in an operation (rename parameters that are not).| |true| |fullJavaUtil|whether to use fully qualified name for classes under java.util. This option only works for Java API client| |false| |groupId|groupId in generated pom.xml| |org.openapitools| @@ -30,6 +31,7 @@ sidebar_label: java-play-framework |hideGenerationTimestamp|Hides the generation timestamp when files are generated.| |false| |invokerPackage|root package for generated code| |org.openapitools.api| |java8|Option. Use Java8 classes instead of third party equivalents|
**true**
Use Java 8 classes such as Base64
**false**
Various third party libraries as needed
|false| +|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}}.|
**true**
The mapping in the discriminator includes descendent schemas that allOf inherit from self and the discriminator mapping schemas in the OAS document.
**false**
The mapping in the discriminator includes any descendent schemas that allOf inherit from self, any oneOf schemas, any anyOf schemas, any x-discriminator-values, and the discriminator mapping schemas in the OAS document AND Codegen validates that oneOf and anyOf schemas contain the required discriminator and throws an error if the discriminator is missing.
|true| |licenseName|The name of the license| |Unlicense| |licenseUrl|The URL of the license| |http://unlicense.org| |modelPackage|package for generated models| |apimodels| diff --git a/docs/generators/java-undertow-server.md b/docs/generators/java-undertow-server.md index 188cea719fc5..641ed21d2c5e 100644 --- a/docs/generators/java-undertow-server.md +++ b/docs/generators/java-undertow-server.md @@ -20,12 +20,14 @@ sidebar_label: java-undertow-server |developerOrganization|developer organization in generated pom.xml| |OpenAPITools.org| |developerOrganizationUrl|developer organization URL in generated pom.xml| |http://openapitools.org| |disableHtmlEscaping|Disable HTML escaping of JSON strings when using gson (needed to avoid problems with byte[] fields)| |false| +|discriminatorCaseSensitive|Whether the discriminator value lookup should be case-sensitive or not. This option only works for Java API client| |true| |ensureUniqueParams|Whether to ensure parameter names are unique in an operation (rename parameters that are not).| |true| |fullJavaUtil|whether to use fully qualified name for classes under java.util. This option only works for Java API client| |false| |groupId|groupId in generated pom.xml| |org.openapitools| |hideGenerationTimestamp|Hides the generation timestamp when files are generated.| |false| |invokerPackage|root package for generated code| |org.openapitools.handler| |java8|Option. Use Java8 classes instead of third party equivalents|
**true**
Use Java 8 classes such as Base64
**false**
Various third party libraries as needed
|false| +|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}}.|
**true**
The mapping in the discriminator includes descendent schemas that allOf inherit from self and the discriminator mapping schemas in the OAS document.
**false**
The mapping in the discriminator includes any descendent schemas that allOf inherit from self, any oneOf schemas, any anyOf schemas, any x-discriminator-values, and the discriminator mapping schemas in the OAS document AND Codegen validates that oneOf and anyOf schemas contain the required discriminator and throws an error if the discriminator is missing.
|true| |licenseName|The name of the license| |Unlicense| |licenseUrl|The URL of the license| |http://unlicense.org| |modelPackage|package for generated models| |null| diff --git a/docs/generators/java-vertx-web.md b/docs/generators/java-vertx-web.md index b3896623ab1b..1fe08d3b107c 100644 --- a/docs/generators/java-vertx-web.md +++ b/docs/generators/java-vertx-web.md @@ -20,12 +20,14 @@ sidebar_label: java-vertx-web |developerOrganization|developer organization in generated pom.xml| |OpenAPITools.org| |developerOrganizationUrl|developer organization URL in generated pom.xml| |http://openapitools.org| |disableHtmlEscaping|Disable HTML escaping of JSON strings when using gson (needed to avoid problems with byte[] fields)| |false| +|discriminatorCaseSensitive|Whether the discriminator value lookup should be case-sensitive or not. This option only works for Java API client| |true| |ensureUniqueParams|Whether to ensure parameter names are unique in an operation (rename parameters that are not).| |true| |fullJavaUtil|whether to use fully qualified name for classes under java.util. This option only works for Java API client| |false| |groupId|groupId in generated pom.xml| |org.openapitools| |hideGenerationTimestamp|Hides the generation timestamp when files are generated.| |false| |invokerPackage|root package for generated code| |org.openapitools.vertxweb.server| |java8|Option. Use Java8 classes instead of third party equivalents|
**true**
Use Java 8 classes such as Base64
**false**
Various third party libraries as needed
|false| +|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}}.|
**true**
The mapping in the discriminator includes descendent schemas that allOf inherit from self and the discriminator mapping schemas in the OAS document.
**false**
The mapping in the discriminator includes any descendent schemas that allOf inherit from self, any oneOf schemas, any anyOf schemas, any x-discriminator-values, and the discriminator mapping schemas in the OAS document AND Codegen validates that oneOf and anyOf schemas contain the required discriminator and throws an error if the discriminator is missing.
|true| |licenseName|The name of the license| |Unlicense| |licenseUrl|The URL of the license| |http://unlicense.org| |modelPackage|package for generated models| |org.openapitools.vertxweb.server.model| diff --git a/docs/generators/java-vertx.md b/docs/generators/java-vertx.md index a6cd8ed7b85b..e2d68f9c5e31 100644 --- a/docs/generators/java-vertx.md +++ b/docs/generators/java-vertx.md @@ -20,12 +20,14 @@ sidebar_label: java-vertx |developerOrganization|developer organization in generated pom.xml| |OpenAPITools.org| |developerOrganizationUrl|developer organization URL in generated pom.xml| |http://openapitools.org| |disableHtmlEscaping|Disable HTML escaping of JSON strings when using gson (needed to avoid problems with byte[] fields)| |false| +|discriminatorCaseSensitive|Whether the discriminator value lookup should be case-sensitive or not. This option only works for Java API client| |true| |ensureUniqueParams|Whether to ensure parameter names are unique in an operation (rename parameters that are not).| |true| |fullJavaUtil|whether to use fully qualified name for classes under java.util. This option only works for Java API client| |false| |groupId|groupId in generated pom.xml| |org.openapitools| |hideGenerationTimestamp|Hides the generation timestamp when files are generated.| |false| |invokerPackage|root package for generated code| |org.openapitools| |java8|Option. Use Java8 classes instead of third party equivalents|
**true**
Use Java 8 classes such as Base64
**false**
Various third party libraries as needed
|false| +|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}}.|
**true**
The mapping in the discriminator includes descendent schemas that allOf inherit from self and the discriminator mapping schemas in the OAS document.
**false**
The mapping in the discriminator includes any descendent schemas that allOf inherit from self, any oneOf schemas, any anyOf schemas, any x-discriminator-values, and the discriminator mapping schemas in the OAS document AND Codegen validates that oneOf and anyOf schemas contain the required discriminator and throws an error if the discriminator is missing.
|true| |licenseName|The name of the license| |Unlicense| |licenseUrl|The URL of the license| |http://unlicense.org| |modelPackage|package for generated models| |org.openapitools.server.api.model| diff --git a/docs/generators/java.md b/docs/generators/java.md index c97d5e24d4e3..c1e25a2055e4 100644 --- a/docs/generators/java.md +++ b/docs/generators/java.md @@ -21,6 +21,7 @@ sidebar_label: java |developerOrganization|developer organization in generated pom.xml| |OpenAPITools.org| |developerOrganizationUrl|developer organization URL in generated pom.xml| |http://openapitools.org| |disableHtmlEscaping|Disable HTML escaping of JSON strings when using gson (needed to avoid problems with byte[] fields)| |false| +|discriminatorCaseSensitive|Whether the discriminator value lookup should be case-sensitive or not. This option only works for Java API client| |true| |ensureUniqueParams|Whether to ensure parameter names are unique in an operation (rename parameters that are not).| |true| |feignVersion|Version of OpenFeign: '10.x' (default), '9.x' (deprecated)| |false| |fullJavaUtil|whether to use fully qualified name for classes under java.util. This option only works for Java API client| |false| @@ -28,7 +29,8 @@ sidebar_label: java |hideGenerationTimestamp|Hides the generation timestamp when files are generated.| |false| |invokerPackage|root package for generated code| |org.openapitools.client| |java8|Option. Use Java8 classes instead of third party equivalents|
**true**
Use Java 8 classes such as Base64
**false**
Various third party libraries as needed
|false| -|library|library template (sub-template) to use|
**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.
**jersey2**
HTTP client: Jersey client 2.25.1. JSON processing: Jackson 2.9.x
**feign**
HTTP client: OpenFeign 9.x (deprecated) or 10.x (default). JSON processing: Jackson 2.9.x.
**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'.
**retrofit**
HTTP client: OkHttp 2.x. JSON processing: Gson 2.x (Retrofit 1.9.0). IMPORTANT NOTE: retrofit1.x is no longer actively maintained so please upgrade to 'retrofit2' instead.
**retrofit2**
HTTP client: OkHttp 3.x. JSON processing: Gson 2.x (Retrofit 2.3.0). Enable the RxJava adapter using '-DuseRxJava[2]=true'. (RxJava 1.x or 2.x)
**resttemplate**
HTTP client: Spring RestTemplate 4.x. JSON processing: Jackson 2.9.x
**webclient**
HTTP client: Spring WebClient 5.x. JSON processing: Jackson 2.9.x
**resteasy**
HTTP client: Resteasy client 3.x. JSON processing: Jackson 2.9.x
**vertx**
HTTP client: VertX client 3.x. JSON processing: Jackson 2.9.x
**google-api-client**
HTTP client: Google API client 1.x. JSON processing: Jackson 2.9.x
**rest-assured**
HTTP client: rest-assured : 4.x. JSON processing: Gson 2.x or Jackson 2.9.x. Only for Java8
**native**
HTTP client: Java native HttpClient. JSON processing: Jackson 2.9.x. Only for Java11+
**microprofile**
HTTP client: Microprofile client X.x. JSON processing: Jackson 2.9.x
|okhttp-gson| +|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}}.|
**true**
The mapping in the discriminator includes descendent schemas that allOf inherit from self and the discriminator mapping schemas in the OAS document.
**false**
The mapping in the discriminator includes any descendent schemas that allOf inherit from self, any oneOf schemas, any anyOf schemas, any x-discriminator-values, and the discriminator mapping schemas in the OAS document AND Codegen validates that oneOf and anyOf schemas contain the required discriminator and throws an error if the discriminator is missing.
|true| +|library|library template (sub-template) to use|
**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.
**jersey2**
HTTP client: Jersey client 2.25.1. JSON processing: Jackson 2.9.x
**jersey2-experimental**
HTTP client: Jersey client 2.25.1. JSON processing: Jackson 2.9.x
**feign**
HTTP client: OpenFeign 9.x (deprecated) or 10.x (default). JSON processing: Jackson 2.9.x.
**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'.
**retrofit**
HTTP client: OkHttp 2.x. JSON processing: Gson 2.x (Retrofit 1.9.0). IMPORTANT NOTE: retrofit1.x is no longer actively maintained so please upgrade to 'retrofit2' instead.
**retrofit2**
HTTP client: OkHttp 3.x. JSON processing: Gson 2.x (Retrofit 2.3.0). Enable the RxJava adapter using '-DuseRxJava[2]=true'. (RxJava 1.x or 2.x)
**resttemplate**
HTTP client: Spring RestTemplate 4.x. JSON processing: Jackson 2.9.x
**webclient**
HTTP client: Spring WebClient 5.x. JSON processing: Jackson 2.9.x
**resteasy**
HTTP client: Resteasy client 3.x. JSON processing: Jackson 2.9.x
**vertx**
HTTP client: VertX client 3.x. JSON processing: Jackson 2.9.x
**google-api-client**
HTTP client: Google API client 1.x. JSON processing: Jackson 2.9.x
**rest-assured**
HTTP client: rest-assured : 4.x. JSON processing: Gson 2.x or Jackson 2.10.x. Only for Java 8
**native**
HTTP client: Java native HttpClient. JSON processing: Jackson 2.9.x. Only for Java11+
**microprofile**
HTTP client: Microprofile client X.x. JSON processing: Jackson 2.9.x
|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| diff --git a/docs/generators/javascript-apollo.md b/docs/generators/javascript-apollo.md index 44cad073fd8d..ca26bb0c0616 100644 --- a/docs/generators/javascript-apollo.md +++ b/docs/generators/javascript-apollo.md @@ -11,6 +11,7 @@ sidebar_label: javascript-apollo |ensureUniqueParams|Whether to ensure parameter names are unique in an operation (rename parameters that are not).| |true| |hideGenerationTimestamp|Hides the generation timestamp when files are generated.| |true| |invokerPackage|root package for generated code| |null| +|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}}.|
**true**
The mapping in the discriminator includes descendent schemas that allOf inherit from self and the discriminator mapping schemas in the OAS document.
**false**
The mapping in the discriminator includes any descendent schemas that allOf inherit from self, any oneOf schemas, any anyOf schemas, any x-discriminator-values, and the discriminator mapping schemas in the OAS document AND Codegen validates that oneOf and anyOf schemas contain the required discriminator and throws an error if the discriminator is missing.
|true| |licenseName|name of the license the project uses (Default: using info.license.name)| |null| |modelPackage|package for generated models| |null| |modelPropertyNaming|Naming convention for the property: 'camelCase', 'PascalCase', 'snake_case' and 'original', which keeps the original name| |camelCase| diff --git a/docs/generators/javascript-closure-angular.md b/docs/generators/javascript-closure-angular.md index 89b3bd9b0ffe..e870e567eaca 100644 --- a/docs/generators/javascript-closure-angular.md +++ b/docs/generators/javascript-closure-angular.md @@ -8,6 +8,7 @@ sidebar_label: javascript-closure-angular |allowUnicodeIdentifiers|boolean, toggles whether unicode identifiers are allowed in names or not, default is false| |false| |ensureUniqueParams|Whether to ensure parameter names are unique in an operation (rename parameters that are not).| |true| |hideGenerationTimestamp|Hides the generation timestamp when files are generated.| |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}}.|
**true**
The mapping in the discriminator includes descendent schemas that allOf inherit from self and the discriminator mapping schemas in the OAS document.
**false**
The mapping in the discriminator includes any descendent schemas that allOf inherit from self, any oneOf schemas, any anyOf schemas, any x-discriminator-values, and the discriminator mapping schemas in the OAS document AND Codegen validates that oneOf and anyOf schemas contain the required discriminator and throws an error if the discriminator is missing.
|true| |prependFormOrBodyParameters|Add form or body parameters to the beginning of the parameter list.| |false| |sortModelPropertiesByRequiredFlag|Sort model properties to place required parameters before optional parameters.| |true| |sortParamsByRequiredFlag|Sort method arguments to place required parameters before optional parameters.| |true| diff --git a/docs/generators/javascript-flowtyped.md b/docs/generators/javascript-flowtyped.md index 6ecd6654d10d..d0a0a709985a 100644 --- a/docs/generators/javascript-flowtyped.md +++ b/docs/generators/javascript-flowtyped.md @@ -9,6 +9,7 @@ sidebar_label: javascript-flowtyped |ensureUniqueParams|Whether to ensure parameter names are unique in an operation (rename parameters that are not).| |true| |enumNameSuffix|Suffix that will be appended to all enum names. A special 'v4-compat' value enables the backward-compatible behavior (as pre v4.2.3)| |v4-compat| |enumPropertyNaming|Naming convention for enum properties: 'camelCase', 'PascalCase', 'snake_case', 'UPPERCASE', and 'original'| |PascalCase| +|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}}.|
**true**
The mapping in the discriminator includes descendent schemas that allOf inherit from self and the discriminator mapping schemas in the OAS document.
**false**
The mapping in the discriminator includes any descendent schemas that allOf inherit from self, any oneOf schemas, any anyOf schemas, any x-discriminator-values, and the discriminator mapping schemas in the OAS document AND Codegen validates that oneOf and anyOf schemas contain the required discriminator and throws an error if the discriminator is missing.
|true| |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| |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| diff --git a/docs/generators/javascript.md b/docs/generators/javascript.md index 1181fffa500f..49dabe82ea2e 100644 --- a/docs/generators/javascript.md +++ b/docs/generators/javascript.md @@ -12,6 +12,7 @@ sidebar_label: javascript |ensureUniqueParams|Whether to ensure parameter names are unique in an operation (rename parameters that are not).| |true| |hideGenerationTimestamp|Hides the generation timestamp when files are generated.| |true| |invokerPackage|root package for generated code| |null| +|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}}.|
**true**
The mapping in the discriminator includes descendent schemas that allOf inherit from self and the discriminator mapping schemas in the OAS document.
**false**
The mapping in the discriminator includes any descendent schemas that allOf inherit from self, any oneOf schemas, any anyOf schemas, any x-discriminator-values, and the discriminator mapping schemas in the OAS document AND Codegen validates that oneOf and anyOf schemas contain the required discriminator and throws an error if the discriminator is missing.
|true| |licenseName|name of the license the project uses (Default: using info.license.name)| |null| |modelPackage|package for generated models| |null| |modelPropertyNaming|Naming convention for the property: 'camelCase', 'PascalCase', 'snake_case' and 'original', which keeps the original name| |camelCase| diff --git a/docs/generators/jaxrs-cxf-cdi.md b/docs/generators/jaxrs-cxf-cdi.md index 501f8ced3cbb..dbb740fd3741 100644 --- a/docs/generators/jaxrs-cxf-cdi.md +++ b/docs/generators/jaxrs-cxf-cdi.md @@ -20,8 +20,10 @@ sidebar_label: jaxrs-cxf-cdi |developerOrganization|developer organization in generated pom.xml| |OpenAPITools.org| |developerOrganizationUrl|developer organization URL in generated pom.xml| |http://openapitools.org| |disableHtmlEscaping|Disable HTML escaping of JSON strings when using gson (needed to avoid problems with byte[] fields)| |false| +|discriminatorCaseSensitive|Whether the discriminator value lookup should be case-sensitive or not. This option only works for Java API client| |true| |ensureUniqueParams|Whether to ensure parameter names are unique in an operation (rename parameters that are not).| |true| |fullJavaUtil|whether to use fully qualified name for classes under java.util. This option only works for Java API client| |false| +|generateBuilders|Whether to generate builders for models.| |false| |generatePom|Whether to generate pom.xml if the file does not already exist.| |true| |groupId|groupId in generated pom.xml| |org.openapitools| |hideGenerationTimestamp|Hides the generation timestamp when files are generated.| |false| @@ -29,6 +31,7 @@ sidebar_label: jaxrs-cxf-cdi |interfaceOnly|Whether to generate only API interface stubs without the server files.| |false| |invokerPackage|root package for generated code| |org.openapitools.api| |java8|Option. Use Java8 classes instead of third party equivalents|
**true**
Use Java 8 classes such as Base64
**false**
Various third party libraries as needed
|false| +|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}}.|
**true**
The mapping in the discriminator includes descendent schemas that allOf inherit from self and the discriminator mapping schemas in the OAS document.
**false**
The mapping in the discriminator includes any descendent schemas that allOf inherit from self, any oneOf schemas, any anyOf schemas, any x-discriminator-values, and the discriminator mapping schemas in the OAS document AND Codegen validates that oneOf and anyOf schemas contain the required discriminator and throws an error if the discriminator is missing.
|true| |library|library template (sub-template)|
**<default>**
JAXRS spec only, to be deployed in an app server (TomEE, JBoss, WLS, ...)
**quarkus**
Server using Quarkus
**thorntail**
Server using Thorntail
**openliberty**
Server using Open Liberty
**helidon**
Server using Helidon
|<default>| |licenseName|The name of the license| |Unlicense| |licenseUrl|The URL of the license| |http://unlicense.org| diff --git a/docs/generators/jaxrs-cxf-client.md b/docs/generators/jaxrs-cxf-client.md index e816515ab192..41b28b8bc0b8 100644 --- a/docs/generators/jaxrs-cxf-client.md +++ b/docs/generators/jaxrs-cxf-client.md @@ -20,12 +20,14 @@ sidebar_label: jaxrs-cxf-client |developerOrganization|developer organization in generated pom.xml| |OpenAPITools.org| |developerOrganizationUrl|developer organization URL in generated pom.xml| |http://openapitools.org| |disableHtmlEscaping|Disable HTML escaping of JSON strings when using gson (needed to avoid problems with byte[] fields)| |false| +|discriminatorCaseSensitive|Whether the discriminator value lookup should be case-sensitive or not. This option only works for Java API client| |true| |ensureUniqueParams|Whether to ensure parameter names are unique in an operation (rename parameters that are not).| |true| |fullJavaUtil|whether to use fully qualified name for classes under java.util. This option only works for Java API client| |false| |groupId|groupId in generated pom.xml| |org.openapitools| |hideGenerationTimestamp|Hides the generation timestamp when files are generated.| |false| |invokerPackage|root package for generated code| |org.openapitools.api| |java8|Option. Use Java8 classes instead of third party equivalents|
**true**
Use Java 8 classes such as Base64
**false**
Various third party libraries as needed
|false| +|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}}.|
**true**
The mapping in the discriminator includes descendent schemas that allOf inherit from self and the discriminator mapping schemas in the OAS document.
**false**
The mapping in the discriminator includes any descendent schemas that allOf inherit from self, any oneOf schemas, any anyOf schemas, any x-discriminator-values, and the discriminator mapping schemas in the OAS document AND Codegen validates that oneOf and anyOf schemas contain the required discriminator and throws an error if the discriminator is missing.
|true| |licenseName|The name of the license| |Unlicense| |licenseUrl|The URL of the license| |http://unlicense.org| |modelPackage|package for generated models| |org.openapitools.model| diff --git a/docs/generators/jaxrs-cxf-extended.md b/docs/generators/jaxrs-cxf-extended.md index 6fa651a36e1e..68373c8e73bc 100644 --- a/docs/generators/jaxrs-cxf-extended.md +++ b/docs/generators/jaxrs-cxf-extended.md @@ -21,6 +21,7 @@ sidebar_label: jaxrs-cxf-extended |developerOrganization|developer organization in generated pom.xml| |OpenAPITools.org| |developerOrganizationUrl|developer organization URL in generated pom.xml| |http://openapitools.org| |disableHtmlEscaping|Disable HTML escaping of JSON strings when using gson (needed to avoid problems with byte[] fields)| |false| +|discriminatorCaseSensitive|Whether the discriminator value lookup should be case-sensitive or not. This option only works for Java API client| |true| |ensureUniqueParams|Whether to ensure parameter names are unique in an operation (rename parameters that are not).| |true| |fullJavaUtil|whether to use fully qualified name for classes under java.util. This option only works for Java API client| |false| |generateJbossDeploymentDescriptor|Generate Jboss Deployment Descriptor| |false| @@ -33,6 +34,7 @@ sidebar_label: jaxrs-cxf-extended |implFolder|folder for generated implementation code| |src/main/java| |invokerPackage|root package for generated code| |org.openapitools.api| |java8|Option. Use Java8 classes instead of third party equivalents|
**true**
Use Java 8 classes such as Base64
**false**
Various third party libraries as needed
|false| +|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}}.|
**true**
The mapping in the discriminator includes descendent schemas that allOf inherit from self and the discriminator mapping schemas in the OAS document.
**false**
The mapping in the discriminator includes any descendent schemas that allOf inherit from self, any oneOf schemas, any anyOf schemas, any x-discriminator-values, and the discriminator mapping schemas in the OAS document AND Codegen validates that oneOf and anyOf schemas contain the required discriminator and throws an error if the discriminator is missing.
|true| |licenseName|The name of the license| |Unlicense| |licenseUrl|The URL of the license| |http://unlicense.org| |loadTestDataFromFile|Load test data from a generated JSON file| |false| diff --git a/docs/generators/jaxrs-cxf.md b/docs/generators/jaxrs-cxf.md index 7c1f0333da44..4e524009c7c1 100644 --- a/docs/generators/jaxrs-cxf.md +++ b/docs/generators/jaxrs-cxf.md @@ -21,6 +21,7 @@ sidebar_label: jaxrs-cxf |developerOrganization|developer organization in generated pom.xml| |OpenAPITools.org| |developerOrganizationUrl|developer organization URL in generated pom.xml| |http://openapitools.org| |disableHtmlEscaping|Disable HTML escaping of JSON strings when using gson (needed to avoid problems with byte[] fields)| |false| +|discriminatorCaseSensitive|Whether the discriminator value lookup should be case-sensitive or not. This option only works for Java API client| |true| |ensureUniqueParams|Whether to ensure parameter names are unique in an operation (rename parameters that are not).| |true| |fullJavaUtil|whether to use fully qualified name for classes under java.util. This option only works for Java API client| |false| |generateJbossDeploymentDescriptor|Generate Jboss Deployment Descriptor| |false| @@ -32,6 +33,7 @@ sidebar_label: jaxrs-cxf |implFolder|folder for generated implementation code| |src/main/java| |invokerPackage|root package for generated code| |org.openapitools.api| |java8|Option. Use Java8 classes instead of third party equivalents|
**true**
Use Java 8 classes such as Base64
**false**
Various third party libraries as needed
|false| +|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}}.|
**true**
The mapping in the discriminator includes descendent schemas that allOf inherit from self and the discriminator mapping schemas in the OAS document.
**false**
The mapping in the discriminator includes any descendent schemas that allOf inherit from self, any oneOf schemas, any anyOf schemas, any x-discriminator-values, and the discriminator mapping schemas in the OAS document AND Codegen validates that oneOf and anyOf schemas contain the required discriminator and throws an error if the discriminator is missing.
|true| |licenseName|The name of the license| |Unlicense| |licenseUrl|The URL of the license| |http://unlicense.org| |modelPackage|package for generated models| |org.openapitools.model| diff --git a/docs/generators/jaxrs-jersey.md b/docs/generators/jaxrs-jersey.md index 253f52217084..80948607ec94 100644 --- a/docs/generators/jaxrs-jersey.md +++ b/docs/generators/jaxrs-jersey.md @@ -20,6 +20,7 @@ sidebar_label: jaxrs-jersey |developerOrganization|developer organization in generated pom.xml| |OpenAPITools.org| |developerOrganizationUrl|developer organization URL in generated pom.xml| |http://openapitools.org| |disableHtmlEscaping|Disable HTML escaping of JSON strings when using gson (needed to avoid problems with byte[] fields)| |false| +|discriminatorCaseSensitive|Whether the discriminator value lookup should be case-sensitive or not. This option only works for Java API client| |true| |ensureUniqueParams|Whether to ensure parameter names are unique in an operation (rename parameters that are not).| |true| |fullJavaUtil|whether to use fully qualified name for classes under java.util. This option only works for Java API client| |false| |groupId|groupId in generated pom.xml| |org.openapitools| @@ -27,6 +28,7 @@ sidebar_label: jaxrs-jersey |implFolder|folder for generated implementation code| |src/main/java| |invokerPackage|root package for generated code| |org.openapitools.api| |java8|Option. Use Java8 classes instead of third party equivalents|
**true**
Use Java 8 classes such as Base64
**false**
Various third party libraries as needed
|false| +|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}}.|
**true**
The mapping in the discriminator includes descendent schemas that allOf inherit from self and the discriminator mapping schemas in the OAS document.
**false**
The mapping in the discriminator includes any descendent schemas that allOf inherit from self, any oneOf schemas, any anyOf schemas, any x-discriminator-values, and the discriminator mapping schemas in the OAS document AND Codegen validates that oneOf and anyOf schemas contain the required discriminator and throws an error if the discriminator is missing.
|true| |library|library template (sub-template)|
**jersey1**
Jersey core 1.x
**jersey2**
Jersey core 2.x
|jersey2| |licenseName|The name of the license| |Unlicense| |licenseUrl|The URL of the license| |http://unlicense.org| diff --git a/docs/generators/jaxrs-resteasy-eap.md b/docs/generators/jaxrs-resteasy-eap.md index b21e40893590..50c05785dc61 100644 --- a/docs/generators/jaxrs-resteasy-eap.md +++ b/docs/generators/jaxrs-resteasy-eap.md @@ -20,6 +20,7 @@ sidebar_label: jaxrs-resteasy-eap |developerOrganization|developer organization in generated pom.xml| |OpenAPITools.org| |developerOrganizationUrl|developer organization URL in generated pom.xml| |http://openapitools.org| |disableHtmlEscaping|Disable HTML escaping of JSON strings when using gson (needed to avoid problems with byte[] fields)| |false| +|discriminatorCaseSensitive|Whether the discriminator value lookup should be case-sensitive or not. This option only works for Java API client| |true| |ensureUniqueParams|Whether to ensure parameter names are unique in an operation (rename parameters that are not).| |true| |fullJavaUtil|whether to use fully qualified name for classes under java.util. This option only works for Java API client| |false| |generateJbossDeploymentDescriptor|Generate Jboss Deployment Descriptor| |true| @@ -28,6 +29,7 @@ sidebar_label: jaxrs-resteasy-eap |implFolder|folder for generated implementation code| |src/main/java| |invokerPackage|root package for generated code| |org.openapitools.api| |java8|Option. Use Java8 classes instead of third party equivalents|
**true**
Use Java 8 classes such as Base64
**false**
Various third party libraries as needed
|false| +|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}}.|
**true**
The mapping in the discriminator includes descendent schemas that allOf inherit from self and the discriminator mapping schemas in the OAS document.
**false**
The mapping in the discriminator includes any descendent schemas that allOf inherit from self, any oneOf schemas, any anyOf schemas, any x-discriminator-values, and the discriminator mapping schemas in the OAS document AND Codegen validates that oneOf and anyOf schemas contain the required discriminator and throws an error if the discriminator is missing.
|true| |licenseName|The name of the license| |Unlicense| |licenseUrl|The URL of the license| |http://unlicense.org| |modelPackage|package for generated models| |org.openapitools.model| diff --git a/docs/generators/jaxrs-resteasy.md b/docs/generators/jaxrs-resteasy.md index 0967238e18e7..66e7882c4409 100644 --- a/docs/generators/jaxrs-resteasy.md +++ b/docs/generators/jaxrs-resteasy.md @@ -20,6 +20,7 @@ sidebar_label: jaxrs-resteasy |developerOrganization|developer organization in generated pom.xml| |OpenAPITools.org| |developerOrganizationUrl|developer organization URL in generated pom.xml| |http://openapitools.org| |disableHtmlEscaping|Disable HTML escaping of JSON strings when using gson (needed to avoid problems with byte[] fields)| |false| +|discriminatorCaseSensitive|Whether the discriminator value lookup should be case-sensitive or not. This option only works for Java API client| |true| |ensureUniqueParams|Whether to ensure parameter names are unique in an operation (rename parameters that are not).| |true| |fullJavaUtil|whether to use fully qualified name for classes under java.util. This option only works for Java API client| |false| |generateJbossDeploymentDescriptor|Generate Jboss Deployment Descriptor| |false| @@ -28,6 +29,7 @@ sidebar_label: jaxrs-resteasy |implFolder|folder for generated implementation code| |src/main/java| |invokerPackage|root package for generated code| |org.openapitools.api| |java8|Option. Use Java8 classes instead of third party equivalents|
**true**
Use Java 8 classes such as Base64
**false**
Various third party libraries as needed
|false| +|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}}.|
**true**
The mapping in the discriminator includes descendent schemas that allOf inherit from self and the discriminator mapping schemas in the OAS document.
**false**
The mapping in the discriminator includes any descendent schemas that allOf inherit from self, any oneOf schemas, any anyOf schemas, any x-discriminator-values, and the discriminator mapping schemas in the OAS document AND Codegen validates that oneOf and anyOf schemas contain the required discriminator and throws an error if the discriminator is missing.
|true| |licenseName|The name of the license| |Unlicense| |licenseUrl|The URL of the license| |http://unlicense.org| |modelPackage|package for generated models| |org.openapitools.model| diff --git a/docs/generators/jaxrs-spec.md b/docs/generators/jaxrs-spec.md index efa6474297ba..1d4e97cbf8b6 100644 --- a/docs/generators/jaxrs-spec.md +++ b/docs/generators/jaxrs-spec.md @@ -20,8 +20,10 @@ sidebar_label: jaxrs-spec |developerOrganization|developer organization in generated pom.xml| |OpenAPITools.org| |developerOrganizationUrl|developer organization URL in generated pom.xml| |http://openapitools.org| |disableHtmlEscaping|Disable HTML escaping of JSON strings when using gson (needed to avoid problems with byte[] fields)| |false| +|discriminatorCaseSensitive|Whether the discriminator value lookup should be case-sensitive or not. This option only works for Java API client| |true| |ensureUniqueParams|Whether to ensure parameter names are unique in an operation (rename parameters that are not).| |true| |fullJavaUtil|whether to use fully qualified name for classes under java.util. This option only works for Java API client| |false| +|generateBuilders|Whether to generate builders for models.| |false| |generatePom|Whether to generate pom.xml if the file does not already exist.| |true| |groupId|groupId in generated pom.xml| |org.openapitools| |hideGenerationTimestamp|Hides the generation timestamp when files are generated.| |false| @@ -29,6 +31,7 @@ sidebar_label: jaxrs-spec |interfaceOnly|Whether to generate only API interface stubs without the server files.| |false| |invokerPackage|root package for generated code| |org.openapitools.api| |java8|Option. Use Java8 classes instead of third party equivalents|
**true**
Use Java 8 classes such as Base64
**false**
Various third party libraries as needed
|false| +|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}}.|
**true**
The mapping in the discriminator includes descendent schemas that allOf inherit from self and the discriminator mapping schemas in the OAS document.
**false**
The mapping in the discriminator includes any descendent schemas that allOf inherit from self, any oneOf schemas, any anyOf schemas, any x-discriminator-values, and the discriminator mapping schemas in the OAS document AND Codegen validates that oneOf and anyOf schemas contain the required discriminator and throws an error if the discriminator is missing.
|true| |library|library template (sub-template)|
**<default>**
JAXRS spec only, to be deployed in an app server (TomEE, JBoss, WLS, ...)
**quarkus**
Server using Quarkus
**thorntail**
Server using Thorntail
**openliberty**
Server using Open Liberty
**helidon**
Server using Helidon
|<default>| |licenseName|The name of the license| |Unlicense| |licenseUrl|The URL of the license| |http://unlicense.org| diff --git a/docs/generators/jmeter.md b/docs/generators/jmeter.md index 142f826d7938..16825e5dee41 100644 --- a/docs/generators/jmeter.md +++ b/docs/generators/jmeter.md @@ -7,6 +7,7 @@ sidebar_label: jmeter | ------ | ----------- | ------ | ------- | |allowUnicodeIdentifiers|boolean, toggles whether unicode identifiers are allowed in names or not, default is false| |false| |ensureUniqueParams|Whether to ensure parameter names are unique in an operation (rename parameters that are not).| |true| +|legacyDiscriminatorBehavior|This flag is used by OpenAPITools codegen to influence the processing of the discriminator attribute in OpenAPI documents. This flag has no impact if the OAS document does not use the discriminator attribute. The default value of this flag is set in each language-specific code generator (e.g. Python, Java, go...)using the method toModelName. Note to developers supporting a language generator in OpenAPITools; to fully support the discriminator attribute as defined in the OAS specification 3.x, language generators should set this flag to true by default; however this requires updating the mustache templates to generate a language-specific discriminator lookup function that iterates over {{#mappedModels}} and does not iterate over {{children}}, {{#anyOf}}, or {{#oneOf}}.|
**true**
The mapping in the discriminator includes descendent schemas that allOf inherit from self and the discriminator mapping schemas in the OAS document.
**false**
The mapping in the discriminator includes any descendent schemas that allOf inherit from self, any oneOf schemas, any anyOf schemas, any x-discriminator-values, and the discriminator mapping schemas in the OAS document AND Codegen validates that oneOf and anyOf schemas contain the required discriminator and throws an error if the discriminator is missing.
|true| |prependFormOrBodyParameters|Add form or body parameters to the beginning of the parameter list.| |false| |sortModelPropertiesByRequiredFlag|Sort model properties to place required parameters before optional parameters.| |true| |sortParamsByRequiredFlag|Sort method arguments to place required parameters before optional parameters.| |true| diff --git a/docs/generators/k6.md b/docs/generators/k6.md index 4ff51c7527fb..7d2b09f46ebe 100644 --- a/docs/generators/k6.md +++ b/docs/generators/k6.md @@ -7,6 +7,7 @@ sidebar_label: k6 | ------ | ----------- | ------ | ------- | |allowUnicodeIdentifiers|boolean, toggles whether unicode identifiers are allowed in names or not, default is false| |false| |ensureUniqueParams|Whether to ensure parameter names are unique in an operation (rename parameters that are not).| |true| +|legacyDiscriminatorBehavior|This flag is used by OpenAPITools codegen to influence the processing of the discriminator attribute in OpenAPI documents. This flag has no impact if the OAS document does not use the discriminator attribute. The default value of this flag is set in each language-specific code generator (e.g. Python, Java, go...)using the method toModelName. Note to developers supporting a language generator in OpenAPITools; to fully support the discriminator attribute as defined in the OAS specification 3.x, language generators should set this flag to true by default; however this requires updating the mustache templates to generate a language-specific discriminator lookup function that iterates over {{#mappedModels}} and does not iterate over {{children}}, {{#anyOf}}, or {{#oneOf}}.|
**true**
The mapping in the discriminator includes descendent schemas that allOf inherit from self and the discriminator mapping schemas in the OAS document.
**false**
The mapping in the discriminator includes any descendent schemas that allOf inherit from self, any oneOf schemas, any anyOf schemas, any x-discriminator-values, and the discriminator mapping schemas in the OAS document AND Codegen validates that oneOf and anyOf schemas contain the required discriminator and throws an error if the discriminator is missing.
|true| |prependFormOrBodyParameters|Add form or body parameters to the beginning of the parameter list.| |false| |sortModelPropertiesByRequiredFlag|Sort model properties to place required parameters before optional parameters.| |true| |sortParamsByRequiredFlag|Sort method arguments to place required parameters before optional parameters.| |true| diff --git a/docs/generators/markdown.md b/docs/generators/markdown.md index 2cba7bc698ef..fef2cddc340d 100644 --- a/docs/generators/markdown.md +++ b/docs/generators/markdown.md @@ -7,6 +7,7 @@ sidebar_label: markdown | ------ | ----------- | ------ | ------- | |allowUnicodeIdentifiers|boolean, toggles whether unicode identifiers are allowed in names or not, default is false| |false| |ensureUniqueParams|Whether to ensure parameter names are unique in an operation (rename parameters that are not).| |true| +|legacyDiscriminatorBehavior|This flag is used by OpenAPITools codegen to influence the processing of the discriminator attribute in OpenAPI documents. This flag has no impact if the OAS document does not use the discriminator attribute. The default value of this flag is set in each language-specific code generator (e.g. Python, Java, go...)using the method toModelName. Note to developers supporting a language generator in OpenAPITools; to fully support the discriminator attribute as defined in the OAS specification 3.x, language generators should set this flag to true by default; however this requires updating the mustache templates to generate a language-specific discriminator lookup function that iterates over {{#mappedModels}} and does not iterate over {{children}}, {{#anyOf}}, or {{#oneOf}}.|
**true**
The mapping in the discriminator includes descendent schemas that allOf inherit from self and the discriminator mapping schemas in the OAS document.
**false**
The mapping in the discriminator includes any descendent schemas that allOf inherit from self, any oneOf schemas, any anyOf schemas, any x-discriminator-values, and the discriminator mapping schemas in the OAS document AND Codegen validates that oneOf and anyOf schemas contain the required discriminator and throws an error if the discriminator is missing.
|true| |prependFormOrBodyParameters|Add form or body parameters to the beginning of the parameter list.| |false| |sortModelPropertiesByRequiredFlag|Sort model properties to place required parameters before optional parameters.| |true| |sortParamsByRequiredFlag|Sort method arguments to place required parameters before optional parameters.| |true| diff --git a/docs/generators/mysql-schema.md b/docs/generators/mysql-schema.md index be5ae0f443de..7963dd5fafbb 100644 --- a/docs/generators/mysql-schema.md +++ b/docs/generators/mysql-schema.md @@ -8,6 +8,7 @@ sidebar_label: mysql-schema |defaultDatabaseName|Default database name for all MySQL queries| || |identifierNamingConvention|Naming convention of MySQL identifiers(table names and column names). This is not related to database name which is defined by defaultDatabaseName option|
**original**
Do not transform original names
**snake_case**
Use snake_case names
|original| |jsonDataTypeEnabled|Use special JSON MySQL data type for complex model properties. Requires MySQL version 5.7.8. Generates TEXT data type when disabled| |true| +|namedParametersEnabled|Generates model prepared SQLs with named parameters, eg. :petName. Question mark placeholder used when option disabled.| |false| ## IMPORT MAPPING diff --git a/docs/generators/nim.md b/docs/generators/nim.md index 61ba1d00f1f5..5b72fb3575a9 100644 --- a/docs/generators/nim.md +++ b/docs/generators/nim.md @@ -7,6 +7,7 @@ sidebar_label: nim | ------ | ----------- | ------ | ------- | |allowUnicodeIdentifiers|boolean, toggles whether unicode identifiers are allowed in names or not, default is false| |false| |ensureUniqueParams|Whether to ensure parameter names are unique in an operation (rename parameters that are not).| |true| +|legacyDiscriminatorBehavior|This flag is used by OpenAPITools codegen to influence the processing of the discriminator attribute in OpenAPI documents. This flag has no impact if the OAS document does not use the discriminator attribute. The default value of this flag is set in each language-specific code generator (e.g. Python, Java, go...)using the method toModelName. Note to developers supporting a language generator in OpenAPITools; to fully support the discriminator attribute as defined in the OAS specification 3.x, language generators should set this flag to true by default; however this requires updating the mustache templates to generate a language-specific discriminator lookup function that iterates over {{#mappedModels}} and does not iterate over {{children}}, {{#anyOf}}, or {{#oneOf}}.|
**true**
The mapping in the discriminator includes descendent schemas that allOf inherit from self and the discriminator mapping schemas in the OAS document.
**false**
The mapping in the discriminator includes any descendent schemas that allOf inherit from self, any oneOf schemas, any anyOf schemas, any x-discriminator-values, and the discriminator mapping schemas in the OAS document AND Codegen validates that oneOf and anyOf schemas contain the required discriminator and throws an error if the discriminator is missing.
|true| |prependFormOrBodyParameters|Add form or body parameters to the beginning of the parameter list.| |false| |sortModelPropertiesByRequiredFlag|Sort model properties to place required parameters before optional parameters.| |true| |sortParamsByRequiredFlag|Sort method arguments to place required parameters before optional parameters.| |true| diff --git a/docs/generators/nodejs-express-server.md b/docs/generators/nodejs-express-server.md index 76b0893f9a33..5ded08347aa2 100644 --- a/docs/generators/nodejs-express-server.md +++ b/docs/generators/nodejs-express-server.md @@ -7,6 +7,7 @@ sidebar_label: nodejs-express-server | ------ | ----------- | ------ | ------- | |allowUnicodeIdentifiers|boolean, toggles whether unicode identifiers are allowed in names or not, default is false| |false| |ensureUniqueParams|Whether to ensure parameter names are unique in an operation (rename parameters that are not).| |true| +|legacyDiscriminatorBehavior|This flag is used by OpenAPITools codegen to influence the processing of the discriminator attribute in OpenAPI documents. This flag has no impact if the OAS document does not use the discriminator attribute. The default value of this flag is set in each language-specific code generator (e.g. Python, Java, go...)using the method toModelName. Note to developers supporting a language generator in OpenAPITools; to fully support the discriminator attribute as defined in the OAS specification 3.x, language generators should set this flag to true by default; however this requires updating the mustache templates to generate a language-specific discriminator lookup function that iterates over {{#mappedModels}} and does not iterate over {{children}}, {{#anyOf}}, or {{#oneOf}}.|
**true**
The mapping in the discriminator includes descendent schemas that allOf inherit from self and the discriminator mapping schemas in the OAS document.
**false**
The mapping in the discriminator includes any descendent schemas that allOf inherit from self, any oneOf schemas, any anyOf schemas, any x-discriminator-values, and the discriminator mapping schemas in the OAS document AND Codegen validates that oneOf and anyOf schemas contain the required discriminator and throws an error if the discriminator is missing.
|true| |prependFormOrBodyParameters|Add form or body parameters to the beginning of the parameter list.| |false| |serverPort|TCP port to listen on.| |null| |sortModelPropertiesByRequiredFlag|Sort model properties to place required parameters before optional parameters.| |true| diff --git a/docs/generators/nodejs-server-deprecated.md b/docs/generators/nodejs-server-deprecated.md index 84a3b1319439..981b7b9fffec 100644 --- a/docs/generators/nodejs-server-deprecated.md +++ b/docs/generators/nodejs-server-deprecated.md @@ -9,6 +9,7 @@ sidebar_label: nodejs-server-deprecated |ensureUniqueParams|Whether to ensure parameter names are unique in an operation (rename parameters that are not).| |true| |exportedName|When the generated code will be deployed to Google Cloud Functions, this option can be used to update the name of the exported function. By default, it refers to the basePath. This does not affect normal standalone nodejs server code.| |null| |googleCloudFunctions|When specified, it will generate the code which runs within Google Cloud Functions instead of standalone Node.JS server. See https://cloud.google.com/functions/docs/quickstart for the details of how to deploy the generated code.| |false| +|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}}.|
**true**
The mapping in the discriminator includes descendent schemas that allOf inherit from self and the discriminator mapping schemas in the OAS document.
**false**
The mapping in the discriminator includes any descendent schemas that allOf inherit from self, any oneOf schemas, any anyOf schemas, any x-discriminator-values, and the discriminator mapping schemas in the OAS document AND Codegen validates that oneOf and anyOf schemas contain the required discriminator and throws an error if the discriminator is missing.
|true| |prependFormOrBodyParameters|Add form or body parameters to the beginning of the parameter list.| |false| |serverPort|TCP port to listen on.| |null| |sortModelPropertiesByRequiredFlag|Sort model properties to place required parameters before optional parameters.| |true| diff --git a/docs/generators/ocaml.md b/docs/generators/ocaml.md index d8cda30ed802..403a8eff9e76 100644 --- a/docs/generators/ocaml.md +++ b/docs/generators/ocaml.md @@ -7,6 +7,7 @@ sidebar_label: ocaml | ------ | ----------- | ------ | ------- | |allowUnicodeIdentifiers|boolean, toggles whether unicode identifiers are allowed in names or not, default is false| |false| |ensureUniqueParams|Whether to ensure parameter names are unique in an operation (rename parameters that are not).| |true| +|legacyDiscriminatorBehavior|This flag is used by OpenAPITools codegen to influence the processing of the discriminator attribute in OpenAPI documents. This flag has no impact if the OAS document does not use the discriminator attribute. The default value of this flag is set in each language-specific code generator (e.g. Python, Java, go...)using the method toModelName. Note to developers supporting a language generator in OpenAPITools; to fully support the discriminator attribute as defined in the OAS specification 3.x, language generators should set this flag to true by default; however this requires updating the mustache templates to generate a language-specific discriminator lookup function that iterates over {{#mappedModels}} and does not iterate over {{children}}, {{#anyOf}}, or {{#oneOf}}.|
**true**
The mapping in the discriminator includes descendent schemas that allOf inherit from self and the discriminator mapping schemas in the OAS document.
**false**
The mapping in the discriminator includes any descendent schemas that allOf inherit from self, any oneOf schemas, any anyOf schemas, any x-discriminator-values, and the discriminator mapping schemas in the OAS document AND Codegen validates that oneOf and anyOf schemas contain the required discriminator and throws an error if the discriminator is missing.
|true| |prependFormOrBodyParameters|Add form or body parameters to the beginning of the parameter list.| |false| |sortModelPropertiesByRequiredFlag|Sort model properties to place required parameters before optional parameters.| |true| |sortParamsByRequiredFlag|Sort method arguments to place required parameters before optional parameters.| |true| diff --git a/docs/generators/openapi-yaml.md b/docs/generators/openapi-yaml.md index 7eda9d44be0d..3fde0dfd3bb6 100644 --- a/docs/generators/openapi-yaml.md +++ b/docs/generators/openapi-yaml.md @@ -7,6 +7,7 @@ sidebar_label: openapi-yaml | ------ | ----------- | ------ | ------- | |allowUnicodeIdentifiers|boolean, toggles whether unicode identifiers are allowed in names or not, default is false| |false| |ensureUniqueParams|Whether to ensure parameter names are unique in an operation (rename parameters that are not).| |true| +|legacyDiscriminatorBehavior|This flag is used by OpenAPITools codegen to influence the processing of the discriminator attribute in OpenAPI documents. This flag has no impact if the OAS document does not use the discriminator attribute. The default value of this flag is set in each language-specific code generator (e.g. Python, Java, go...)using the method toModelName. Note to developers supporting a language generator in OpenAPITools; to fully support the discriminator attribute as defined in the OAS specification 3.x, language generators should set this flag to true by default; however this requires updating the mustache templates to generate a language-specific discriminator lookup function that iterates over {{#mappedModels}} and does not iterate over {{children}}, {{#anyOf}}, or {{#oneOf}}.|
**true**
The mapping in the discriminator includes descendent schemas that allOf inherit from self and the discriminator mapping schemas in the OAS document.
**false**
The mapping in the discriminator includes any descendent schemas that allOf inherit from self, any oneOf schemas, any anyOf schemas, any x-discriminator-values, and the discriminator mapping schemas in the OAS document AND Codegen validates that oneOf and anyOf schemas contain the required discriminator and throws an error if the discriminator is missing.
|true| |outputFile|Output filename| |openapi/openapi.yaml| |prependFormOrBodyParameters|Add form or body parameters to the beginning of the parameter list.| |false| |sortModelPropertiesByRequiredFlag|Sort model properties to place required parameters before optional parameters.| |true| diff --git a/docs/generators/openapi.md b/docs/generators/openapi.md index 5d46dccf4fd9..fe7fe0cfa509 100644 --- a/docs/generators/openapi.md +++ b/docs/generators/openapi.md @@ -7,6 +7,7 @@ sidebar_label: openapi | ------ | ----------- | ------ | ------- | |allowUnicodeIdentifiers|boolean, toggles whether unicode identifiers are allowed in names or not, default is false| |false| |ensureUniqueParams|Whether to ensure parameter names are unique in an operation (rename parameters that are not).| |true| +|legacyDiscriminatorBehavior|This flag is used by OpenAPITools codegen to influence the processing of the discriminator attribute in OpenAPI documents. This flag has no impact if the OAS document does not use the discriminator attribute. The default value of this flag is set in each language-specific code generator (e.g. Python, Java, go...)using the method toModelName. Note to developers supporting a language generator in OpenAPITools; to fully support the discriminator attribute as defined in the OAS specification 3.x, language generators should set this flag to true by default; however this requires updating the mustache templates to generate a language-specific discriminator lookup function that iterates over {{#mappedModels}} and does not iterate over {{children}}, {{#anyOf}}, or {{#oneOf}}.|
**true**
The mapping in the discriminator includes descendent schemas that allOf inherit from self and the discriminator mapping schemas in the OAS document.
**false**
The mapping in the discriminator includes any descendent schemas that allOf inherit from self, any oneOf schemas, any anyOf schemas, any x-discriminator-values, and the discriminator mapping schemas in the OAS document AND Codegen validates that oneOf and anyOf schemas contain the required discriminator and throws an error if the discriminator is missing.
|true| |prependFormOrBodyParameters|Add form or body parameters to the beginning of the parameter list.| |false| |sortModelPropertiesByRequiredFlag|Sort model properties to place required parameters before optional parameters.| |true| |sortParamsByRequiredFlag|Sort method arguments to place required parameters before optional parameters.| |true| diff --git a/docs/generators/php-laravel.md b/docs/generators/php-laravel.md index 57b9191b6012..f6447b33d5c4 100644 --- a/docs/generators/php-laravel.md +++ b/docs/generators/php-laravel.md @@ -10,6 +10,7 @@ sidebar_label: php-laravel |artifactVersion|The version to use in the composer package version field. e.g. 1.2.3| |null| |ensureUniqueParams|Whether to ensure parameter names are unique in an operation (rename parameters that are not).| |true| |invokerPackage|The main namespace to use for all classes. e.g. Yay\Pets| |null| +|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}}.|
**true**
The mapping in the discriminator includes descendent schemas that allOf inherit from self and the discriminator mapping schemas in the OAS document.
**false**
The mapping in the discriminator includes any descendent schemas that allOf inherit from self, any oneOf schemas, any anyOf schemas, any x-discriminator-values, and the discriminator mapping schemas in the OAS document AND Codegen validates that oneOf and anyOf schemas contain the required discriminator and throws an error if the discriminator is missing.
|true| |modelPackage|package for generated models| |null| |packageName|The main package name for classes. e.g. GeneratedPetstore| |null| |prependFormOrBodyParameters|Add form or body parameters to the beginning of the parameter list.| |false| diff --git a/docs/generators/php-lumen.md b/docs/generators/php-lumen.md index 2414dda65c72..33efe2cc794f 100644 --- a/docs/generators/php-lumen.md +++ b/docs/generators/php-lumen.md @@ -10,6 +10,7 @@ sidebar_label: php-lumen |artifactVersion|The version to use in the composer package version field. e.g. 1.2.3| |null| |ensureUniqueParams|Whether to ensure parameter names are unique in an operation (rename parameters that are not).| |true| |invokerPackage|The main namespace to use for all classes. e.g. Yay\Pets| |null| +|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}}.|
**true**
The mapping in the discriminator includes descendent schemas that allOf inherit from self and the discriminator mapping schemas in the OAS document.
**false**
The mapping in the discriminator includes any descendent schemas that allOf inherit from self, any oneOf schemas, any anyOf schemas, any x-discriminator-values, and the discriminator mapping schemas in the OAS document AND Codegen validates that oneOf and anyOf schemas contain the required discriminator and throws an error if the discriminator is missing.
|true| |modelPackage|package for generated models| |null| |packageName|The main package name for classes. e.g. GeneratedPetstore| |null| |prependFormOrBodyParameters|Add form or body parameters to the beginning of the parameter list.| |false| diff --git a/docs/generators/php-silex.md b/docs/generators/php-silex.md index 81f5e6cb38c8..c9fc756ed198 100644 --- a/docs/generators/php-silex.md +++ b/docs/generators/php-silex.md @@ -7,6 +7,7 @@ sidebar_label: php-silex | ------ | ----------- | ------ | ------- | |allowUnicodeIdentifiers|boolean, toggles whether unicode identifiers are allowed in names or not, default is false| |false| |ensureUniqueParams|Whether to ensure parameter names are unique in an operation (rename parameters that are not).| |true| +|legacyDiscriminatorBehavior|This flag is used by OpenAPITools codegen to influence the processing of the discriminator attribute in OpenAPI documents. This flag has no impact if the OAS document does not use the discriminator attribute. The default value of this flag is set in each language-specific code generator (e.g. Python, Java, go...)using the method toModelName. Note to developers supporting a language generator in OpenAPITools; to fully support the discriminator attribute as defined in the OAS specification 3.x, language generators should set this flag to true by default; however this requires updating the mustache templates to generate a language-specific discriminator lookup function that iterates over {{#mappedModels}} and does not iterate over {{children}}, {{#anyOf}}, or {{#oneOf}}.|
**true**
The mapping in the discriminator includes descendent schemas that allOf inherit from self and the discriminator mapping schemas in the OAS document.
**false**
The mapping in the discriminator includes any descendent schemas that allOf inherit from self, any oneOf schemas, any anyOf schemas, any x-discriminator-values, and the discriminator mapping schemas in the OAS document AND Codegen validates that oneOf and anyOf schemas contain the required discriminator and throws an error if the discriminator is missing.
|true| |prependFormOrBodyParameters|Add form or body parameters to the beginning of the parameter list.| |false| |sortModelPropertiesByRequiredFlag|Sort model properties to place required parameters before optional parameters.| |true| |sortParamsByRequiredFlag|Sort method arguments to place required parameters before optional parameters.| |true| diff --git a/docs/generators/php-slim-deprecated.md b/docs/generators/php-slim-deprecated.md index 98381616b95b..d97ebb8060d9 100644 --- a/docs/generators/php-slim-deprecated.md +++ b/docs/generators/php-slim-deprecated.md @@ -10,6 +10,7 @@ sidebar_label: php-slim-deprecated |artifactVersion|The version to use in the composer package version field. e.g. 1.2.3| |null| |ensureUniqueParams|Whether to ensure parameter names are unique in an operation (rename parameters that are not).| |true| |invokerPackage|The main namespace to use for all classes. e.g. Yay\Pets| |null| +|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}}.|
**true**
The mapping in the discriminator includes descendent schemas that allOf inherit from self and the discriminator mapping schemas in the OAS document.
**false**
The mapping in the discriminator includes any descendent schemas that allOf inherit from self, any oneOf schemas, any anyOf schemas, any x-discriminator-values, and the discriminator mapping schemas in the OAS document AND Codegen validates that oneOf and anyOf schemas contain the required discriminator and throws an error if the discriminator is missing.
|true| |modelPackage|package for generated models| |null| |packageName|The main package name for classes. e.g. GeneratedPetstore| |null| |prependFormOrBodyParameters|Add form or body parameters to the beginning of the parameter list.| |false| diff --git a/docs/generators/php-slim4.md b/docs/generators/php-slim4.md index b0e79e02ae71..ff5ee683ab1d 100644 --- a/docs/generators/php-slim4.md +++ b/docs/generators/php-slim4.md @@ -10,6 +10,7 @@ sidebar_label: php-slim4 |artifactVersion|The version to use in the composer package version field. e.g. 1.2.3| |null| |ensureUniqueParams|Whether to ensure parameter names are unique in an operation (rename parameters that are not).| |true| |invokerPackage|The main namespace to use for all classes. e.g. Yay\Pets| |null| +|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}}.|
**true**
The mapping in the discriminator includes descendent schemas that allOf inherit from self and the discriminator mapping schemas in the OAS document.
**false**
The mapping in the discriminator includes any descendent schemas that allOf inherit from self, any oneOf schemas, any anyOf schemas, any x-discriminator-values, and the discriminator mapping schemas in the OAS document AND Codegen validates that oneOf and anyOf schemas contain the required discriminator and throws an error if the discriminator is missing.
|true| |modelPackage|package for generated models| |null| |packageName|The main package name for classes. e.g. GeneratedPetstore| |null| |prependFormOrBodyParameters|Add form or body parameters to the beginning of the parameter list.| |false| diff --git a/docs/generators/php-symfony.md b/docs/generators/php-symfony.md index 1d3e71d39265..1c781a04c97b 100644 --- a/docs/generators/php-symfony.md +++ b/docs/generators/php-symfony.md @@ -15,6 +15,7 @@ sidebar_label: php-symfony |ensureUniqueParams|Whether to ensure parameter names are unique in an operation (rename parameters that are not).| |true| |hideGenerationTimestamp|Hides the generation timestamp when files are generated.| |true| |invokerPackage|The main namespace to use for all classes. e.g. Yay\Pets| |null| +|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}}.|
**true**
The mapping in the discriminator includes descendent schemas that allOf inherit from self and the discriminator mapping schemas in the OAS document.
**false**
The mapping in the discriminator includes any descendent schemas that allOf inherit from self, any oneOf schemas, any anyOf schemas, any x-discriminator-values, and the discriminator mapping schemas in the OAS document AND Codegen validates that oneOf and anyOf schemas contain the required discriminator and throws an error if the discriminator is missing.
|true| |modelPackage|package for generated models| |null| |packageName|The main package name for classes. e.g. GeneratedPetstore| |null| |phpLegacySupport|Should the generated code be compatible with PHP 5.x?| |true| diff --git a/docs/generators/php-ze-ph.md b/docs/generators/php-ze-ph.md index 93a1d3f6adf7..b6852f1087d6 100644 --- a/docs/generators/php-ze-ph.md +++ b/docs/generators/php-ze-ph.md @@ -10,6 +10,7 @@ sidebar_label: php-ze-ph |artifactVersion|The version to use in the composer package version field. e.g. 1.2.3| |null| |ensureUniqueParams|Whether to ensure parameter names are unique in an operation (rename parameters that are not).| |true| |invokerPackage|The main namespace to use for all classes. e.g. Yay\Pets| |null| +|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}}.|
**true**
The mapping in the discriminator includes descendent schemas that allOf inherit from self and the discriminator mapping schemas in the OAS document.
**false**
The mapping in the discriminator includes any descendent schemas that allOf inherit from self, any oneOf schemas, any anyOf schemas, any x-discriminator-values, and the discriminator mapping schemas in the OAS document AND Codegen validates that oneOf and anyOf schemas contain the required discriminator and throws an error if the discriminator is missing.
|true| |modelPackage|package for generated models| |null| |packageName|The main package name for classes. e.g. GeneratedPetstore| |null| |prependFormOrBodyParameters|Add form or body parameters to the beginning of the parameter list.| |false| diff --git a/docs/generators/php.md b/docs/generators/php.md index 413996804eb0..329969e42fdc 100644 --- a/docs/generators/php.md +++ b/docs/generators/php.md @@ -11,6 +11,7 @@ sidebar_label: php |ensureUniqueParams|Whether to ensure parameter names are unique in an operation (rename parameters that are not).| |true| |hideGenerationTimestamp|boolean, toggles whether unicode identifiers are allowed in names or not, default is false| |true| |invokerPackage|The main namespace to use for all classes. e.g. Yay\Pets| |null| +|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}}.|
**true**
The mapping in the discriminator includes descendent schemas that allOf inherit from self and the discriminator mapping schemas in the OAS document.
**false**
The mapping in the discriminator includes any descendent schemas that allOf inherit from self, any oneOf schemas, any anyOf schemas, any x-discriminator-values, and the discriminator mapping schemas in the OAS document AND Codegen validates that oneOf and anyOf schemas contain the required discriminator and throws an error if the discriminator is missing.
|true| |modelPackage|package for generated models| |null| |packageName|The main package name for classes. e.g. GeneratedPetstore| |null| |prependFormOrBodyParameters|Add form or body parameters to the beginning of the parameter list.| |false| diff --git a/docs/generators/powershell-experimental.md b/docs/generators/powershell-experimental.md index 36e5728eae7e..bc3c8be474f7 100644 --- a/docs/generators/powershell-experimental.md +++ b/docs/generators/powershell-experimental.md @@ -6,6 +6,7 @@ sidebar_label: powershell-experimental | Option | Description | Values | Default | | ------ | ----------- | ------ | ------- | |apiNamePrefix|Prefix that will be appended to all PS objects. Default: empty string. e.g. Pet => PSPet.| |null| +|commonVerbs|PS common verb mappings. e.g. Delete=Remove:Patch=Update to map Delete with Remove and Patch with Update accordingly.| |null| |packageGuid|GUID for PowerShell module (e.g. a27b908d-2a20-467f-bc32-af6f3a654ac5). A random GUID will be generated by default.| |null| |packageName|Client package name (e.g. PSTwitter).| |PSOpenAPITools| |packageVersion|Package version (e.g. 0.1.2).| |0.1.2| @@ -71,37 +72,70 @@ sidebar_label: powershell-experimental ## RESERVED WORDS
    -
  • Begin
  • -
  • Break
  • -
  • Catch
  • -
  • Continue
  • -
  • Data
  • -
  • Do
  • -
  • Dynamicparam
  • -
  • Else
  • -
  • Elseif
  • -
  • End
  • -
  • Exit
  • -
  • Filter
  • -
  • Finally
  • -
  • For
  • -
  • Foreach
  • -
  • From
  • -
  • Function
  • -
  • If
  • -
  • In
  • -
  • Local
  • -
  • Param
  • -
  • Private
  • -
  • Process
  • -
  • Return
  • -
  • Switch
  • -
  • Throw
  • -
  • Trap
  • -
  • Try
  • -
  • Until
  • -
  • Where
  • -
  • While
  • +
  • args
  • +
  • begin
  • +
  • break
  • +
  • catch
  • +
  • consolefilename
  • +
  • continue
  • +
  • data
  • +
  • do
  • +
  • dynamicparam
  • +
  • else
  • +
  • elseif
  • +
  • end
  • +
  • error
  • +
  • event
  • +
  • eventargs
  • +
  • eventsubscriber
  • +
  • executioncontext
  • +
  • exit
  • +
  • false
  • +
  • filter
  • +
  • finally
  • +
  • for
  • +
  • foreach
  • +
  • from
  • +
  • function
  • +
  • home
  • +
  • host
  • +
  • if
  • +
  • in
  • +
  • input
  • +
  • lastexitcode
  • +
  • local
  • +
  • matches
  • +
  • myinvocation
  • +
  • nestedpromptlevel
  • +
  • null
  • +
  • param
  • +
  • pid
  • +
  • private
  • +
  • process
  • +
  • profile
  • +
  • pscmdlet
  • +
  • pscommandpath
  • +
  • psculture
  • +
  • psdebugcontext
  • +
  • pshome
  • +
  • psitem
  • +
  • psscriptroot
  • +
  • pssenderinfo
  • +
  • psuiculture
  • +
  • psversiontable
  • +
  • return
  • +
  • sender
  • +
  • shellid
  • +
  • stacktrace
  • +
  • switch
  • +
  • this
  • +
  • throw
  • +
  • trap
  • +
  • true
  • +
  • try
  • +
  • until
  • +
  • where
  • +
  • while
## FEATURE SET diff --git a/docs/generators/python-aiohttp.md b/docs/generators/python-aiohttp.md index 5f71e7b0b5dd..522e75b3866e 100644 --- a/docs/generators/python-aiohttp.md +++ b/docs/generators/python-aiohttp.md @@ -9,9 +9,11 @@ sidebar_label: python-aiohttp |controllerPackage|controller package| |controllers| |defaultController|default controller| |default_controller| |ensureUniqueParams|Whether to ensure parameter names are unique in an operation (rename parameters that are not).| |true| +|legacyDiscriminatorBehavior|This flag is used by OpenAPITools codegen to influence the processing of the discriminator attribute in OpenAPI documents. This flag has no impact if the OAS document does not use the discriminator attribute. The default value of this flag is set in each language-specific code generator (e.g. Python, Java, go...)using the method toModelName. Note to developers supporting a language generator in OpenAPITools; to fully support the discriminator attribute as defined in the OAS specification 3.x, language generators should set this flag to true by default; however this requires updating the mustache templates to generate a language-specific discriminator lookup function that iterates over {{#mappedModels}} and does not iterate over {{children}}, {{#anyOf}}, or {{#oneOf}}.|
**true**
The mapping in the discriminator includes descendent schemas that allOf inherit from self and the discriminator mapping schemas in the OAS document.
**false**
The mapping in the discriminator includes any descendent schemas that allOf inherit from self, any oneOf schemas, any anyOf schemas, any x-discriminator-values, and the discriminator mapping schemas in the OAS document AND Codegen validates that oneOf and anyOf schemas contain the required discriminator and throws an error if the discriminator is missing.
|true| |packageName|python package name (convention: snake_case).| |openapi_server| |packageVersion|python package version.| |1.0.0| |prependFormOrBodyParameters|Add form or body parameters to the beginning of the parameter list.| |false| +|pythonSrcRoot|put python sources in this subdirectory of output folder (defaults to "" for). Use this for src/ layout.| || |serverPort|TCP port to listen to in app.run| |8080| |sortModelPropertiesByRequiredFlag|Sort model properties to place required parameters before optional parameters.| |true| |sortParamsByRequiredFlag|Sort method arguments to place required parameters before optional parameters.| |true| diff --git a/docs/generators/python-blueplanet.md b/docs/generators/python-blueplanet.md index 356d5847fa7b..2192715c9850 100644 --- a/docs/generators/python-blueplanet.md +++ b/docs/generators/python-blueplanet.md @@ -9,9 +9,11 @@ sidebar_label: python-blueplanet |controllerPackage|controller package| |controllers| |defaultController|default controller| |default_controller| |ensureUniqueParams|Whether to ensure parameter names are unique in an operation (rename parameters that are not).| |true| +|legacyDiscriminatorBehavior|This flag is used by OpenAPITools codegen to influence the processing of the discriminator attribute in OpenAPI documents. This flag has no impact if the OAS document does not use the discriminator attribute. The default value of this flag is set in each language-specific code generator (e.g. Python, Java, go...)using the method toModelName. Note to developers supporting a language generator in OpenAPITools; to fully support the discriminator attribute as defined in the OAS specification 3.x, language generators should set this flag to true by default; however this requires updating the mustache templates to generate a language-specific discriminator lookup function that iterates over {{#mappedModels}} and does not iterate over {{children}}, {{#anyOf}}, or {{#oneOf}}.|
**true**
The mapping in the discriminator includes descendent schemas that allOf inherit from self and the discriminator mapping schemas in the OAS document.
**false**
The mapping in the discriminator includes any descendent schemas that allOf inherit from self, any oneOf schemas, any anyOf schemas, any x-discriminator-values, and the discriminator mapping schemas in the OAS document AND Codegen validates that oneOf and anyOf schemas contain the required discriminator and throws an error if the discriminator is missing.
|true| |packageName|python package name (convention: snake_case).| |openapi_server| |packageVersion|python package version.| |1.0.0| |prependFormOrBodyParameters|Add form or body parameters to the beginning of the parameter list.| |false| +|pythonSrcRoot|put python sources in this subdirectory of output folder (defaults to "" for). Use this for src/ layout.| || |serverPort|TCP port to listen to in app.run| |8080| |sortModelPropertiesByRequiredFlag|Sort model properties to place required parameters before optional parameters.| |true| |sortParamsByRequiredFlag|Sort method arguments to place required parameters before optional parameters.| |true| diff --git a/docs/generators/python-experimental.md b/docs/generators/python-experimental.md index 8f3b02c7e566..546dcc22542a 100644 --- a/docs/generators/python-experimental.md +++ b/docs/generators/python-experimental.md @@ -31,6 +31,7 @@ sidebar_label: python-experimental
  • bool
  • +
  • bytes
  • date
  • datetime
  • dict
  • diff --git a/docs/generators/python-flask.md b/docs/generators/python-flask.md index a800c98ce3bc..8a230e5fbad1 100644 --- a/docs/generators/python-flask.md +++ b/docs/generators/python-flask.md @@ -9,9 +9,11 @@ sidebar_label: python-flask |controllerPackage|controller package| |controllers| |defaultController|default controller| |default_controller| |ensureUniqueParams|Whether to ensure parameter names are unique in an operation (rename parameters that are not).| |true| +|legacyDiscriminatorBehavior|This flag is used by OpenAPITools codegen to influence the processing of the discriminator attribute in OpenAPI documents. This flag has no impact if the OAS document does not use the discriminator attribute. The default value of this flag is set in each language-specific code generator (e.g. Python, Java, go...)using the method toModelName. Note to developers supporting a language generator in OpenAPITools; to fully support the discriminator attribute as defined in the OAS specification 3.x, language generators should set this flag to true by default; however this requires updating the mustache templates to generate a language-specific discriminator lookup function that iterates over {{#mappedModels}} and does not iterate over {{children}}, {{#anyOf}}, or {{#oneOf}}.|
    **true**
    The mapping in the discriminator includes descendent schemas that allOf inherit from self and the discriminator mapping schemas in the OAS document.
    **false**
    The mapping in the discriminator includes any descendent schemas that allOf inherit from self, any oneOf schemas, any anyOf schemas, any x-discriminator-values, and the discriminator mapping schemas in the OAS document AND Codegen validates that oneOf and anyOf schemas contain the required discriminator and throws an error if the discriminator is missing.
    |true| |packageName|python package name (convention: snake_case).| |openapi_server| |packageVersion|python package version.| |1.0.0| |prependFormOrBodyParameters|Add form or body parameters to the beginning of the parameter list.| |false| +|pythonSrcRoot|put python sources in this subdirectory of output folder (defaults to "" for). Use this for src/ layout.| || |serverPort|TCP port to listen to in app.run| |8080| |sortModelPropertiesByRequiredFlag|Sort model properties to place required parameters before optional parameters.| |true| |sortParamsByRequiredFlag|Sort method arguments to place required parameters before optional parameters.| |true| diff --git a/docs/generators/python.md b/docs/generators/python.md index 3bd96b865bcb..7c4ff80016a1 100644 --- a/docs/generators/python.md +++ b/docs/generators/python.md @@ -31,6 +31,7 @@ sidebar_label: python
    • bool
    • +
    • bytes
    • date
    • datetime
    • dict
    • diff --git a/docs/generators/ruby.md b/docs/generators/ruby.md index 2475a797ec6c..72dc31253a7e 100644 --- a/docs/generators/ruby.md +++ b/docs/generators/ruby.md @@ -17,6 +17,7 @@ sidebar_label: ruby |gemSummary|gem summary. | |A ruby wrapper for the REST APIs| |gemVersion|gem version.| |1.0.0| |hideGenerationTimestamp|Hides the generation timestamp when files are generated.| |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}}.|
      **true**
      The mapping in the discriminator includes descendent schemas that allOf inherit from self and the discriminator mapping schemas in the OAS document.
      **false**
      The mapping in the discriminator includes any descendent schemas that allOf inherit from self, any oneOf schemas, any anyOf schemas, any x-discriminator-values, and the discriminator mapping schemas in the OAS document AND Codegen validates that oneOf and anyOf schemas contain the required discriminator and throws an error if the discriminator is missing.
      |true| |library|HTTP library template (sub-template) to use|
      **faraday**
      Faraday (https://github.com/lostisland/faraday) (Beta support)
      **typhoeus**
      Typhoeus >= 1.0.1 (https://github.com/typhoeus/typhoeus)
      |typhoeus| |moduleName|top module name (convention: CamelCase, usually corresponding to gem name).| |OpenAPIClient| |prependFormOrBodyParameters|Add form or body parameters to the beginning of the parameter list.| |false| diff --git a/docs/generators/scala-akka-http-server.md b/docs/generators/scala-akka-http-server.md new file mode 100644 index 000000000000..ce885201ee98 --- /dev/null +++ b/docs/generators/scala-akka-http-server.md @@ -0,0 +1,222 @@ +--- +title: Config Options for scala-akka-http-server +sidebar_label: scala-akka-http-server +--- + +| Option | Description | Values | Default | +| ------ | ----------- | ------ | ------- | +|akkaHttpVersion|The version of akka-http| |10.1.10| +|allowUnicodeIdentifiers|boolean, toggles whether unicode identifiers are allowed in names or not, default is false| |false| +|apiPackage|package for generated api classes| |null| +|artifactId|artifactId| |openapi-scala-akka-http-server| +|artifactVersion|artifact version in generated pom.xml. This also becomes part of the generated library's filename| |1.0.0| +|dateLibrary|Option. Date library to use|
      **joda**
      Joda (for legacy app)
      **java8**
      Java 8 native JSR310 (prefered for JDK 1.8+)
      |java8| +|ensureUniqueParams|Whether to ensure parameter names are unique in an operation (rename parameters that are not).| |true| +|groupId|groupId in generated pom.xml| |org.openapitools| +|invokerPackage|root package for generated code| |org.openapitools.server| +|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}}.|
      **true**
      The mapping in the discriminator includes descendent schemas that allOf inherit from self and the discriminator mapping schemas in the OAS document.
      **false**
      The mapping in the discriminator includes any descendent schemas that allOf inherit from self, any oneOf schemas, any anyOf schemas, any x-discriminator-values, and the discriminator mapping schemas in the OAS document AND Codegen validates that oneOf and anyOf schemas contain the required discriminator and throws an error if the discriminator is missing.
      |true| +|modelPackage|package for generated models| |null| +|modelPropertyNaming|Naming convention for the property: 'camelCase', 'PascalCase', 'snake_case' and 'original', which keeps the original name| |camelCase| +|prependFormOrBodyParameters|Add form or body parameters to the beginning of the parameter list.| |false| +|sortModelPropertiesByRequiredFlag|Sort model properties to place required parameters before optional parameters.| |true| +|sortParamsByRequiredFlag|Sort method arguments to place required parameters before optional parameters.| |true| +|sourceFolder|source folder for generated code| |null| + +## IMPORT MAPPING + +| Type/Alias | Imports | +| ---------- | ------- | +|Array|java.util.List| +|ArrayList|java.util.ArrayList| +|Date|java.util.Date| +|DateTime|org.joda.time.*| +|File|java.io.File| +|HashMap|java.util.HashMap| +|ListBuffer|scala.collection.mutable.ListBuffer| +|ListSet|scala.collection.immutable.ListSet| +|LocalDate|org.joda.time.*| +|LocalDateTime|org.joda.time.*| +|LocalTime|org.joda.time.*| +|Timestamp|java.sql.Timestamp| +|URI|java.net.URI| +|UUID|java.util.UUID| + + +## INSTANTIATION TYPES + +| Type/Alias | Instantiated By | +| ---------- | --------------- | +|array|ListBuffer| +|map|Map| +|set|Set| + + +## LANGUAGE PRIMITIVES + +
        +
      • Any
      • +
      • Array
      • +
      • Boolean
      • +
      • Double
      • +
      • Float
      • +
      • Int
      • +
      • List
      • +
      • Long
      • +
      • Map
      • +
      • Object
      • +
      • Seq
      • +
      • String
      • +
      • boolean
      • +
      + +## RESERVED WORDS + +
        +
      • abstract
      • +
      • case
      • +
      • catch
      • +
      • class
      • +
      • def
      • +
      • do
      • +
      • else
      • +
      • extends
      • +
      • false
      • +
      • final
      • +
      • finally
      • +
      • for
      • +
      • forsome
      • +
      • if
      • +
      • implicit
      • +
      • import
      • +
      • lazy
      • +
      • match
      • +
      • new
      • +
      • null
      • +
      • object
      • +
      • override
      • +
      • package
      • +
      • private
      • +
      • protected
      • +
      • return
      • +
      • sealed
      • +
      • super
      • +
      • this
      • +
      • throw
      • +
      • trait
      • +
      • true
      • +
      • try
      • +
      • type
      • +
      • val
      • +
      • var
      • +
      • while
      • +
      • with
      • +
      • yield
      • +
      + +## FEATURE SET + + +### Client Modification Feature +| Name | Supported | Defined By | +| ---- | --------- | ---------- | +|BasePath|✗|ToolingExtension +|Authorizations|✗|ToolingExtension +|UserAgent|✗|ToolingExtension + +### Data Type Feature +| Name | Supported | Defined By | +| ---- | --------- | ---------- | +|Custom|✗|OAS2,OAS3 +|Int32|✓|OAS2,OAS3 +|Int64|✓|OAS2,OAS3 +|Float|✓|OAS2,OAS3 +|Double|✓|OAS2,OAS3 +|Decimal|✓|ToolingExtension +|String|✓|OAS2,OAS3 +|Byte|✓|OAS2,OAS3 +|Binary|✓|OAS2,OAS3 +|Boolean|✓|OAS2,OAS3 +|Date|✓|OAS2,OAS3 +|DateTime|✓|OAS2,OAS3 +|Password|✓|OAS2,OAS3 +|File|✓|OAS2 +|Array|✓|OAS2,OAS3 +|Maps|✓|ToolingExtension +|CollectionFormat|✓|OAS2 +|CollectionFormatMulti|✓|OAS2 +|Enum|✓|OAS2,OAS3 +|ArrayOfEnum|✓|ToolingExtension +|ArrayOfModel|✓|ToolingExtension +|ArrayOfCollectionOfPrimitives|✓|ToolingExtension +|ArrayOfCollectionOfModel|✓|ToolingExtension +|ArrayOfCollectionOfEnum|✓|ToolingExtension +|MapOfEnum|✓|ToolingExtension +|MapOfModel|✓|ToolingExtension +|MapOfCollectionOfPrimitives|✓|ToolingExtension +|MapOfCollectionOfModel|✓|ToolingExtension +|MapOfCollectionOfEnum|✓|ToolingExtension + +### Documentation Feature +| Name | Supported | Defined By | +| ---- | --------- | ---------- | +|Readme|✓|ToolingExtension +|Model|✓|ToolingExtension +|Api|✓|ToolingExtension + +### Global Feature +| Name | Supported | Defined By | +| ---- | --------- | ---------- | +|Host|✓|OAS2,OAS3 +|BasePath|✓|OAS2,OAS3 +|Info|✓|OAS2,OAS3 +|Schemes|✗|OAS2,OAS3 +|PartialSchemes|✓|OAS2,OAS3 +|Consumes|✓|OAS2 +|Produces|✓|OAS2 +|ExternalDocumentation|✓|OAS2,OAS3 +|Examples|✓|OAS2,OAS3 +|XMLStructureDefinitions|✗|OAS2,OAS3 +|MultiServer|✗|OAS3 +|ParameterizedServer|✗|OAS3 +|ParameterStyling|✗|OAS3 +|Callbacks|✗|OAS3 +|LinkObjects|✗|OAS3 + +### Parameter Feature +| Name | Supported | Defined By | +| ---- | --------- | ---------- | +|Path|✓|OAS2,OAS3 +|Query|✓|OAS2,OAS3 +|Header|✓|OAS2,OAS3 +|Body|✓|OAS2 +|FormUnencoded|✓|OAS2 +|FormMultipart|✓|OAS2 +|Cookie|✗|OAS3 + +### Schema Support Feature +| Name | Supported | Defined By | +| ---- | --------- | ---------- | +|Simple|✓|OAS2,OAS3 +|Composite|✓|OAS2,OAS3 +|Polymorphism|✗|OAS2,OAS3 +|Union|✗|OAS3 + +### Security Feature +| Name | Supported | Defined By | +| ---- | --------- | ---------- | +|BasicAuth|✓|OAS2,OAS3 +|ApiKey|✓|OAS2,OAS3 +|OpenIDConnect|✗|OAS3 +|BearerToken|✓|OAS3 +|OAuth2_Implicit|✗|OAS2,OAS3 +|OAuth2_Password|✗|OAS2,OAS3 +|OAuth2_ClientCredentials|✗|OAS2,OAS3 +|OAuth2_AuthorizationCode|✗|OAS2,OAS3 + +### Wire Format Feature +| Name | Supported | Defined By | +| ---- | --------- | ---------- | +|JSON|✓|OAS2,OAS3 +|XML|✓|OAS2,OAS3 +|PROTOBUF|✗|ToolingExtension +|Custom|✓|OAS2,OAS3 diff --git a/docs/generators/scala-akka-http.md b/docs/generators/scala-akka-http.md new file mode 100644 index 000000000000..88f96cb531fd --- /dev/null +++ b/docs/generators/scala-akka-http.md @@ -0,0 +1,221 @@ +--- +title: Config Options for scala-akka-http +sidebar_label: scala-akka-http +--- + +| Option | Description | Values | Default | +| ------ | ----------- | ------ | ------- | +|akkaHttpVersion|The version of akka-http| |10.1.10| +|allowUnicodeIdentifiers|boolean, toggles whether unicode identifiers are allowed in names or not, default is false| |false| +|apiPackage|package for generated api classes| |null| +|artifactId|artifactId| |openapi-scala-akka-http-server| +|artifactVersion|artifact version in generated pom.xml. This also becomes part of the generated library's filename| |1.0.0| +|dateLibrary|Option. Date library to use|
      **joda**
      Joda (for legacy app)
      **java8**
      Java 8 native JSR310 (prefered for JDK 1.8+)
      |java8| +|ensureUniqueParams|Whether to ensure parameter names are unique in an operation (rename parameters that are not).| |true| +|groupId|groupId in generated pom.xml| |org.openapitools| +|invokerPackage|root package for generated code| |org.openapitools.server| +|modelPackage|package for generated models| |null| +|modelPropertyNaming|Naming convention for the property: 'camelCase', 'PascalCase', 'snake_case' and 'original', which keeps the original name| |camelCase| +|prependFormOrBodyParameters|Add form or body parameters to the beginning of the parameter list.| |false| +|sortModelPropertiesByRequiredFlag|Sort model properties to place required parameters before optional parameters.| |true| +|sortParamsByRequiredFlag|Sort method arguments to place required parameters before optional parameters.| |true| +|sourceFolder|source folder for generated code| |null| + +## IMPORT MAPPING + +| Type/Alias | Imports | +| ---------- | ------- | +|Array|java.util.List| +|ArrayList|java.util.ArrayList| +|Date|java.util.Date| +|DateTime|org.joda.time.*| +|File|java.io.File| +|HashMap|java.util.HashMap| +|ListBuffer|scala.collection.mutable.ListBuffer| +|ListSet|scala.collection.immutable.ListSet| +|LocalDate|org.joda.time.*| +|LocalDateTime|org.joda.time.*| +|LocalTime|org.joda.time.*| +|Timestamp|java.sql.Timestamp| +|URI|java.net.URI| +|UUID|java.util.UUID| + + +## INSTANTIATION TYPES + +| Type/Alias | Instantiated By | +| ---------- | --------------- | +|array|ListBuffer| +|map|Map| +|set|Set| + + +## LANGUAGE PRIMITIVES + +
        +
      • Any
      • +
      • Array
      • +
      • Boolean
      • +
      • Double
      • +
      • Float
      • +
      • Int
      • +
      • List
      • +
      • Long
      • +
      • Map
      • +
      • Object
      • +
      • Seq
      • +
      • String
      • +
      • boolean
      • +
      + +## RESERVED WORDS + +
        +
      • abstract
      • +
      • case
      • +
      • catch
      • +
      • class
      • +
      • def
      • +
      • do
      • +
      • else
      • +
      • extends
      • +
      • false
      • +
      • final
      • +
      • finally
      • +
      • for
      • +
      • forsome
      • +
      • if
      • +
      • implicit
      • +
      • import
      • +
      • lazy
      • +
      • match
      • +
      • new
      • +
      • null
      • +
      • object
      • +
      • override
      • +
      • package
      • +
      • private
      • +
      • protected
      • +
      • return
      • +
      • sealed
      • +
      • super
      • +
      • this
      • +
      • throw
      • +
      • trait
      • +
      • true
      • +
      • try
      • +
      • type
      • +
      • val
      • +
      • var
      • +
      • while
      • +
      • with
      • +
      • yield
      • +
      + +## FEATURE SET + + +### Client Modification Feature +| Name | Supported | Defined By | +| ---- | --------- | ---------- | +|BasePath|✗|ToolingExtension +|Authorizations|✗|ToolingExtension +|UserAgent|✗|ToolingExtension + +### Data Type Feature +| Name | Supported | Defined By | +| ---- | --------- | ---------- | +|Custom|✗|OAS2,OAS3 +|Int32|✓|OAS2,OAS3 +|Int64|✓|OAS2,OAS3 +|Float|✓|OAS2,OAS3 +|Double|✓|OAS2,OAS3 +|Decimal|✓|ToolingExtension +|String|✓|OAS2,OAS3 +|Byte|✓|OAS2,OAS3 +|Binary|✓|OAS2,OAS3 +|Boolean|✓|OAS2,OAS3 +|Date|✓|OAS2,OAS3 +|DateTime|✓|OAS2,OAS3 +|Password|✓|OAS2,OAS3 +|File|✓|OAS2 +|Array|✓|OAS2,OAS3 +|Maps|✓|ToolingExtension +|CollectionFormat|✓|OAS2 +|CollectionFormatMulti|✓|OAS2 +|Enum|✓|OAS2,OAS3 +|ArrayOfEnum|✓|ToolingExtension +|ArrayOfModel|✓|ToolingExtension +|ArrayOfCollectionOfPrimitives|✓|ToolingExtension +|ArrayOfCollectionOfModel|✓|ToolingExtension +|ArrayOfCollectionOfEnum|✓|ToolingExtension +|MapOfEnum|✓|ToolingExtension +|MapOfModel|✓|ToolingExtension +|MapOfCollectionOfPrimitives|✓|ToolingExtension +|MapOfCollectionOfModel|✓|ToolingExtension +|MapOfCollectionOfEnum|✓|ToolingExtension + +### Documentation Feature +| Name | Supported | Defined By | +| ---- | --------- | ---------- | +|Readme|✓|ToolingExtension +|Model|✓|ToolingExtension +|Api|✓|ToolingExtension + +### Global Feature +| Name | Supported | Defined By | +| ---- | --------- | ---------- | +|Host|✓|OAS2,OAS3 +|BasePath|✓|OAS2,OAS3 +|Info|✓|OAS2,OAS3 +|Schemes|✗|OAS2,OAS3 +|PartialSchemes|✓|OAS2,OAS3 +|Consumes|✓|OAS2 +|Produces|✓|OAS2 +|ExternalDocumentation|✓|OAS2,OAS3 +|Examples|✓|OAS2,OAS3 +|XMLStructureDefinitions|✗|OAS2,OAS3 +|MultiServer|✗|OAS3 +|ParameterizedServer|✗|OAS3 +|ParameterStyling|✗|OAS3 +|Callbacks|✗|OAS3 +|LinkObjects|✗|OAS3 + +### Parameter Feature +| Name | Supported | Defined By | +| ---- | --------- | ---------- | +|Path|✓|OAS2,OAS3 +|Query|✓|OAS2,OAS3 +|Header|✓|OAS2,OAS3 +|Body|✓|OAS2 +|FormUnencoded|✓|OAS2 +|FormMultipart|✓|OAS2 +|Cookie|✗|OAS3 + +### Schema Support Feature +| Name | Supported | Defined By | +| ---- | --------- | ---------- | +|Simple|✓|OAS2,OAS3 +|Composite|✓|OAS2,OAS3 +|Polymorphism|✗|OAS2,OAS3 +|Union|✗|OAS3 + +### Security Feature +| Name | Supported | Defined By | +| ---- | --------- | ---------- | +|BasicAuth|✓|OAS2,OAS3 +|ApiKey|✓|OAS2,OAS3 +|OpenIDConnect|✗|OAS3 +|BearerToken|✓|OAS3 +|OAuth2_Implicit|✗|OAS2,OAS3 +|OAuth2_Password|✗|OAS2,OAS3 +|OAuth2_ClientCredentials|✗|OAS2,OAS3 +|OAuth2_AuthorizationCode|✗|OAS2,OAS3 + +### Wire Format Feature +| Name | Supported | Defined By | +| ---- | --------- | ---------- | +|JSON|✓|OAS2,OAS3 +|XML|✓|OAS2,OAS3 +|PROTOBUF|✗|ToolingExtension +|Custom|✓|OAS2,OAS3 diff --git a/docs/generators/scala-akka.md b/docs/generators/scala-akka.md index ad8c5d485cf1..0faa17e202b7 100644 --- a/docs/generators/scala-akka.md +++ b/docs/generators/scala-akka.md @@ -9,6 +9,7 @@ sidebar_label: scala-akka |apiPackage|package for generated api classes| |null| |dateLibrary|Option. Date library to use|
      **joda**
      Joda (for legacy app)
      **java8**
      Java 8 native JSR310 (prefered for JDK 1.8+)
      |java8| |ensureUniqueParams|Whether to ensure parameter names are unique in an operation (rename parameters that are not).| |true| +|legacyDiscriminatorBehavior|This flag is used by OpenAPITools codegen to influence the processing of the discriminator attribute in OpenAPI documents. This flag has no impact if the OAS document does not use the discriminator attribute. The default value of this flag is set in each language-specific code generator (e.g. Python, Java, go...)using the method toModelName. Note to developers supporting a language generator in OpenAPITools; to fully support the discriminator attribute as defined in the OAS specification 3.x, language generators should set this flag to true by default; however this requires updating the mustache templates to generate a language-specific discriminator lookup function that iterates over {{#mappedModels}} and does not iterate over {{children}}, {{#anyOf}}, or {{#oneOf}}.|
      **true**
      The mapping in the discriminator includes descendent schemas that allOf inherit from self and the discriminator mapping schemas in the OAS document.
      **false**
      The mapping in the discriminator includes any descendent schemas that allOf inherit from self, any oneOf schemas, any anyOf schemas, any x-discriminator-values, and the discriminator mapping schemas in the OAS document AND Codegen validates that oneOf and anyOf schemas contain the required discriminator and throws an error if the discriminator is missing.
      |true| |mainPackage|Top-level package name, which defines 'apiPackage', 'modelPackage', 'invokerPackage'| |org.openapitools.client| |modelPackage|package for generated models| |null| |modelPropertyNaming|Naming convention for the property: 'camelCase', 'PascalCase', 'snake_case' and 'original', which keeps the original name| |camelCase| diff --git a/docs/generators/scala-gatling.md b/docs/generators/scala-gatling.md index 0e1e748245e1..3a957c1cb097 100644 --- a/docs/generators/scala-gatling.md +++ b/docs/generators/scala-gatling.md @@ -9,6 +9,7 @@ sidebar_label: scala-gatling |apiPackage|package for generated api classes| |null| |dateLibrary|Option. Date library to use|
      **joda**
      Joda (for legacy app)
      **java8**
      Java 8 native JSR310 (prefered for JDK 1.8+)
      |java8| |ensureUniqueParams|Whether to ensure parameter names are unique in an operation (rename parameters that are not).| |true| +|legacyDiscriminatorBehavior|This flag is used by OpenAPITools codegen to influence the processing of the discriminator attribute in OpenAPI documents. This flag has no impact if the OAS document does not use the discriminator attribute. The default value of this flag is set in each language-specific code generator (e.g. Python, Java, go...)using the method toModelName. Note to developers supporting a language generator in OpenAPITools; to fully support the discriminator attribute as defined in the OAS specification 3.x, language generators should set this flag to true by default; however this requires updating the mustache templates to generate a language-specific discriminator lookup function that iterates over {{#mappedModels}} and does not iterate over {{children}}, {{#anyOf}}, or {{#oneOf}}.|
      **true**
      The mapping in the discriminator includes descendent schemas that allOf inherit from self and the discriminator mapping schemas in the OAS document.
      **false**
      The mapping in the discriminator includes any descendent schemas that allOf inherit from self, any oneOf schemas, any anyOf schemas, any x-discriminator-values, and the discriminator mapping schemas in the OAS document AND Codegen validates that oneOf and anyOf schemas contain the required discriminator and throws an error if the discriminator is missing.
      |true| |modelPackage|package for generated models| |null| |modelPropertyNaming|Naming convention for the property: 'camelCase', 'PascalCase', 'snake_case' and 'original', which keeps the original name| |camelCase| |prependFormOrBodyParameters|Add form or body parameters to the beginning of the parameter list.| |false| diff --git a/docs/generators/scala-httpclient-deprecated.md b/docs/generators/scala-httpclient-deprecated.md index febeca9a6900..0a4015fbac0a 100644 --- a/docs/generators/scala-httpclient-deprecated.md +++ b/docs/generators/scala-httpclient-deprecated.md @@ -9,6 +9,7 @@ sidebar_label: scala-httpclient-deprecated |apiPackage|package for generated api classes| |null| |dateLibrary|Option. Date library to use|
      **joda**
      Joda (for legacy app)
      **java8**
      Java 8 native JSR310 (prefered for JDK 1.8+)
      |java8| |ensureUniqueParams|Whether to ensure parameter names are unique in an operation (rename parameters that are not).| |true| +|legacyDiscriminatorBehavior|This flag is used by OpenAPITools codegen to influence the processing of the discriminator attribute in OpenAPI documents. This flag has no impact if the OAS document does not use the discriminator attribute. The default value of this flag is set in each language-specific code generator (e.g. Python, Java, go...)using the method toModelName. Note to developers supporting a language generator in OpenAPITools; to fully support the discriminator attribute as defined in the OAS specification 3.x, language generators should set this flag to true by default; however this requires updating the mustache templates to generate a language-specific discriminator lookup function that iterates over {{#mappedModels}} and does not iterate over {{children}}, {{#anyOf}}, or {{#oneOf}}.|
      **true**
      The mapping in the discriminator includes descendent schemas that allOf inherit from self and the discriminator mapping schemas in the OAS document.
      **false**
      The mapping in the discriminator includes any descendent schemas that allOf inherit from self, any oneOf schemas, any anyOf schemas, any x-discriminator-values, and the discriminator mapping schemas in the OAS document AND Codegen validates that oneOf and anyOf schemas contain the required discriminator and throws an error if the discriminator is missing.
      |true| |modelPackage|package for generated models| |null| |modelPropertyNaming|Naming convention for the property: 'camelCase', 'PascalCase', 'snake_case' and 'original', which keeps the original name| |camelCase| |prependFormOrBodyParameters|Add form or body parameters to the beginning of the parameter list.| |false| diff --git a/docs/generators/scala-lagom-server.md b/docs/generators/scala-lagom-server.md index 99b43af7d58c..cef8bf855c0d 100644 --- a/docs/generators/scala-lagom-server.md +++ b/docs/generators/scala-lagom-server.md @@ -9,6 +9,7 @@ sidebar_label: scala-lagom-server |apiPackage|package for generated api classes| |null| |dateLibrary|Option. Date library to use|
      **joda**
      Joda (for legacy app)
      **java8**
      Java 8 native JSR310 (prefered for JDK 1.8+)
      |java8| |ensureUniqueParams|Whether to ensure parameter names are unique in an operation (rename parameters that are not).| |true| +|legacyDiscriminatorBehavior|This flag is used by OpenAPITools codegen to influence the processing of the discriminator attribute in OpenAPI documents. This flag has no impact if the OAS document does not use the discriminator attribute. The default value of this flag is set in each language-specific code generator (e.g. Python, Java, go...)using the method toModelName. Note to developers supporting a language generator in OpenAPITools; to fully support the discriminator attribute as defined in the OAS specification 3.x, language generators should set this flag to true by default; however this requires updating the mustache templates to generate a language-specific discriminator lookup function that iterates over {{#mappedModels}} and does not iterate over {{children}}, {{#anyOf}}, or {{#oneOf}}.|
      **true**
      The mapping in the discriminator includes descendent schemas that allOf inherit from self and the discriminator mapping schemas in the OAS document.
      **false**
      The mapping in the discriminator includes any descendent schemas that allOf inherit from self, any oneOf schemas, any anyOf schemas, any x-discriminator-values, and the discriminator mapping schemas in the OAS document AND Codegen validates that oneOf and anyOf schemas contain the required discriminator and throws an error if the discriminator is missing.
      |true| |modelPackage|package for generated models| |null| |modelPropertyNaming|Naming convention for the property: 'camelCase', 'PascalCase', 'snake_case' and 'original', which keeps the original name| |camelCase| |prependFormOrBodyParameters|Add form or body parameters to the beginning of the parameter list.| |false| diff --git a/docs/generators/scala-play-server.md b/docs/generators/scala-play-server.md index 57bdf5d70ed8..dea0eb49248a 100644 --- a/docs/generators/scala-play-server.md +++ b/docs/generators/scala-play-server.md @@ -10,6 +10,7 @@ sidebar_label: scala-play-server |basePackage|Base package in which supporting classes are generated.| |org.openapitools| |ensureUniqueParams|Whether to ensure parameter names are unique in an operation (rename parameters that are not).| |true| |generateCustomExceptions|If set, generates custom exception types.| |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}}.|
      **true**
      The mapping in the discriminator includes descendent schemas that allOf inherit from self and the discriminator mapping schemas in the OAS document.
      **false**
      The mapping in the discriminator includes any descendent schemas that allOf inherit from self, any oneOf schemas, any anyOf schemas, any x-discriminator-values, and the discriminator mapping schemas in the OAS document AND Codegen validates that oneOf and anyOf schemas contain the required discriminator and throws an error if the discriminator is missing.
      |true| |modelPackage|package for generated models| |null| |modelPropertyNaming|Naming convention for the property: 'camelCase', 'PascalCase', 'snake_case' and 'original', which keeps the original name| |camelCase| |prependFormOrBodyParameters|Add form or body parameters to the beginning of the parameter list.| |false| diff --git a/docs/generators/scala-sttp.md b/docs/generators/scala-sttp.md index 5c277bf9dcc2..27a8b862b10d 100644 --- a/docs/generators/scala-sttp.md +++ b/docs/generators/scala-sttp.md @@ -9,6 +9,7 @@ sidebar_label: scala-sttp |apiPackage|package for generated api classes| |null| |dateLibrary|Option. Date library to use|
      **joda**
      Joda (for legacy app)
      **java8**
      Java 8 native JSR310 (prefered for JDK 1.8+)
      |java8| |ensureUniqueParams|Whether to ensure parameter names are unique in an operation (rename parameters that are not).| |true| +|legacyDiscriminatorBehavior|This flag is used by OpenAPITools codegen to influence the processing of the discriminator attribute in OpenAPI documents. This flag has no impact if the OAS document does not use the discriminator attribute. The default value of this flag is set in each language-specific code generator (e.g. Python, Java, go...)using the method toModelName. Note to developers supporting a language generator in OpenAPITools; to fully support the discriminator attribute as defined in the OAS specification 3.x, language generators should set this flag to true by default; however this requires updating the mustache templates to generate a language-specific discriminator lookup function that iterates over {{#mappedModels}} and does not iterate over {{children}}, {{#anyOf}}, or {{#oneOf}}.|
      **true**
      The mapping in the discriminator includes descendent schemas that allOf inherit from self and the discriminator mapping schemas in the OAS document.
      **false**
      The mapping in the discriminator includes any descendent schemas that allOf inherit from self, any oneOf schemas, any anyOf schemas, any x-discriminator-values, and the discriminator mapping schemas in the OAS document AND Codegen validates that oneOf and anyOf schemas contain the required discriminator and throws an error if the discriminator is missing.
      |true| |mainPackage|Top-level package name, which defines 'apiPackage', 'modelPackage', 'invokerPackage'| |org.openapitools.client| |modelPackage|package for generated models| |null| |modelPropertyNaming|Naming convention for the property: 'camelCase', 'PascalCase', 'snake_case' and 'original', which keeps the original name| |camelCase| diff --git a/docs/generators/scalatra.md b/docs/generators/scalatra.md index af71e32aa463..39eb4dc8ca6c 100644 --- a/docs/generators/scalatra.md +++ b/docs/generators/scalatra.md @@ -9,6 +9,7 @@ sidebar_label: scalatra |apiPackage|package for generated api classes| |null| |dateLibrary|Option. Date library to use|
      **joda**
      Joda (for legacy app)
      **java8**
      Java 8 native JSR310 (prefered for JDK 1.8+)
      |java8| |ensureUniqueParams|Whether to ensure parameter names are unique in an operation (rename parameters that are not).| |true| +|legacyDiscriminatorBehavior|This flag is used by OpenAPITools codegen to influence the processing of the discriminator attribute in OpenAPI documents. This flag has no impact if the OAS document does not use the discriminator attribute. The default value of this flag is set in each language-specific code generator (e.g. Python, Java, go...)using the method toModelName. Note to developers supporting a language generator in OpenAPITools; to fully support the discriminator attribute as defined in the OAS specification 3.x, language generators should set this flag to true by default; however this requires updating the mustache templates to generate a language-specific discriminator lookup function that iterates over {{#mappedModels}} and does not iterate over {{children}}, {{#anyOf}}, or {{#oneOf}}.|
      **true**
      The mapping in the discriminator includes descendent schemas that allOf inherit from self and the discriminator mapping schemas in the OAS document.
      **false**
      The mapping in the discriminator includes any descendent schemas that allOf inherit from self, any oneOf schemas, any anyOf schemas, any x-discriminator-values, and the discriminator mapping schemas in the OAS document AND Codegen validates that oneOf and anyOf schemas contain the required discriminator and throws an error if the discriminator is missing.
      |true| |modelPackage|package for generated models| |null| |modelPropertyNaming|Naming convention for the property: 'camelCase', 'PascalCase', 'snake_case' and 'original', which keeps the original name| |camelCase| |prependFormOrBodyParameters|Add form or body parameters to the beginning of the parameter list.| |false| diff --git a/docs/generators/scalaz.md b/docs/generators/scalaz.md index aa2f6121ca13..f8279d1df61a 100644 --- a/docs/generators/scalaz.md +++ b/docs/generators/scalaz.md @@ -9,6 +9,7 @@ sidebar_label: scalaz |apiPackage|package for generated api classes| |null| |dateLibrary|Option. Date library to use|
      **joda**
      Joda (for legacy app)
      **java8**
      Java 8 native JSR310 (prefered for JDK 1.8+)
      |java8| |ensureUniqueParams|Whether to ensure parameter names are unique in an operation (rename parameters that are not).| |true| +|legacyDiscriminatorBehavior|This flag is used by OpenAPITools codegen to influence the processing of the discriminator attribute in OpenAPI documents. This flag has no impact if the OAS document does not use the discriminator attribute. The default value of this flag is set in each language-specific code generator (e.g. Python, Java, go...)using the method toModelName. Note to developers supporting a language generator in OpenAPITools; to fully support the discriminator attribute as defined in the OAS specification 3.x, language generators should set this flag to true by default; however this requires updating the mustache templates to generate a language-specific discriminator lookup function that iterates over {{#mappedModels}} and does not iterate over {{children}}, {{#anyOf}}, or {{#oneOf}}.|
      **true**
      The mapping in the discriminator includes descendent schemas that allOf inherit from self and the discriminator mapping schemas in the OAS document.
      **false**
      The mapping in the discriminator includes any descendent schemas that allOf inherit from self, any oneOf schemas, any anyOf schemas, any x-discriminator-values, and the discriminator mapping schemas in the OAS document AND Codegen validates that oneOf and anyOf schemas contain the required discriminator and throws an error if the discriminator is missing.
      |true| |modelPackage|package for generated models| |null| |modelPropertyNaming|Naming convention for the property: 'camelCase', 'PascalCase', 'snake_case' and 'original', which keeps the original name| |camelCase| |prependFormOrBodyParameters|Add form or body parameters to the beginning of the parameter list.| |false| diff --git a/docs/generators/spring.md b/docs/generators/spring.md index e981672bff32..93159837dd49 100644 --- a/docs/generators/spring.md +++ b/docs/generators/spring.md @@ -25,6 +25,7 @@ sidebar_label: spring |developerOrganization|developer organization in generated pom.xml| |OpenAPITools.org| |developerOrganizationUrl|developer organization URL in generated pom.xml| |http://openapitools.org| |disableHtmlEscaping|Disable HTML escaping of JSON strings when using gson (needed to avoid problems with byte[] fields)| |false| +|discriminatorCaseSensitive|Whether the discriminator value lookup should be case-sensitive or not. This option only works for Java API client| |true| |ensureUniqueParams|Whether to ensure parameter names are unique in an operation (rename parameters that are not).| |true| |fullJavaUtil|whether to use fully qualified name for classes under java.util. This option only works for Java API client| |false| |groupId|groupId in generated pom.xml| |org.openapitools| @@ -34,6 +35,7 @@ sidebar_label: spring |interfaceOnly|Whether to generate only API interface stubs without the server files.| |false| |invokerPackage|root package for generated code| |org.openapitools.api| |java8|Option. Use Java8 classes instead of third party equivalents|
      **true**
      Use Java 8 classes such as Base64. Use java8 default interface when a responseWrapper is used
      **false**
      Various third party libraries as needed
      |false| +|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}}.|
      **true**
      The mapping in the discriminator includes descendent schemas that allOf inherit from self and the discriminator mapping schemas in the OAS document.
      **false**
      The mapping in the discriminator includes any descendent schemas that allOf inherit from self, any oneOf schemas, any anyOf schemas, any x-discriminator-values, and the discriminator mapping schemas in the OAS document AND Codegen validates that oneOf and anyOf schemas contain the required discriminator and throws an error if the discriminator is missing.
      |true| |library|library template (sub-template)|
      **spring-boot**
      Spring-boot Server application using the SpringFox integration.
      **spring-mvc**
      Spring-MVC Server application using the SpringFox integration.
      **spring-cloud**
      Spring-Cloud-Feign client with Spring-Boot auto-configured settings.
      |spring-boot| |licenseName|The name of the license| |Unlicense| |licenseUrl|The URL of the license| |http://unlicense.org| diff --git a/docs/generators/swift2-deprecated.md b/docs/generators/swift2-deprecated.md index fe739bc109a2..76adbe1b0ec3 100644 --- a/docs/generators/swift2-deprecated.md +++ b/docs/generators/swift2-deprecated.md @@ -8,6 +8,7 @@ sidebar_label: swift2-deprecated |allowUnicodeIdentifiers|boolean, toggles whether unicode identifiers are allowed in names or not, default is false| |false| |ensureUniqueParams|Whether to ensure parameter names are unique in an operation (rename parameters that are not).| |true| |hideGenerationTimestamp|Hides the generation timestamp when files are generated.| |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}}.|
      **true**
      The mapping in the discriminator includes descendent schemas that allOf inherit from self and the discriminator mapping schemas in the OAS document.
      **false**
      The mapping in the discriminator includes any descendent schemas that allOf inherit from self, any oneOf schemas, any anyOf schemas, any x-discriminator-values, and the discriminator mapping schemas in the OAS document AND Codegen validates that oneOf and anyOf schemas contain the required discriminator and throws an error if the discriminator is missing.
      |true| |podAuthors|Authors used for Podspec| |null| |podDescription|Description used for Podspec| |null| |podDocsetURL|Docset URL used for Podspec| |null| diff --git a/docs/generators/swift3-deprecated.md b/docs/generators/swift3-deprecated.md index 7f1997eaef95..4d775405c98d 100644 --- a/docs/generators/swift3-deprecated.md +++ b/docs/generators/swift3-deprecated.md @@ -8,6 +8,7 @@ sidebar_label: swift3-deprecated |allowUnicodeIdentifiers|boolean, toggles whether unicode identifiers are allowed in names or not, default is false| |false| |ensureUniqueParams|Whether to ensure parameter names are unique in an operation (rename parameters that are not).| |true| |hideGenerationTimestamp|Hides the generation timestamp when files are generated.| |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}}.|
      **true**
      The mapping in the discriminator includes descendent schemas that allOf inherit from self and the discriminator mapping schemas in the OAS document.
      **false**
      The mapping in the discriminator includes any descendent schemas that allOf inherit from self, any oneOf schemas, any anyOf schemas, any x-discriminator-values, and the discriminator mapping schemas in the OAS document AND Codegen validates that oneOf and anyOf schemas contain the required discriminator and throws an error if the discriminator is missing.
      |true| |lenientTypeCast|Accept and cast values for simple types (string->bool, string->int, int->string)| |false| |objcCompatible|Add additional properties and methods for Objective-C compatibility (default: false)| |null| |podAuthors|Authors used for Podspec| |null| diff --git a/docs/generators/swift4.md b/docs/generators/swift4.md index f4c589c02eab..df9bc30f7ac6 100644 --- a/docs/generators/swift4.md +++ b/docs/generators/swift4.md @@ -8,6 +8,7 @@ sidebar_label: swift4 |allowUnicodeIdentifiers|boolean, toggles whether unicode identifiers are allowed in names or not, default is false| |false| |ensureUniqueParams|Whether to ensure parameter names are unique in an operation (rename parameters that are not).| |true| |hideGenerationTimestamp|Hides the generation timestamp when files are generated.| |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}}.|
      **true**
      The mapping in the discriminator includes descendent schemas that allOf inherit from self and the discriminator mapping schemas in the OAS document.
      **false**
      The mapping in the discriminator includes any descendent schemas that allOf inherit from self, any oneOf schemas, any anyOf schemas, any x-discriminator-values, and the discriminator mapping schemas in the OAS document AND Codegen validates that oneOf and anyOf schemas contain the required discriminator and throws an error if the discriminator is missing.
      |true| |lenientTypeCast|Accept and cast values for simple types (string->bool, string->int, int->string)| |false| |nonPublicApi|Generates code with reduced access modifiers; allows embedding elsewhere without exposing non-public API calls to consumers.(default: false)| |null| |objcCompatible|Add additional properties and methods for Objective-C compatibility (default: false)| |null| diff --git a/docs/generators/swift5.md b/docs/generators/swift5.md index 52a75bd93b1a..9b172cdf785a 100644 --- a/docs/generators/swift5.md +++ b/docs/generators/swift5.md @@ -9,6 +9,7 @@ sidebar_label: swift5 |apiNamePrefix|Prefix that will be appended to all API names ('tags'). Default: empty string. e.g. Pet => Pet.| |null| |ensureUniqueParams|Whether to ensure parameter names are unique in an operation (rename parameters that are not).| |true| |hideGenerationTimestamp|Hides the generation timestamp when files are generated.| |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}}.|
      **true**
      The mapping in the discriminator includes descendent schemas that allOf inherit from self and the discriminator mapping schemas in the OAS document.
      **false**
      The mapping in the discriminator includes any descendent schemas that allOf inherit from self, any oneOf schemas, any anyOf schemas, any x-discriminator-values, and the discriminator mapping schemas in the OAS document AND Codegen validates that oneOf and anyOf schemas contain the required discriminator and throws an error if the discriminator is missing.
      |true| |lenientTypeCast|Accept and cast values for simple types (string->bool, string->int, int->string)| |false| |library|Library template (sub-template) to use|
      **urlsession**
      [DEFAULT] HTTP client: URLSession
      **alamofire**
      HTTP client: Alamofire
      |urlsession| |nonPublicApi|Generates code with reduced access modifiers; allows embedding elsewhere without exposing non-public API calls to consumers.(default: false)| |null| @@ -25,6 +26,7 @@ sidebar_label: swift5 |podVersion|Version used for Podspec| |null| |prependFormOrBodyParameters|Add form or body parameters to the beginning of the parameter list.| |false| |projectName|Project name in Xcode| |null| +|readonlyProperties|Make properties readonly (default: false)| |null| |responseAs|Optionally use libraries to manage response. Currently PromiseKit, RxSwift, Result, Combine are available.| |null| |sortModelPropertiesByRequiredFlag|Sort model properties to place required parameters before optional parameters.| |true| |sortParamsByRequiredFlag|Sort method arguments to place required parameters before optional parameters.| |true| diff --git a/docs/generators/typescript-angular.md b/docs/generators/typescript-angular.md index f382194df4ab..c4048c19a5b1 100644 --- a/docs/generators/typescript-angular.md +++ b/docs/generators/typescript-angular.md @@ -11,6 +11,7 @@ sidebar_label: typescript-angular |enumNameSuffix|Suffix that will be appended to all enum names. A special 'v4-compat' value enables the backward-compatible behavior (as pre v4.2.3)| |v4-compat| |enumPropertyNaming|Naming convention for enum properties: 'camelCase', 'PascalCase', 'snake_case', 'UPPERCASE', and 'original'| |PascalCase| |fileNaming|Naming convention for the output files: 'camelCase', 'kebab-case'.| |camelCase| +|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}}.|
      **true**
      The mapping in the discriminator includes descendent schemas that allOf inherit from self and the discriminator mapping schemas in the OAS document.
      **false**
      The mapping in the discriminator includes any descendent schemas that allOf inherit from self, any oneOf schemas, any anyOf schemas, any x-discriminator-values, and the discriminator mapping schemas in the OAS document AND Codegen validates that oneOf and anyOf schemas contain the required discriminator and throws an error if the discriminator is missing.
      |true| |modelFileSuffix|The suffix of the file of the generated model (model<suffix>.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| diff --git a/docs/generators/typescript-angularjs.md b/docs/generators/typescript-angularjs.md index fbfd828ba323..546fff28cc31 100644 --- a/docs/generators/typescript-angularjs.md +++ b/docs/generators/typescript-angularjs.md @@ -9,6 +9,7 @@ sidebar_label: typescript-angularjs |ensureUniqueParams|Whether to ensure parameter names are unique in an operation (rename parameters that are not).| |true| |enumNameSuffix|Suffix that will be appended to all enum names. A special 'v4-compat' value enables the backward-compatible behavior (as pre v4.2.3)| |v4-compat| |enumPropertyNaming|Naming convention for enum properties: 'camelCase', 'PascalCase', 'snake_case', 'UPPERCASE', and 'original'| |PascalCase| +|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}}.|
      **true**
      The mapping in the discriminator includes descendent schemas that allOf inherit from self and the discriminator mapping schemas in the OAS document.
      **false**
      The mapping in the discriminator includes any descendent schemas that allOf inherit from self, any oneOf schemas, any anyOf schemas, any x-discriminator-values, and the discriminator mapping schemas in the OAS document AND Codegen validates that oneOf and anyOf schemas contain the required discriminator and throws an error if the discriminator is missing.
      |true| |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| |nullSafeAdditionalProps|Set to make additional properties types declare that their indexer may return undefined| |false| |prependFormOrBodyParameters|Add form or body parameters to the beginning of the parameter list.| |false| diff --git a/docs/generators/typescript-aurelia.md b/docs/generators/typescript-aurelia.md index 955079117b0e..02c2e8786abf 100644 --- a/docs/generators/typescript-aurelia.md +++ b/docs/generators/typescript-aurelia.md @@ -9,6 +9,7 @@ sidebar_label: typescript-aurelia |ensureUniqueParams|Whether to ensure parameter names are unique in an operation (rename parameters that are not).| |true| |enumNameSuffix|Suffix that will be appended to all enum names. A special 'v4-compat' value enables the backward-compatible behavior (as pre v4.2.3)| |v4-compat| |enumPropertyNaming|Naming convention for enum properties: 'camelCase', 'PascalCase', 'snake_case', 'UPPERCASE', and 'original'| |PascalCase| +|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}}.|
      **true**
      The mapping in the discriminator includes descendent schemas that allOf inherit from self and the discriminator mapping schemas in the OAS document.
      **false**
      The mapping in the discriminator includes any descendent schemas that allOf inherit from self, any oneOf schemas, any anyOf schemas, any x-discriminator-values, and the discriminator mapping schemas in the OAS document AND Codegen validates that oneOf and anyOf schemas contain the required discriminator and throws an error if the discriminator is missing.
      |true| |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| |npmName|The name under which you want to publish generated npm package. Required to generate a full package| |null| |npmVersion|The version of your npm package. If not provided, using the version from the OpenAPI specification file.| |1.0.0| diff --git a/docs/generators/typescript-axios.md b/docs/generators/typescript-axios.md index 5e65684a0e6e..b990ed95bd45 100644 --- a/docs/generators/typescript-axios.md +++ b/docs/generators/typescript-axios.md @@ -9,6 +9,7 @@ sidebar_label: typescript-axios |ensureUniqueParams|Whether to ensure parameter names are unique in an operation (rename parameters that are not).| |true| |enumNameSuffix|Suffix that will be appended to all enum names. A special 'v4-compat' value enables the backward-compatible behavior (as pre v4.2.3)| |v4-compat| |enumPropertyNaming|Naming convention for enum properties: 'camelCase', 'PascalCase', 'snake_case', 'UPPERCASE', and 'original'| |PascalCase| +|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}}.|
      **true**
      The mapping in the discriminator includes descendent schemas that allOf inherit from self and the discriminator mapping schemas in the OAS document.
      **false**
      The mapping in the discriminator includes any descendent schemas that allOf inherit from self, any oneOf schemas, any anyOf schemas, any x-discriminator-values, and the discriminator mapping schemas in the OAS document AND Codegen validates that oneOf and anyOf schemas contain the required discriminator and throws an error if the discriminator is missing.
      |true| |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| |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 of your private npmRepo in the package.json| |null| diff --git a/docs/generators/typescript-fetch.md b/docs/generators/typescript-fetch.md index af3dd9162686..f1a2226ece47 100644 --- a/docs/generators/typescript-fetch.md +++ b/docs/generators/typescript-fetch.md @@ -9,6 +9,7 @@ sidebar_label: typescript-fetch |ensureUniqueParams|Whether to ensure parameter names are unique in an operation (rename parameters that are not).| |true| |enumNameSuffix|Suffix that will be appended to all enum names. A special 'v4-compat' value enables the backward-compatible behavior (as pre v4.2.3)| |v4-compat| |enumPropertyNaming|Naming convention for enum properties: 'camelCase', 'PascalCase', 'snake_case', 'UPPERCASE', and 'original'| |PascalCase| +|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}}.|
      **true**
      The mapping in the discriminator includes descendent schemas that allOf inherit from self and the discriminator mapping schemas in the OAS document.
      **false**
      The mapping in the discriminator includes any descendent schemas that allOf inherit from self, any oneOf schemas, any anyOf schemas, any x-discriminator-values, and the discriminator mapping schemas in the OAS document AND Codegen validates that oneOf and anyOf schemas contain the required discriminator and throws an error if the discriminator is missing.
      |true| |modelPropertyNaming|Naming convention for the property: 'camelCase', 'PascalCase', 'snake_case' and 'original', which keeps the original name| |camelCase| |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| @@ -76,6 +77,7 @@ sidebar_label: typescript-fetch
    • HTTPHeaders
    • HTTPMethod
    • HTTPQuery
    • +
    • Index
    • JSONApiResponse
    • Middleware
    • ModelPropertyNaming
    • diff --git a/docs/generators/typescript-inversify.md b/docs/generators/typescript-inversify.md index 5d68c9f08399..4b321619e837 100644 --- a/docs/generators/typescript-inversify.md +++ b/docs/generators/typescript-inversify.md @@ -9,6 +9,7 @@ sidebar_label: typescript-inversify |ensureUniqueParams|Whether to ensure parameter names are unique in an operation (rename parameters that are not).| |true| |enumNameSuffix|Suffix that will be appended to all enum names. A special 'v4-compat' value enables the backward-compatible behavior (as pre v4.2.3)| |v4-compat| |enumPropertyNaming|Naming convention for enum properties: 'camelCase', 'PascalCase', 'snake_case', 'UPPERCASE', and 'original'| |PascalCase| +|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}}.|
      **true**
      The mapping in the discriminator includes descendent schemas that allOf inherit from self and the discriminator mapping schemas in the OAS document.
      **false**
      The mapping in the discriminator includes any descendent schemas that allOf inherit from self, any oneOf schemas, any anyOf schemas, any x-discriminator-values, and the discriminator mapping schemas in the OAS document AND Codegen validates that oneOf and anyOf schemas contain the required discriminator and throws an error if the discriminator is missing.
      |true| |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| |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| diff --git a/docs/generators/typescript-jquery.md b/docs/generators/typescript-jquery.md index 91d61cf31e10..b28d6b47cb93 100644 --- a/docs/generators/typescript-jquery.md +++ b/docs/generators/typescript-jquery.md @@ -10,6 +10,7 @@ sidebar_label: typescript-jquery |enumNameSuffix|Suffix that will be appended to all enum names. A special 'v4-compat' value enables the backward-compatible behavior (as pre v4.2.3)| |v4-compat| |enumPropertyNaming|Naming convention for enum properties: 'camelCase', 'PascalCase', 'snake_case', 'UPPERCASE', and 'original'| |PascalCase| |jqueryAlreadyImported|When using this in legacy app using mix of typescript and javascript, this will only declare jquery and not import it| |false| +|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}}.|
      **true**
      The mapping in the discriminator includes descendent schemas that allOf inherit from self and the discriminator mapping schemas in the OAS document.
      **false**
      The mapping in the discriminator includes any descendent schemas that allOf inherit from self, any oneOf schemas, any anyOf schemas, any x-discriminator-values, and the discriminator mapping schemas in the OAS document AND Codegen validates that oneOf and anyOf schemas contain the required discriminator and throws an error if the discriminator is missing.
      |true| |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| |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| diff --git a/docs/generators/typescript-node.md b/docs/generators/typescript-node.md index d4bdee29bcc8..ff7916f91309 100644 --- a/docs/generators/typescript-node.md +++ b/docs/generators/typescript-node.md @@ -9,6 +9,7 @@ sidebar_label: typescript-node |ensureUniqueParams|Whether to ensure parameter names are unique in an operation (rename parameters that are not).| |true| |enumNameSuffix|Suffix that will be appended to all enum names. A special 'v4-compat' value enables the backward-compatible behavior (as pre v4.2.3)| |v4-compat| |enumPropertyNaming|Naming convention for enum properties: 'camelCase', 'PascalCase', 'snake_case', 'UPPERCASE', and 'original'| |PascalCase| +|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}}.|
      **true**
      The mapping in the discriminator includes descendent schemas that allOf inherit from self and the discriminator mapping schemas in the OAS document.
      **false**
      The mapping in the discriminator includes any descendent schemas that allOf inherit from self, any oneOf schemas, any anyOf schemas, any x-discriminator-values, and the discriminator mapping schemas in the OAS document AND Codegen validates that oneOf and anyOf schemas contain the required discriminator and throws an error if the discriminator is missing.
      |true| |modelPropertyNaming|Naming convention for the property: 'camelCase', 'PascalCase', 'snake_case' and 'original', which keeps the original name| |camelCase| |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| diff --git a/docs/generators/typescript-redux-query.md b/docs/generators/typescript-redux-query.md index e5674a4c302c..0b1eef9f73a4 100644 --- a/docs/generators/typescript-redux-query.md +++ b/docs/generators/typescript-redux-query.md @@ -9,6 +9,7 @@ sidebar_label: typescript-redux-query |ensureUniqueParams|Whether to ensure parameter names are unique in an operation (rename parameters that are not).| |true| |enumNameSuffix|Suffix that will be appended to all enum names. A special 'v4-compat' value enables the backward-compatible behavior (as pre v4.2.3)| |v4-compat| |enumPropertyNaming|Naming convention for enum properties: 'camelCase', 'PascalCase', 'snake_case', 'UPPERCASE', and 'original'| |PascalCase| +|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}}.|
      **true**
      The mapping in the discriminator includes descendent schemas that allOf inherit from self and the discriminator mapping schemas in the OAS document.
      **false**
      The mapping in the discriminator includes any descendent schemas that allOf inherit from self, any oneOf schemas, any anyOf schemas, any x-discriminator-values, and the discriminator mapping schemas in the OAS document AND Codegen validates that oneOf and anyOf schemas contain the required discriminator and throws an error if the discriminator is missing.
      |true| |modelPropertyNaming|Naming convention for the property: 'camelCase', 'PascalCase', 'snake_case' and 'original', which keeps the original name| |camelCase| |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| diff --git a/docs/generators/typescript-rxjs.md b/docs/generators/typescript-rxjs.md index 9a210f4934b9..422b1fda35ff 100644 --- a/docs/generators/typescript-rxjs.md +++ b/docs/generators/typescript-rxjs.md @@ -9,6 +9,7 @@ sidebar_label: typescript-rxjs |ensureUniqueParams|Whether to ensure parameter names are unique in an operation (rename parameters that are not).| |true| |enumNameSuffix|Suffix that will be appended to all enum names. A special 'v4-compat' value enables the backward-compatible behavior (as pre v4.2.3)| |v4-compat| |enumPropertyNaming|Naming convention for enum properties: 'camelCase', 'PascalCase', 'snake_case', 'UPPERCASE', and 'original'| |PascalCase| +|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}}.|
      **true**
      The mapping in the discriminator includes descendent schemas that allOf inherit from self and the discriminator mapping schemas in the OAS document.
      **false**
      The mapping in the discriminator includes any descendent schemas that allOf inherit from self, any oneOf schemas, any anyOf schemas, any x-discriminator-values, and the discriminator mapping schemas in the OAS document AND Codegen validates that oneOf and anyOf schemas contain the required discriminator and throws an error if the discriminator is missing.
      |true| |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| |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| diff --git a/docs/usage.md b/docs/usage.md index 1f7d4ae52c1b..0d99e25b14d6 100644 --- a/docs/usage.md +++ b/docs/usage.md @@ -25,6 +25,22 @@ The most commonly used openapi-generator-cli commands are: See 'openapi-generator-cli help ' for more information on a specific command. +``` + +## version + +The version command provides version information, returning either the semver version by default or the git sha when passed `--sha`. + +```bash +NAME + openapi-generator-cli version - Show version information + +SYNOPSIS + openapi-generator-cli version [--sha] + +OPTIONS + --sha + Git commit SHA version ``` diff --git a/modules/openapi-generator-cli/src/main/java/org/openapitools/codegen/Constants.java b/modules/openapi-generator-cli/src/main/java/org/openapitools/codegen/Constants.java new file mode 100644 index 000000000000..863f1783828a --- /dev/null +++ b/modules/openapi-generator-cli/src/main/java/org/openapitools/codegen/Constants.java @@ -0,0 +1,9 @@ +package org.openapitools.codegen; + +public class Constants { + private Constants(){ } + + public static final String CLI_NAME = "openapi-generator-cli"; + public static final String GIT_REPO = "https://github.com/openapitools/openapi-generator"; + public static final String SITE = "https://openapi-generator.tech/"; +} diff --git a/modules/openapi-generator-cli/src/main/java/org/openapitools/codegen/OpenAPIGenerator.java b/modules/openapi-generator-cli/src/main/java/org/openapitools/codegen/OpenAPIGenerator.java index 8770c48a3549..f0e42adb4a9f 100644 --- a/modules/openapi-generator-cli/src/main/java/org/openapitools/codegen/OpenAPIGenerator.java +++ b/modules/openapi-generator-cli/src/main/java/org/openapitools/codegen/OpenAPIGenerator.java @@ -18,7 +18,6 @@ package org.openapitools.codegen; import io.airlift.airline.Cli; -import io.airlift.airline.Help; import io.airlift.airline.ParseArgumentsUnexpectedException; import io.airlift.airline.ParseOptionMissingException; import io.airlift.airline.ParseOptionMissingValueException; @@ -26,30 +25,31 @@ import java.util.Locale; +import static org.openapitools.codegen.Constants.CLI_NAME; + /** * User: lanwen Date: 24.03.15 Time: 17:56 *

      * Command line interface for OpenAPI Generator use `openapi-generator-cli.jar help` for more info - * - * @since 2.1.3-M1 */ public class OpenAPIGenerator { public static void main(String[] args) { - String version = Version.readVersionFromResources(); - Cli.CliBuilder builder = - Cli.builder("openapi-generator-cli") + BuildInfo buildInfo = new BuildInfo(); + Cli.CliBuilder builder = + Cli.builder(CLI_NAME) .withDescription( String.format( Locale.ROOT, - "OpenAPI generator CLI (version %s).", - version)) - .withDefaultCommand(ListGenerators.class) + "OpenAPI Generator CLI %s (%s).", + buildInfo.getVersion(), + buildInfo.getSha())) + .withDefaultCommand(HelpCommand.class) .withCommands( ListGenerators.class, Generate.class, Meta.class, - Help.class, + HelpCommand.class, ConfigHelp.class, Validate.class, Version.class, @@ -60,7 +60,7 @@ public static void main(String[] args) { try { builder.build().parse(args).run(); - // If CLI is run without a command, consider this an error. This exists after initial parse/run + // If CLI runs without a command, consider this an error. This exists after initial parse/run // so we can present the configured "default command". // We can check against empty args because unrecognized arguments/commands result in an exception. // This is useful to exit with status 1, for example, so that misconfigured scripts fail fast. @@ -71,10 +71,10 @@ public static void main(String[] args) { System.exit(1); } } catch (ParseArgumentsUnexpectedException e) { - System.err.printf(Locale.ROOT,"[error] %s%n%nSee 'openapi-generator help' for usage.%n", e.getMessage()); + System.err.printf(Locale.ROOT, "[error] %s%n%nSee '%s help' for usage.%n", e.getMessage(), CLI_NAME); System.exit(1); } catch (ParseOptionMissingException | ParseOptionMissingValueException e) { - System.err.printf(Locale.ROOT,"[error] %s%n", e.getMessage()); + System.err.printf(Locale.ROOT, "[error] %s%n", e.getMessage()); System.exit(1); } } diff --git a/modules/openapi-generator-cli/src/main/java/org/openapitools/codegen/cmd/BuildInfo.java b/modules/openapi-generator-cli/src/main/java/org/openapitools/codegen/cmd/BuildInfo.java new file mode 100644 index 000000000000..7d7c72b7f2f9 --- /dev/null +++ b/modules/openapi-generator-cli/src/main/java/org/openapitools/codegen/cmd/BuildInfo.java @@ -0,0 +1,101 @@ +package org.openapitools.codegen.cmd; + +import java.io.IOException; +import java.io.InputStream; +import java.time.DateTimeException; +import java.time.OffsetDateTime; +import java.time.format.DateTimeFormatter; +import java.time.format.DateTimeParseException; +import java.util.Locale; +import java.util.Properties; + +import static org.openapitools.codegen.Constants.*; + +/** + * Presents build-time information + */ +@SuppressWarnings({"java:S108"}) +public class BuildInfo { + private static final String VERSION_PLACEHOLDER = "${project.version}"; + private static final String UNSET = "unset"; + private static final String UNKNOWN = "unknown"; + + private static final Properties properties = new Properties(); + + static { + try (InputStream is = BuildInfo.class.getResourceAsStream("/version.properties")) { + if (is != null) { + Properties versionProps = new Properties(); + versionProps.load(is); + properties.putAll(versionProps); + } + } catch (IOException ignored) { + } + try (InputStream is = BuildInfo.class.getResourceAsStream("/openapi-generator-git.properties")) { + if (is != null) { + Properties gitProps = new Properties(); + gitProps.load(is); + properties.putAll(gitProps); + } + } catch (IOException ignored) { + } + } + + /** + * Gets the version of the toolset. + * + * @return A semver string + */ + public String getVersion() { + String version = (String) properties.getOrDefault("version", UNKNOWN); + if (VERSION_PLACEHOLDER.equals(version)) { + return UNSET; + } else { + return version; + } + } + + /** + * Gets the git commit SHA1 hash. Useful for differentiating between SNAPSHOT builds. + * + * @return A short git SHA + */ + public String getSha() { + return (String) properties.getOrDefault("git.commit.id.abbrev", UNKNOWN); + } + + /** + * Gets the time when this tool was built. + * + * @return The time as {@link OffsetDateTime}, or {@link OffsetDateTime#MIN} if metadata cannot be parsed. + */ + public OffsetDateTime getBuildTime() { + try { + String time = (String) properties.getOrDefault("git.build.time", ""); + return OffsetDateTime.parse(time, DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ssZ", Locale.ROOT)); + } catch (DateTimeParseException e) { + return OffsetDateTime.MIN; + } + } + + /** + * Gets the full version display text, as one would expect from a '--version' CLI option + * + * @return Human-readable version display information + */ + public String versionDisplayText() { + StringBuilder sb = new StringBuilder(CLI_NAME); + sb.append(" ").append(this.getVersion()).append(System.lineSeparator()); + sb.append(" commit : ").append(this.getSha()).append(System.lineSeparator()); + sb.append(" built : "); + try { + sb.append(this.getBuildTime().format(DateTimeFormatter.ISO_OFFSET_DATE_TIME)); + } catch (DateTimeException e) { + sb.append(UNKNOWN); + } + sb.append(System.lineSeparator()); + sb.append(" source : ").append(GIT_REPO).append(System.lineSeparator()); + sb.append(" docs : ").append(SITE).append(System.lineSeparator()); + return sb.toString(); + } +} diff --git a/modules/openapi-generator-cli/src/main/java/org/openapitools/codegen/cmd/CompletionCommand.java b/modules/openapi-generator-cli/src/main/java/org/openapitools/codegen/cmd/CompletionCommand.java index 369137fa9f17..bd67596fa9bf 100644 --- a/modules/openapi-generator-cli/src/main/java/org/openapitools/codegen/cmd/CompletionCommand.java +++ b/modules/openapi-generator-cli/src/main/java/org/openapitools/codegen/cmd/CompletionCommand.java @@ -36,8 +36,9 @@ import static com.google.common.collect.Lists.newArrayList; import static io.airlift.airline.ParserUtil.createInstance; +@SuppressWarnings({"java:S106"}) @Command(name = "completion", description = "Complete commands (for using in tooling such as Bash Completions).", hidden = true) -public class CompletionCommand +public class CompletionCommand extends OpenApiGeneratorCommand implements Runnable, Callable { private static final Map> BUILTIN_SUGGESTERS = ImmutableMap.>builder() .put(Context.GLOBAL, GlobalSuggester.class) @@ -95,7 +96,7 @@ public Iterable generateSuggestions() { } @Override - public void run() { + void execute() { System.out.println(Joiner.on("\n").join(generateSuggestions())); } } \ No newline at end of file diff --git a/modules/openapi-generator-cli/src/main/java/org/openapitools/codegen/cmd/ConfigHelp.java b/modules/openapi-generator-cli/src/main/java/org/openapitools/codegen/cmd/ConfigHelp.java index 6c6f50b544e1..20a18901099d 100644 --- a/modules/openapi-generator-cli/src/main/java/org/openapitools/codegen/cmd/ConfigHelp.java +++ b/modules/openapi-generator-cli/src/main/java/org/openapitools/codegen/cmd/ConfigHelp.java @@ -39,9 +39,9 @@ import static org.apache.commons.lang3.StringEscapeUtils.escapeHtml4; import static org.apache.commons.lang3.StringUtils.isEmpty; -@SuppressWarnings("unused") +@SuppressWarnings({"unused","java:S106"}) @Command(name = "config-help", description = "Config help for chosen lang") -public class ConfigHelp implements Runnable { +public class ConfigHelp extends OpenApiGeneratorCommand { private static final Logger LOGGER = LoggerFactory.getLogger(Generate.class); @@ -91,7 +91,7 @@ public class ConfigHelp implements Runnable { private String newline = System.lineSeparator(); @Override - public void run() { + public void execute() { if (isEmpty(generatorName)) { LOGGER.error("[error] A generator name (--generator-name / -g) is required."); System.exit(1); @@ -320,6 +320,7 @@ private void generateYamlSample(StringBuilder sb, CodegenConfig config) { } } + @SuppressWarnings({"java:S1117"}) private void generatePlainTextHelp(StringBuilder sb, CodegenConfig config) { sb.append(newline).append("CONFIG OPTIONS"); if (Boolean.TRUE.equals(namedHeader)) { @@ -418,6 +419,7 @@ private void generatePlainTextHelp(StringBuilder sb, CodegenConfig config) { } } + @SuppressWarnings({"java:S1117"}) private void writePlainTextFromMap( StringBuilder sb, Map map, @@ -449,6 +451,7 @@ private void writePlainTextFromMap( } } + @SuppressWarnings({"java:S1117"}) private void writePlainTextFromArray(StringBuilder sb, String[] arr, String optIndent) { if (arr.length > 0) { // target a width of 20, then take the max up to 40. diff --git a/modules/openapi-generator-cli/src/main/java/org/openapitools/codegen/cmd/Generate.java b/modules/openapi-generator-cli/src/main/java/org/openapitools/codegen/cmd/Generate.java index 976aa7892fb7..084026f5552e 100644 --- a/modules/openapi-generator-cli/src/main/java/org/openapitools/codegen/cmd/Generate.java +++ b/modules/openapi-generator-cli/src/main/java/org/openapitools/codegen/cmd/Generate.java @@ -34,8 +34,9 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; +@SuppressWarnings({"java:S106"}) @Command(name = "generate", description = "Generate code with the specified generator.") -public class Generate implements Runnable { +public class Generate extends OpenApiGeneratorCommand { CodegenConfigurator configurator; Generator generator; @@ -70,12 +71,13 @@ public class Generate implements Runnable { + "Pass in a URL-encoded string of name:header with a comma separating multiple values") private String auth; + // TODO: Remove -D short option in 5.0 @Option( - name = {"-D"}, - title = "system properties", - description = "sets specified system properties in " + name = {"-D", "--global-property"}, + title = "global properties", + description = "sets specified global properties (previously called 'system properties') in " + "the format of name=value,name=value (or multiple options, each with name=value)") - private List systemProperties = new ArrayList<>(); + private List globalProperties = new ArrayList<>(); @Option( name = {"-c", "--config"}, @@ -238,13 +240,16 @@ public class Generate implements Runnable { @Option(name = {"--generate-alias-as-model"}, title = "generate alias (array, map) as model", description = CodegenConstants.GENERATE_ALIAS_AS_MODEL_DESC) private Boolean generateAliasAsModel; + @Option(name = {"--legacy-discriminator-behavior"}, title = "Support legacy logic for evaluating discriminators", description = CodegenConstants.LEGACY_DISCRIMINATOR_BEHAVIOR_DESC) + private Boolean legacyDiscriminatorBehavior; + @Option(name = {"--minimal-update"}, title = "Minimal update", description = "Only write output files that have changed.") private Boolean minimalUpdate; @Override - public void run() { + public void execute() { if (logToStderr != null) { LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory(); Stream.of(Logger.ROOT_LOGGER_NAME, "io.swagger", "org.openapitools") @@ -402,9 +407,9 @@ public void run() { configurator.setStrictSpecBehavior(strictSpecBehavior); } - if (systemProperties != null && !systemProperties.isEmpty()) { - System.err.println("[DEPRECATED] -D arguments after 'generate' are application arguments and not Java System Properties, please consider changing to -p, or apply your options to JAVA_OPTS, or move the -D arguments before the jar option."); - applySystemPropertiesKvpList(systemProperties, configurator); + if (globalProperties != null && !globalProperties.isEmpty()) { + System.err.println("[DEPRECATED] -D arguments after 'generate' are application arguments and not Java System Properties, please consider changing to --global-property, apply your system properties to JAVA_OPTS, or move the -D arguments before the jar option."); + applyGlobalPropertiesKvpList(globalProperties, configurator); } applyInstantiationTypesKvpList(instantiationTypes, configurator); applyImportMappingsKvpList(importMappings, configurator); diff --git a/modules/openapi-generator-cli/src/main/java/org/openapitools/codegen/cmd/GenerateBatch.java b/modules/openapi-generator-cli/src/main/java/org/openapitools/codegen/cmd/GenerateBatch.java index fde5f6ea4a33..90bdec1f3f02 100644 --- a/modules/openapi-generator-cli/src/main/java/org/openapitools/codegen/cmd/GenerateBatch.java +++ b/modules/openapi-generator-cli/src/main/java/org/openapitools/codegen/cmd/GenerateBatch.java @@ -50,9 +50,9 @@ import java.util.stream.Collectors; import java.util.stream.Stream; -@SuppressWarnings({"unused", "MismatchedQueryAndUpdateOfCollection"}) +@SuppressWarnings({"unused", "MismatchedQueryAndUpdateOfCollection", "java:S106"}) @Command(name = "batch", description = "Generate code in batch via external configs.", hidden = true) -public class GenerateBatch implements Runnable { +public class GenerateBatch extends OpenApiGeneratorCommand { private static final Logger LOGGER = LoggerFactory.getLogger(GenerateBatch.class); @@ -89,7 +89,7 @@ public class GenerateBatch implements Runnable { * @see Thread#run() */ @Override - public void run() { + public void execute() { if (configs.size() < 1) { LOGGER.error("No configuration file inputs specified"); System.exit(1); diff --git a/modules/openapi-generator-cli/src/main/java/org/openapitools/codegen/cmd/GlobalOptions.java b/modules/openapi-generator-cli/src/main/java/org/openapitools/codegen/cmd/GlobalOptions.java new file mode 100644 index 000000000000..3333d30b08eb --- /dev/null +++ b/modules/openapi-generator-cli/src/main/java/org/openapitools/codegen/cmd/GlobalOptions.java @@ -0,0 +1,13 @@ +package org.openapitools.codegen.cmd; + +import io.airlift.airline.Option; + +import static io.airlift.airline.OptionType.GLOBAL; + +public class GlobalOptions { + @Option(type = GLOBAL, name = "--version", description = "Display full version output", hidden = true) + public boolean version; + + @Option(type = GLOBAL, name = "--help", description = "Display help about the tool", hidden = true) + public boolean help; +} diff --git a/modules/openapi-generator-cli/src/main/java/org/openapitools/codegen/cmd/HelpCommand.java b/modules/openapi-generator-cli/src/main/java/org/openapitools/codegen/cmd/HelpCommand.java new file mode 100644 index 000000000000..aab582beb3af --- /dev/null +++ b/modules/openapi-generator-cli/src/main/java/org/openapitools/codegen/cmd/HelpCommand.java @@ -0,0 +1,18 @@ +package org.openapitools.codegen.cmd; + +import io.airlift.airline.Command; +import io.airlift.airline.Help; + +import javax.inject.Inject; + +@Command(name = "help", description = "Display help information about openapi-generator") +public class HelpCommand extends OpenApiGeneratorCommand { + + @Inject + public Help help; + + @Override + public void execute() { + help.call(); + } +} diff --git a/modules/openapi-generator-cli/src/main/java/org/openapitools/codegen/cmd/ListGenerators.java b/modules/openapi-generator-cli/src/main/java/org/openapitools/codegen/cmd/ListGenerators.java index 3cab8cf65631..8a1781932400 100644 --- a/modules/openapi-generator-cli/src/main/java/org/openapitools/codegen/cmd/ListGenerators.java +++ b/modules/openapi-generator-cli/src/main/java/org/openapitools/codegen/cmd/ListGenerators.java @@ -16,8 +16,9 @@ import java.util.stream.Collectors; // NOTE: List can later have subcommands such as list languages, list types, list frameworks, etc. +@SuppressWarnings({"java:S106"}) @Command(name = "list", description = "Lists the available generators") -public class ListGenerators implements Runnable { +public class ListGenerators extends OpenApiGeneratorCommand { @Option(name = {"-s", "--short" }, description = "shortened output (suitable for scripting)") private Boolean shortened = false; @@ -34,7 +35,7 @@ public class ListGenerators implements Runnable { private String include = "stable,beta,experimental"; @Override - public void run() { + public void execute() { List generators = new ArrayList<>(); List stabilities = Arrays.asList(Stability.values()); diff --git a/modules/openapi-generator-cli/src/main/java/org/openapitools/codegen/cmd/Meta.java b/modules/openapi-generator-cli/src/main/java/org/openapitools/codegen/cmd/Meta.java index 2326dcadf2d3..9fa400098fb1 100644 --- a/modules/openapi-generator-cli/src/main/java/org/openapitools/codegen/cmd/Meta.java +++ b/modules/openapi-generator-cli/src/main/java/org/openapitools/codegen/cmd/Meta.java @@ -49,7 +49,7 @@ @Command(name = "meta", description = "MetaGenerator. Generator for creating a new template set " + "and configuration for Codegen. The output will be based on the language you " + "specify, and includes default templates to include.") -public class Meta implements Runnable { +public class Meta extends OpenApiGeneratorCommand { private static final Logger LOGGER = LoggerFactory.getLogger(Meta.class); @@ -80,7 +80,7 @@ public class Meta implements Runnable { private String language = "java"; @Override - public void run() { + public void execute() { final File targetDir = new File(outputFolder); LOGGER.info("writing to folder [{}]", targetDir.getAbsolutePath()); @@ -110,7 +110,7 @@ public void run() { new SupportingFile("myFile.template", String.join(File.separator, "src", "main", "resources", name), "myFile.mustache"), new SupportingFile("services.mustache", "src/main/resources/META-INF/services", CodegenConfig.class.getCanonicalName())); - String currentVersion = Version.readVersionFromResources(); + String currentVersion = buildInfo.getVersion(); Map data = new ImmutableMap.Builder() diff --git a/modules/openapi-generator-cli/src/main/java/org/openapitools/codegen/cmd/OpenApiGeneratorCommand.java b/modules/openapi-generator-cli/src/main/java/org/openapitools/codegen/cmd/OpenApiGeneratorCommand.java new file mode 100644 index 000000000000..47ee715d3dce --- /dev/null +++ b/modules/openapi-generator-cli/src/main/java/org/openapitools/codegen/cmd/OpenApiGeneratorCommand.java @@ -0,0 +1,39 @@ +package org.openapitools.codegen.cmd; + +import io.airlift.airline.Help; +import io.airlift.airline.model.GlobalMetadata; + +import javax.inject.Inject; + +@SuppressWarnings({"java:S106"}) +public abstract class OpenApiGeneratorCommand implements Runnable { + @Inject + public GlobalOptions globalOptions = new GlobalOptions(); + + @Inject + public GlobalMetadata global; + + protected BuildInfo buildInfo = new BuildInfo(); + + @Override + public void run() { + if (globalOptions.version) { + System.out.println(buildInfo.versionDisplayText()); + return; + } + + if (globalOptions.help) { + Help help = new Help(); + help.global = global; + help.call(); + return; + } + + execute(); + } + + /** + * Logic to be executed by implementing commands + */ + abstract void execute(); +} diff --git a/modules/openapi-generator-cli/src/main/java/org/openapitools/codegen/cmd/Validate.java b/modules/openapi-generator-cli/src/main/java/org/openapitools/codegen/cmd/Validate.java index 2d95cbf5dc06..d0517d94415c 100644 --- a/modules/openapi-generator-cli/src/main/java/org/openapitools/codegen/cmd/Validate.java +++ b/modules/openapi-generator-cli/src/main/java/org/openapitools/codegen/cmd/Validate.java @@ -33,8 +33,9 @@ import java.util.List; import java.util.Set; +@SuppressWarnings({"unused","java:S106"}) @Command(name = "validate", description = "Validate specification") -public class Validate implements Runnable { +public class Validate extends OpenApiGeneratorCommand { @Option(name = {"-i", "--input-spec"}, title = "spec file", required = true, description = "location of the OpenAPI spec, as URL or file (required)") @@ -44,7 +45,7 @@ public class Validate implements Runnable { private Boolean recommend; @Override - public void run() { + public void execute() { System.out.println("Validating spec (" + spec + ")"); ParseOptions options = new ParseOptions(); options.setResolve(true); @@ -57,7 +58,9 @@ public void run() { OpenAPI specification = result.getOpenAPI(); RuleConfiguration ruleConfiguration = new RuleConfiguration(); - ruleConfiguration.setEnableRecommendations(recommend != null ? recommend : false); + + if (recommend != null) ruleConfiguration.setEnableRecommendations(recommend); + else ruleConfiguration.setEnableRecommendations(false); OpenApiEvaluator evaluator = new OpenApiEvaluator(ruleConfiguration); ValidationResult validationResult = evaluator.validate(specification); diff --git a/modules/openapi-generator-cli/src/main/java/org/openapitools/codegen/cmd/Version.java b/modules/openapi-generator-cli/src/main/java/org/openapitools/codegen/cmd/Version.java index 93e2b378a799..3c47fc2cbc65 100644 --- a/modules/openapi-generator-cli/src/main/java/org/openapitools/codegen/cmd/Version.java +++ b/modules/openapi-generator-cli/src/main/java/org/openapitools/codegen/cmd/Version.java @@ -17,45 +17,30 @@ package org.openapitools.codegen.cmd; -import java.io.IOException; -import java.io.InputStream; -import java.util.Properties; - import io.airlift.airline.Command; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -@Command(name = "version", description = "Show version information") -public class Version implements Runnable { +import io.airlift.airline.Option; - private static final Logger LOGGER = LoggerFactory.getLogger(Meta.class); +@SuppressWarnings({"unused", "java:S106"}) +@Command(name = "version", description = "Show version information used in tooling") +public class Version extends OpenApiGeneratorCommand { - private static final String VERSION_PLACEHOLDER = "${project.version}"; + @Option(name = {"--sha"}, description = "Git commit SHA version") + private Boolean sha; - private static final String UNREADABLE_VERSION = "unreadable"; - private static final String UNSET_VERSION = "unset"; - private static final String UNKNOWN_VERSION = "unknown"; + @Option(name = {"--full"}, description = "Full version details") + private Boolean full; - public static String readVersionFromResources() { - Properties versionProperties = new Properties(); - try (InputStream is = Version.class.getResourceAsStream("/version.properties")) { - versionProperties.load(is); - } catch (IOException ex) { - LOGGER.error("Error loading version properties", ex); - return UNREADABLE_VERSION; - } + @Override + public void execute() { + String version; - String version = versionProperties.getProperty("version", UNKNOWN_VERSION).trim(); - if (VERSION_PLACEHOLDER.equals(version)) { - return UNSET_VERSION; + if (Boolean.TRUE.equals(full)) { + version = buildInfo.versionDisplayText(); + } else if (Boolean.TRUE.equals(sha)) { + version = buildInfo.getSha(); } else { - return version; + version = buildInfo.getVersion(); } - } - - @Override - public void run() { - String version = readVersionFromResources(); System.out.println(version); } diff --git a/modules/openapi-generator-core/src/main/java/org/openapitools/codegen/config/WorkflowSettings.java b/modules/openapi-generator-core/src/main/java/org/openapitools/codegen/config/WorkflowSettings.java index 0fdc6c6e99c3..2a0c9ac572af 100644 --- a/modules/openapi-generator-core/src/main/java/org/openapitools/codegen/config/WorkflowSettings.java +++ b/modules/openapi-generator-core/src/main/java/org/openapitools/codegen/config/WorkflowSettings.java @@ -28,13 +28,14 @@ import java.util.HashMap; import java.util.Map; import java.util.Objects; +import java.util.concurrent.atomic.AtomicLong; /** * Represents those settings applied to a generation workflow. */ @SuppressWarnings("WeakerAccess") public class WorkflowSettings { - + private static final AtomicLong lastWarning = new AtomicLong(0); private static final Logger LOGGER = LoggerFactory.getLogger(WorkflowSettings.class); public static final String DEFAULT_OUTPUT_DIR = "."; public static final boolean DEFAULT_VERBOSE = false; @@ -77,7 +78,15 @@ private WorkflowSettings(Builder builder) { this.templateDir = builder.templateDir; this.templatingEngineName = builder.templatingEngineName; this.ignoreFileOverride = builder.ignoreFileOverride; + // TODO: rename to globalProperties for 5.0 this.systemProperties = ImmutableMap.copyOf(builder.systemProperties); + if (this.systemProperties.size() > 0) { + // write no more than every 5s. This is temporary until version 5.0 as once(Logger) is not accessible here. + // thread contention may cause this to write more than once, but this is just an attempt to reduce noise + if (System.currentTimeMillis() - lastWarning.getAndUpdate(x -> System.currentTimeMillis()) > 5000) { + LOGGER.warn("systemProperties will be renamed to globalProperties in version 5.0"); + } + } } /** diff --git a/modules/openapi-generator-gradle-plugin/src/main/kotlin/org/openapitools/generator/gradle/plugin/tasks/GenerateTask.kt b/modules/openapi-generator-gradle-plugin/src/main/kotlin/org/openapitools/generator/gradle/plugin/tasks/GenerateTask.kt index e0dee13cafe4..d0c207711a11 100644 --- a/modules/openapi-generator-gradle-plugin/src/main/kotlin/org/openapitools/generator/gradle/plugin/tasks/GenerateTask.kt +++ b/modules/openapi-generator-gradle-plugin/src/main/kotlin/org/openapitools/generator/gradle/plugin/tasks/GenerateTask.kt @@ -21,6 +21,7 @@ import org.gradle.api.GradleException import org.gradle.api.provider.Property import org.gradle.api.tasks.Internal import org.gradle.api.tasks.TaskAction +import org.gradle.api.tasks.options.Option import org.gradle.internal.logging.text.StyledTextOutput import org.gradle.internal.logging.text.StyledTextOutputFactory import org.gradle.kotlin.dsl.listProperty @@ -37,7 +38,7 @@ import org.openapitools.codegen.config.GlobalSettings * * Example (CLI): * - * ./gradlew -q openApiGenerate + * ./gradlew -q openApiGenerate --input=/path/to/file * * @author Jim Schubert */ @@ -68,6 +69,14 @@ open class GenerateTask : DefaultTask() { @get:Internal val outputDir = project.objects.property() + @Suppress("unused") + @get:Internal + @set:Option(option = "input", description = "The input specification.") + var input: String? = null + set(value) { + inputSpec.set(value) + } + /** * The Open API 2.0/3.x specification location. */ @@ -574,6 +583,7 @@ open class GenerateTask : DefaultTask() { } if (systemProperties.isPresent) { + // TODO: rename to globalProperties in 5.0 systemProperties.get().forEach { entry -> configurator.addSystemProperty(entry.key, entry.value) } @@ -639,7 +649,7 @@ open class GenerateTask : DefaultTask() { DefaultGenerator().opts(clientOptInput).generate() - out.println("Successfully generated code to $outputDir") + out.println("Successfully generated code to ${outputDir.get()}") } catch (e: RuntimeException) { throw GradleException("Code generation failed.", e) } diff --git a/modules/openapi-generator-maven-plugin/examples/spring.xml b/modules/openapi-generator-maven-plugin/examples/spring.xml index dda872981b90..a0654ffe260d 100644 --- a/modules/openapi-generator-maven-plugin/examples/spring.xml +++ b/modules/openapi-generator-maven-plugin/examples/spring.xml @@ -20,7 +20,7 @@ org.openapitools openapi-generator-maven-plugin - 4.2.2-SNAPSHOT + 4.3.1-SNAPSHOT diff --git a/modules/openapi-generator-maven-plugin/src/main/java/org/openapitools/codegen/plugin/CodeGenMojo.java b/modules/openapi-generator-maven-plugin/src/main/java/org/openapitools/codegen/plugin/CodeGenMojo.java index 8e17356e4601..0d33707e32d6 100644 --- a/modules/openapi-generator-maven-plugin/src/main/java/org/openapitools/codegen/plugin/CodeGenMojo.java +++ b/modules/openapi-generator-maven-plugin/src/main/java/org/openapitools/codegen/plugin/CodeGenMojo.java @@ -70,7 +70,7 @@ * Goal which generates client/server code from a OpenAPI json/yaml definition. */ @SuppressWarnings({"unused", "MismatchedQueryAndUpdateOfCollection"}) -@Mojo(name = "generate", defaultPhase = LifecyclePhase.GENERATE_SOURCES) +@Mojo(name = "generate", defaultPhase = LifecyclePhase.GENERATE_SOURCES, threadSafe = true) public class CodeGenMojo extends AbstractMojo { private static final Logger LOGGER = LoggerFactory.getLogger(CodeGenMojo.class); @@ -408,6 +408,7 @@ public class CodeGenMojo extends AbstractMojo { @Parameter(defaultValue = "true", property = "openapi.generator.maven.plugin.addCompileSourceRoot") private boolean addCompileSourceRoot = true; + // TODO: Rename to global properties in version 5.0 @Parameter protected Map environmentVariables = new HashMap<>(); diff --git a/modules/openapi-generator/pom.xml b/modules/openapi-generator/pom.xml index c002609cd557..a6a57e4426e2 100644 --- a/modules/openapi-generator/pom.xml +++ b/modules/openapi-generator/pom.xml @@ -43,6 +43,32 @@ target ${project.artifactId}-${project.version} + + pl.project13.maven + git-commit-id-plugin + + + get-the-git-infos + + revision + + initialize + + + + true + ${project.build.outputDirectory}/openapi-generator-git.properties + + + ^git.build.(time|version)$ + ^git.commit.id.(abbrev|full)$ + + full + ${project.parent.basedir}${file.separator}.git + false + false + + org.apache.maven.plugins maven-checkstyle-plugin diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/CodegenConstants.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/CodegenConstants.java index 14e1fe5fce33..63ba78364309 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/CodegenConstants.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/CodegenConstants.java @@ -351,4 +351,9 @@ public static enum ENUM_PROPERTY_NAMING_TYPE {camelCase, PascalCase, snake_case, public static final String REMOVE_ENUM_VALUE_PREFIX = "removeEnumValuePrefix"; public static final String REMOVE_ENUM_VALUE_PREFIX_DESC = "Remove the common prefix of enum values"; + + public static final String LEGACY_DISCRIMINATOR_BEHAVIOR = "legacyDiscriminatorBehavior"; + public static final String LEGACY_DISCRIMINATOR_BEHAVIOR_DESC = "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}}."; + } diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/CodegenDiscriminator.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/CodegenDiscriminator.java index 73d85052e70d..4e30df0c9ea4 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/CodegenDiscriminator.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/CodegenDiscriminator.java @@ -7,12 +7,39 @@ import java.util.Objects; import java.util.Set; +/** + * This class encapsulates the OpenAPI discriminator construct, as specified at + * https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.3.md#discriminatorObject. + * + * When request bodies or response payloads may be one of a number of different schemas, + * a discriminator object can be used to aid in serialization, deserialization, and validation. + * The discriminator is a specific object in a schema which is used to inform the consumer of + * the specification of an alternative schema based on the value associated with it. + */ public class CodegenDiscriminator { + // The name of the property in the payload that will hold the discriminator value. + // This is the propertyName as specified in the OpenAPI discriminator object. private String propertyName; private String propertyBaseName; private String propertyGetter; private String propertyType; private Map mapping; + + // mappedModels is populated differently if discriminatorExplicitMappingVerbose is + // True or False. When: + // + // discriminatorExplicitMappingVerbose == False, this contains: + // - the name to schema map info in the discriminator mapping entry in your openapi spec OR + // - child schemas that allOf inherit self schema + // + // discriminatorExplicitMappingVerbose == True, this contains: + // - the name to schema map info in the discriminMappedModelator mapping entry in your openapi spec AND + // - x-discriminator-value mappings in child oneOf + anyOf schemas + descendant schemas that allOf inherit self schema AND + // - descendant schemas that allOf inherit self schema AND + // - child oneOf + anyOf schemas + // + // see the method createDiscriminator in DefaultCodegen.java + private Set mappedModels = new LinkedHashSet<>(); public String getPropertyName() { @@ -63,8 +90,21 @@ public void setMappedModels(Set mappedModels) { this.mappedModels = mappedModels; } - public static class MappedModel { + /** + * An object to hold discriminator mappings between payload values and schema names or + * references. + * + * In the OpenAPI document, the discriminator "mapping" attribute is optional. + * In scenarios where the value of the discriminator field does not match the schema name + * or implicit mapping is not possible, an optional mapping definition MAY be used. + * In OpenAPITools codegen, the MappedModel is the union of all the discriminator mappings, + * both explicitly defined in the OpenAPI document and inherited from oneOf/allOf/anyOf. + */ + public static class MappedModel implements Comparable{ + // The value of the discriminator property in the payload. private String mappingName; + // The OAS schema name. It is obtained from the OAS document, and the string value + // is converted to a sanitized, internal representation within codegen. private String modelName; public MappedModel(String mappingName, String modelName) { @@ -72,6 +112,18 @@ public MappedModel(String mappingName, String modelName) { this.modelName = modelName; } + @Override + public int compareTo(MappedModel other) { + if (getMappingName() == null && other.getMappingName() == null) { + return 0; + } else if (getMappingName() == null) { + return 1; + } else if (other.getMappingName() == null) { + return -1; + } + return getMappingName().compareTo(other.getMappingName()); + } + public String getMappingName() { return mappingName; } @@ -130,4 +182,4 @@ public String toString() { sb.append('}'); return sb.toString(); } -} +} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/CodegenModel.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/CodegenModel.java index 2caa4a3edee8..09980dde19b3 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/CodegenModel.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/CodegenModel.java @@ -46,6 +46,13 @@ public class CodegenModel implements IJsonSchemaValidationProperties { public Set oneOf = new TreeSet(); public Set allOf = new TreeSet(); + 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. + public String classname; + // The value of the 'title' attribute in the OpenAPI document. + public String title; + public String description, classVarName, modelJson, dataType, xmlPrefix, xmlNamespace, xmlName; public List> stubiExample; public List> getStubiExample() { @@ -56,7 +63,7 @@ public void setStubiExample(List> stubiExample) { this.stubiExample = stubiExample; } - public String name, classname, title, description, classVarName, modelJson, dataType, xmlPrefix, xmlNamespace, xmlName; +// public String name, classname, title, description, classVarName, modelJson, dataType, xmlPrefix, xmlNamespace, xmlName; public String classFilename; // store the class file name, mainly used for import public String unescapedDescription; public CodegenDiscriminator discriminator; @@ -78,7 +85,7 @@ public void setStubiExample(List> stubiExample) { public Set allMandatory = new TreeSet(); // with parent's required properties public Set imports = new TreeSet(); - public boolean hasVars, emptyVars, hasMoreModels, hasEnums, isEnum, isNullable, hasRequired, hasOptional, isArrayModel, hasChildren, isMapModel; + public boolean hasVars, emptyVars, hasMoreModels, hasEnums, isEnum, isNullable, hasRequired, hasOptional, isArrayModel, hasChildren, isMapModel, isDeprecated; public boolean hasOnlyReadOnly = true; // true if all properties are read-only public ExternalDocumentation externalDocumentation; @@ -547,6 +554,7 @@ public boolean equals(Object o) { isArrayModel == that.isArrayModel && hasChildren == that.hasChildren && isMapModel == that.isMapModel && + isDeprecated == that.isDeprecated && hasOnlyReadOnly == that.hasOnlyReadOnly && getUniqueItems() == that.getUniqueItems() && getExclusiveMinimum() == that.getExclusiveMinimum() && @@ -613,7 +621,7 @@ public int hashCode() { getVars(), getAllVars(), getRequiredVars(), getOptionalVars(), getReadOnlyVars(), getReadWriteVars(), getParentVars(), getAllowableValues(), getMandatory(), getAllMandatory(), getImports(), hasVars, isEmptyVars(), hasMoreModels, hasEnums, isEnum, isNullable, hasRequired, hasOptional, isArrayModel, - hasChildren, isMapModel, hasOnlyReadOnly, getExternalDocumentation(), getVendorExtensions(), + hasChildren, isMapModel, isDeprecated, hasOnlyReadOnly, getExternalDocumentation(), getVendorExtensions(), getAdditionalPropertiesType(), getMaxProperties(), getMinProperties(), getUniqueItems(), getMaxItems(), getMinItems(), getMaxLength(), getMinLength(), getExclusiveMinimum(), getExclusiveMaximum(), getMinimum(), getMaximum(), getPattern(), getMultipleOf()); @@ -677,6 +685,7 @@ public String toString() { sb.append(", isArrayModel=").append(isArrayModel); sb.append(", hasChildren=").append(hasChildren); sb.append(", isMapModel=").append(isMapModel); + sb.append(", isDeprecated=").append(isDeprecated); sb.append(", hasOnlyReadOnly=").append(hasOnlyReadOnly); sb.append(", externalDocumentation=").append(externalDocumentation); sb.append(", vendorExtensions=").append(vendorExtensions); @@ -698,6 +707,17 @@ public String toString() { return sb.toString(); } + public void addDiscriminatorMappedModelsImports(){ + if (discriminator == null || discriminator.getMappedModels() == null) { + return; + } + for (CodegenDiscriminator.MappedModel mm : discriminator.getMappedModels()) { + if (!"".equals(mm.getModelName())) { + imports.add(mm.getModelName()); + } + } + } + public boolean isEmptyVars() { return emptyVars; } diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/CodegenParameter.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/CodegenParameter.java index 7072df85be8a..fda66803235c 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/CodegenParameter.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/CodegenParameter.java @@ -34,7 +34,7 @@ public class CodegenParameter implements IJsonSchemaValidationProperties { public String example; // example value (x-example) public String jsonSchema; public boolean isString, isNumeric, isInteger, isLong, isNumber, isFloat, isDouble, isByteArray, isBinary, - isBoolean, isDate, isDateTime, isUuid, isUri, isEmail, isFreeFormObject; + isBoolean, isDate, isDateTime, isUuid, isUri, isEmail, isFreeFormObject, isAnyType; public boolean isListContainer, isMapContainer; public boolean isFile; public boolean isEnum; @@ -178,6 +178,7 @@ public CodegenParameter copy() { output.isUri = this.isUri; output.isEmail = this.isEmail; output.isFreeFormObject = this.isFreeFormObject; + output.isAnyType = this.isAnyType; output.isListContainer = this.isListContainer; output.isMapContainer = this.isMapContainer; output.isExplode = this.isExplode; @@ -188,7 +189,7 @@ public CodegenParameter copy() { @Override public int hashCode() { - return Objects.hash(isFormParam, isQueryParam, isPathParam, isHeaderParam, isCookieParam, isBodyParam, hasMore, isContainer, secondaryParam, isCollectionFormatMulti, isPrimitiveType, isModel, isExplode, baseName, paramName, dataType, datatypeWithEnum, dataFormat, collectionFormat, description, unescapedDescription, baseType, defaultValue, enumName, style, example, jsonSchema, isString, isNumeric, isInteger, isLong, isNumber, isFloat, isDouble, isByteArray, isBinary, isBoolean, isDate, isDateTime, isUuid, isUri, isEmail, isFreeFormObject, isListContainer, isMapContainer, isFile, isEnum, _enum, allowableValues, items, mostInnerItems, vendorExtensions, hasValidation, getMaxProperties(), getMinProperties(), isNullable, required, getMaximum(), getExclusiveMaximum(), getMinimum(), getExclusiveMinimum(), getMaxLength(), getMinLength(), getPattern(), getMaxItems(), getMinItems(), getUniqueItems(), multipleOf); + return Objects.hash(isFormParam, isQueryParam, isPathParam, isHeaderParam, isCookieParam, isBodyParam, hasMore, isContainer, secondaryParam, isCollectionFormatMulti, isPrimitiveType, isModel, isExplode, baseName, paramName, dataType, datatypeWithEnum, dataFormat, collectionFormat, description, unescapedDescription, baseType, defaultValue, enumName, style, example, jsonSchema, isString, isNumeric, isInteger, isLong, isNumber, isFloat, isDouble, isByteArray, isBinary, isBoolean, isDate, isDateTime, isUuid, isUri, isEmail, isFreeFormObject, isAnyType, isListContainer, isMapContainer, isFile, isEnum, _enum, allowableValues, items, mostInnerItems, vendorExtensions, hasValidation, getMaxProperties(), getMinProperties(), isNullable, required, getMaximum(), getExclusiveMaximum(), getMinimum(), getExclusiveMinimum(), getMaxLength(), getMinLength(), getPattern(), getMaxItems(), getMinItems(), getUniqueItems(), multipleOf); } @Override @@ -225,6 +226,7 @@ public boolean equals(Object o) { isUri == that.isUri && isEmail == that.isEmail && isFreeFormObject == that.isFreeFormObject && + isAnyType == that.isAnyType && isListContainer == that.isListContainer && isMapContainer == that.isMapContainer && isFile == that.isFile && @@ -312,6 +314,7 @@ public String toString() { sb.append(", isUri=").append(isUri); sb.append(", isEmail=").append(isEmail); sb.append(", isFreeFormObject=").append(isFreeFormObject); + sb.append(", isAnyType=").append(isAnyType); sb.append(", isListContainer=").append(isListContainer); sb.append(", isMapContainer=").append(isMapContainer); sb.append(", isFile=").append(isFile); diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/CodegenProperty.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/CodegenProperty.java index b6255e1fe02d..bc1101c015e9 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/CodegenProperty.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/CodegenProperty.java @@ -150,6 +150,7 @@ public class CodegenProperty implements Cloneable, IJsonSchemaValidationProperti public boolean isNullable; public boolean isSelfReference; public boolean isCircularReference; + public boolean isDiscriminator; public List _enum; public Map allowableValues; public CodegenProperty items; @@ -651,6 +652,7 @@ public String toString() { sb.append(", isNullable=").append(isNullable); sb.append(", isSelfReference=").append(isSelfReference); sb.append(", isCircularReference=").append(isCircularReference); + sb.append(", isDiscriminator=").append(isDiscriminator); sb.append(", _enum=").append(_enum); sb.append(", allowableValues=").append(allowableValues); sb.append(", items=").append(items); @@ -717,6 +719,7 @@ public boolean equals(Object o) { isNullable == that.isNullable && isSelfReference == that.isSelfReference && isCircularReference == that.isCircularReference && + isDiscriminator == that.isDiscriminator && hasValidation == that.hasValidation && isInherited == that.isInherited && isXmlAttribute == that.isXmlAttribute && @@ -775,7 +778,7 @@ public int hashCode() { isInteger, isLong, isNumber, isFloat, isDouble, isByteArray, isBinary, isFile, isBoolean, isDate, isDateTime, isUuid, isUri, isEmail, isFreeFormObject, isListContainer, isMapContainer, isEnum, isReadOnly, isWriteOnly, isNullable, - isSelfReference, isCircularReference, _enum, allowableValues, items, mostInnerItems, + isSelfReference, isCircularReference, isDiscriminator, _enum, allowableValues, items, mostInnerItems, vendorExtensions, hasValidation, isInherited, discriminatorValue, nameInCamelCase, nameInSnakeCase, enumName, maxItems, minItems, isXmlAttribute, xmlPrefix, xmlName, xmlNamespace, isXmlWrapped); diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/CodegenResponse.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/CodegenResponse.java index 29429c073b7e..9e9d28958af3 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/CodegenResponse.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/CodegenResponse.java @@ -22,6 +22,11 @@ public class CodegenResponse implements IJsonSchemaValidationProperties { public final List headers = new ArrayList(); public String code; + public boolean is1xx; + public boolean is2xx; + public boolean is3xx; + public boolean is4xx; + public boolean is5xx; public String message; public boolean hasMore; public List> examples; @@ -44,6 +49,7 @@ public class CodegenResponse implements IJsonSchemaValidationProperties { public boolean isEmail; public boolean isModel; public boolean isFreeFormObject; + public boolean isAnyType; public boolean isDefault; public boolean simpleType; public boolean primitiveType; @@ -72,7 +78,7 @@ public class CodegenResponse implements IJsonSchemaValidationProperties { public int hashCode() { return Objects.hash(headers, code, message, hasMore, examples, dataType, baseType, containerType, hasHeaders, isString, isNumeric, isInteger, isLong, isNumber, isFloat, isDouble, isByteArray, isBoolean, isDate, - isDateTime, isUuid, isEmail, isModel, isFreeFormObject, isDefault, simpleType, primitiveType, + isDateTime, isUuid, isEmail, isModel, isFreeFormObject, isAnyType, isDefault, simpleType, primitiveType, isMapContainer, isListContainer, isBinary, isFile, schema, jsonSchema, vendorExtensions, getMaxProperties(), getMinProperties(), uniqueItems, getMaxItems(), getMinItems(), getMaxLength(), getMinLength(), exclusiveMinimum, exclusiveMaximum, getMinimum(), getMaximum(), getPattern()); @@ -100,6 +106,7 @@ public boolean equals(Object o) { isEmail == that.isEmail && isModel == that.isModel && isFreeFormObject == that.isFreeFormObject && + isAnyType == that.isAnyType && isDefault == that.isDefault && simpleType == that.simpleType && primitiveType == that.primitiveType && @@ -290,6 +297,7 @@ public String toString() { sb.append(", isEmail=").append(isEmail); sb.append(", isModel=").append(isModel); sb.append(", isFreeFormObject=").append(isFreeFormObject); + sb.append(", isAnyType=").append(isAnyType); sb.append(", isDefault=").append(isDefault); sb.append(", simpleType=").append(simpleType); sb.append(", primitiveType=").append(primitiveType); diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/DefaultCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/DefaultCodegen.java index bade86348d6d..71bb39fee086 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/DefaultCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/DefaultCodegen.java @@ -25,7 +25,6 @@ import com.samskivert.mustache.Mustache; import com.samskivert.mustache.Mustache.Compiler; import com.samskivert.mustache.Mustache.Lambda; - import io.swagger.v3.core.util.Json; import io.swagger.v3.oas.models.OpenAPI; import io.swagger.v3.oas.models.Operation; @@ -57,11 +56,7 @@ import org.openapitools.codegen.meta.features.*; import org.openapitools.codegen.serializer.SerializerUtils; import org.openapitools.codegen.templating.MustacheEngineAdapter; -import org.openapitools.codegen.templating.mustache.CamelCaseLambda; -import org.openapitools.codegen.templating.mustache.IndentedLambda; -import org.openapitools.codegen.templating.mustache.LowercaseLambda; -import org.openapitools.codegen.templating.mustache.TitlecaseLambda; -import org.openapitools.codegen.templating.mustache.UppercaseLambda; +import org.openapitools.codegen.templating.mustache.*; import org.openapitools.codegen.utils.ModelUtils; import org.openapitools.codegen.utils.OneOfImplementorAdditionalData; import org.slf4j.Logger; @@ -77,6 +72,7 @@ import java.util.stream.Collectors; import java.util.stream.Stream; +import static org.openapitools.codegen.utils.OnceLogger.once; import static org.openapitools.codegen.utils.StringUtils.*; public class DefaultCodegen implements CodegenConfig { @@ -132,9 +128,11 @@ public class DefaultCodegen implements CodegenConfig { ) .build(); + int cacheSize = Integer.parseInt(GlobalSettings.getProperty(NAME_CACHE_SIZE_PROPERTY, "500")); + int cacheExpiry = Integer.parseInt(GlobalSettings.getProperty(NAME_CACHE_EXPIRY_PROPERTY, "10")); sanitizedNameCache = Caffeine.newBuilder() - .maximumSize(500) - .expireAfterAccess(10, TimeUnit.SECONDS) + .maximumSize(cacheSize) + .expireAfterAccess(cacheExpiry, TimeUnit.SECONDS) .ticker(Ticker.systemTicker()) .build(); } @@ -217,6 +215,9 @@ apiTemplateFiles are for API outputs only (controllers/handlers). // flag to indicate whether enum value prefixes are removed protected boolean removeEnumValuePrefix = true; + // Support legacy logic for evaluating discriminators + protected boolean legacyDiscriminatorBehavior = true; + // make openapi available to all methods protected OpenAPI openAPI; @@ -308,6 +309,11 @@ public void processOpts() { this.setRemoveEnumValuePrefix(Boolean.valueOf(additionalProperties .get(CodegenConstants.REMOVE_ENUM_VALUE_PREFIX).toString())); } + + if (additionalProperties.containsKey(CodegenConstants.LEGACY_DISCRIMINATOR_BEHAVIOR)) { + this.setLegacyDiscriminatorBehavior(Boolean.valueOf(additionalProperties + .get(CodegenConstants.LEGACY_DISCRIMINATOR_BEHAVIOR).toString())); + } } /*** @@ -470,7 +476,8 @@ public Map updateAllModels(Map objs) { } parent.getChildren().add(cm); parent.hasChildren = true; - if (parent.getDiscriminator() == null) { + Schema parentSchema = this.openAPI.getComponents().getSchemas().get(parent.name); + if (parentSchema.getDiscriminator() == null) { parent = allModels.get(parent.getParent()); } else { parent = null; @@ -501,34 +508,34 @@ public Map updateAllModels(Map objs) { public void setCircularReferences(Map models) { final Map> dependencyMap = models.entrySet().stream() - .collect(Collectors.toMap(Entry::getKey, entry -> getModelDependencies(entry.getValue()))); + .collect(Collectors.toMap(Entry::getKey, entry -> getModelDependencies(entry.getValue()))); models.keySet().forEach(name -> setCircularReferencesOnProperties(name, dependencyMap)); } private List getModelDependencies(CodegenModel model) { return model.getAllVars().stream() - .map(prop -> { - if (prop.isContainer) { - return prop.items.dataType == null ? null : prop; - } - return prop.dataType == null ? null : prop; - }) - .filter(prop -> prop != null) - .collect(Collectors.toList()); + .map(prop -> { + if (prop.isContainer) { + return prop.items.dataType == null ? null : prop; + } + return prop.dataType == null ? null : prop; + }) + .filter(prop -> prop != null) + .collect(Collectors.toList()); } private void setCircularReferencesOnProperties(final String root, final Map> dependencyMap) { dependencyMap.getOrDefault(root, new ArrayList<>()).stream() - .forEach(prop -> { - final List unvisited = - Collections.singletonList(prop.isContainer ? prop.items.dataType : prop.dataType); - prop.isCircularReference = isCircularReference(root, - new HashSet<>(), - new ArrayList<>(unvisited), - dependencyMap); - }); + .forEach(prop -> { + final List unvisited = + Collections.singletonList(prop.isContainer ? prop.items.dataType : prop.dataType); + prop.isCircularReference = isCircularReference(root, + new HashSet<>(), + new ArrayList<>(unvisited), + dependencyMap); + }); } private boolean isCircularReference(final String root, @@ -542,7 +549,7 @@ private boolean isCircularReference(final String root, return true; } dependencyMap.getOrDefault(next, new ArrayList<>()) - .forEach(prop -> unvisited.add(prop.isContainer ? prop.items.dataType : prop.dataType)); + .forEach(prop -> unvisited.add(prop.isContainer ? prop.items.dataType : prop.dataType)); visited.add(next); } } @@ -767,7 +774,7 @@ public void preprocessOpenAPI(OpenAPI openAPI) { if (e.getKey().contains("/")) { // if this is property schema, we also need to generate the oneOf interface model addOneOfNameExtension((ComposedSchema) s, nOneOf); - addOneOfInterfaceModel((ComposedSchema) s, nOneOf); + addOneOfInterfaceModel((ComposedSchema) s, nOneOf, openAPI); } else { // else this is a component schema, so we will just use that as the oneOf interface model addOneOfNameExtension((ComposedSchema) s, n); @@ -776,13 +783,13 @@ public void preprocessOpenAPI(OpenAPI openAPI) { Schema items = ((ArraySchema) s).getItems(); if (ModelUtils.isComposedSchema(items)) { addOneOfNameExtension((ComposedSchema) items, nOneOf); - addOneOfInterfaceModel((ComposedSchema) items, nOneOf); + addOneOfInterfaceModel((ComposedSchema) items, nOneOf, openAPI); } } else if (ModelUtils.isMapSchema(s)) { Schema addProps = ModelUtils.getAdditionalProperties(s); if (addProps != null && ModelUtils.isComposedSchema(addProps)) { addOneOfNameExtension((ComposedSchema) addProps, nOneOf); - addOneOfInterfaceModel((ComposedSchema) addProps, nOneOf); + addOneOfInterfaceModel((ComposedSchema) addProps, nOneOf, openAPI); } } } @@ -1111,6 +1118,14 @@ public void setEnsureUniqueParams(Boolean ensureUniqueParams) { this.ensureUniqueParams = ensureUniqueParams; } + public Boolean getLegacyDiscriminatorBehavior() { + return legacyDiscriminatorBehavior; + } + + public void setLegacyDiscriminatorBehavior(boolean val) { + this.legacyDiscriminatorBehavior = val; + } + public Boolean getAllowUnicodeIdentifiers() { return allowUnicodeIdentifiers; } @@ -1119,7 +1134,9 @@ public void setAllowUnicodeIdentifiers(Boolean allowUnicodeIdentifiers) { this.allowUnicodeIdentifiers = allowUnicodeIdentifiers; } - public Boolean getUseOneOfInterfaces() { return useOneOfInterfaces; } + public Boolean getUseOneOfInterfaces() { + return useOneOfInterfaces; + } public void setUseOneOfInterfaces(Boolean useOneOfInterfaces) { this.useOneOfInterfaces = useOneOfInterfaces; @@ -1381,6 +1398,7 @@ public DefaultCodegen() { typeMapping.put("UUID", "UUID"); typeMapping.put("URI", "URI"); typeMapping.put("BigDecimal", "BigDecimal"); + typeMapping.put("AnyType", "oas_any_type_not_mapped"); instantiationTypes = new HashMap(); @@ -1424,6 +1442,14 @@ public DefaultCodegen() { cliOptions.add(CliOption.newBoolean(CodegenConstants.PREPEND_FORM_OR_BODY_PARAMETERS, CodegenConstants.PREPEND_FORM_OR_BODY_PARAMETERS_DESC).defaultValue(Boolean.FALSE.toString())); + // option to change how we process + set the data in the discriminator mapping + CliOption legacyDiscriminatorBehaviorOpt = CliOption.newBoolean(CodegenConstants.LEGACY_DISCRIMINATOR_BEHAVIOR, CodegenConstants.LEGACY_DISCRIMINATOR_BEHAVIOR_DESC).defaultValue(Boolean.TRUE.toString()); + Map legacyDiscriminatorBehaviorOpts = new HashMap<>(); + legacyDiscriminatorBehaviorOpts.put("true", "The mapping in the discriminator includes descendent schemas that allOf inherit from self and the discriminator mapping schemas in the OAS document."); + legacyDiscriminatorBehaviorOpts.put("false", "The mapping in the discriminator includes any descendent schemas that allOf inherit from self, any oneOf schemas, any anyOf schemas, any x-discriminator-values, and the discriminator mapping schemas in the OAS document AND Codegen validates that oneOf and anyOf schemas contain the required discriminator and throws an error if the discriminator is missing."); + legacyDiscriminatorBehaviorOpt.setEnum(legacyDiscriminatorBehaviorOpts); + cliOptions.add(legacyDiscriminatorBehaviorOpt); + // initialize special character mapping initalizeSpecialCharacterMapping(); @@ -1654,7 +1680,7 @@ public void setParameterExampleValue(CodegenParameter codegenParameter, RequestB if (content.size() > 1) { // @see ModelUtils.getSchemaFromContent() - LOGGER.warn("Multiple MediaTypes found, using only the first one"); + once(LOGGER).warn("Multiple MediaTypes found, using only the first one"); } MediaType mediaType = content.values().iterator().next(); @@ -1802,7 +1828,7 @@ protected Schema getSchemaAdditionalProperties(Schema schema) { /** * Return the name of the 'allOf' composed schema. - * + * * @param names List of names * @param composedSchema composed schema * @return name of the allOf schema @@ -1837,7 +1863,13 @@ public String toAnyOfName(List names, ComposedSchema composedSchema) { } /** - * Return the name of the oneOf schema + * Return the name of the oneOf schema. + *

      + * This name is used to set the value of CodegenProperty.openApiType. + *

      + * If the 'x-one-of-name' extension is specified in the OAS document, return that value. + * Otherwise, a name is constructed by creating a comma-separated list of all the names + * of the oneOf schemas. * * @param names List of names * @param composedSchema composed schema @@ -1846,15 +1878,15 @@ public String toAnyOfName(List names, ComposedSchema composedSchema) { @SuppressWarnings("static-method") public String toOneOfName(List names, ComposedSchema composedSchema) { Map exts = composedSchema.getExtensions(); - if (exts != null && exts.containsKey("x-oneOf-name")) { - return (String) exts.get("x-oneOf-name"); + if (exts != null && exts.containsKey("x-one-of-name")) { + return (String) exts.get("x-one-of-name"); } return "oneOf<" + String.join(",", names) + ">"; } /** * Return a string representation of the schema type, resolving aliasing and references if necessary. - * + * * @param schema * @return the string representation of the schema type. */ @@ -1881,7 +1913,7 @@ private String getSingleSchemaType(Schema schema) { /** * Return the OAI type (e.g. integer, long, etc) corresponding to a schema. *

      $ref
      is not taken into account by this method. - * + *

      * If the schema is free-form (i.e. 'type: object' with no properties) or inline * schema, the returned OAI type is 'object'. * @@ -1950,6 +1982,8 @@ private String getPrimitiveType(Schema schema) { return "object"; } else if (schema.getProperties() != null && !schema.getProperties().isEmpty()) { // having property implies it's a model return "object"; + } else if (ModelUtils.isAnyTypeSchema(schema)) { + return "AnyType"; } else if (StringUtils.isNotEmpty(schema.getType())) { LOGGER.warn("Unknown type found in the schema: " + schema.getType()); return schema.getType(); @@ -2114,8 +2148,15 @@ public CodegenModel fromModel(String name, Schema schema) { m.getVendorExtensions().putAll(schema.getExtensions()); } m.isAlias = (typeAliases.containsKey(name) - || isAliasOfSimpleTypes(schema)); // check if the unaliased schema is an alias of simple OAS types - m.discriminator = createDiscriminator(name, schema); + || isAliasOfSimpleTypes(schema)); // check if the unaliased schema is an alias of simple OAS types + m.discriminator = createDiscriminator(name, schema, this.openAPI); + if (!this.getLegacyDiscriminatorBehavior()) { + m.addDiscriminatorMappedModelsImports(); + } + + if (schema.getDeprecated() != null) { + m.isDeprecated = schema.getDeprecated(); + } if (schema.getXml() != null) { m.xmlPrefix = schema.getXml().getPrefix(); @@ -2157,7 +2198,10 @@ public CodegenModel fromModel(String name, Schema schema) { for (Schema innerSchema : composed.getAllOf()) { // TODO need to work with anyOf, oneOf as well if (m.discriminator == null && innerSchema.getDiscriminator() != null) { LOGGER.debug("discriminator is set to null (not correctly set earlier): {}", name); - m.discriminator = createDiscriminator(name, innerSchema); + m.discriminator = createDiscriminator(name, innerSchema, this.openAPI); + if (!this.getLegacyDiscriminatorBehavior()) { + m.addDiscriminatorMappedModelsImports(); + } modelDiscriminators++; } @@ -2186,9 +2230,33 @@ public CodegenModel fromModel(String name, Schema schema) { m.interfaces = new ArrayList(); for (Schema interfaceSchema : interfaces) { + interfaceSchema = ModelUtils.unaliasSchema(this.openAPI, interfaceSchema, importMapping); + if (StringUtils.isBlank(interfaceSchema.get$ref())) { + // primitive type + String languageType = getTypeDeclaration(interfaceSchema); + + if (composed.getAnyOf() != null) { + if (m.anyOf.contains(languageType)) { + LOGGER.warn("{} (anyOf schema) already has `{}` defined and therefore it's skipped.", m.name, languageType); + } else { + m.anyOf.add(languageType); + } + } else if (composed.getOneOf() != null) { + if (m.oneOf.contains(languageType)) { + LOGGER.warn("{} (oneOf schema) already has `{}` defined and therefore it's skipped.", m.name, languageType); + } else { + m.oneOf.add(languageType); + } + } else if (composed.getAllOf() != null) { + // no need to add primitive type to allOf, which should comprise of schemas (models) only + } else { + LOGGER.error("Composed schema has incorrect anyOf, allOf, oneOf defined: {}", composed); + } continue; } + + // the rest of the section is for model Schema refSchema = null; String ref = ModelUtils.getSimpleRef(interfaceSchema.get$ref()); if (allDefinitions != null) { @@ -2223,7 +2291,7 @@ public CodegenModel fromModel(String name, Schema schema) { } } - if (parent != null) { + if (parent != null && composed.getAllOf() != null) { // set parent for allOf only m.parentSchema = parentName; m.parent = toModelName(parentName); @@ -2257,6 +2325,7 @@ public CodegenModel fromModel(String name, Schema schema) { required.addAll(composed.getRequired()); allRequired.addAll(composed.getRequired()); } + addVars(m, unaliasPropertySchema(properties), required, unaliasPropertySchema(allProperties), allRequired); // end of code block for composed schema @@ -2317,6 +2386,7 @@ public CodegenModel fromModel(String name, Schema schema) { for (CodegenProperty prop : m.vars) { postProcessModelProperty(m, prop); } + m.hasVars = m.vars.size() > 0; } if (m.allVars != null) { for (CodegenProperty prop : m.allVars) { @@ -2324,6 +2394,22 @@ public CodegenModel fromModel(String name, Schema schema) { } } + // set isDiscriminator on the discriminator property + if (m.discriminator != null) { + String discPropName = m.discriminator.getPropertyBaseName(); + List> listOLists = new ArrayList>(); + listOLists.add(m.requiredVars); + listOLists.add(m.vars); + listOLists.add(m.allVars); + for (List theseVars : listOLists) { + for (CodegenProperty requiredVar : theseVars) { + if (discPropName.equals(requiredVar.baseName)) { + requiredVar.isDiscriminator = true; + } + } + } + } + if (sortModelPropertiesByRequiredFlag) { Comparator comparator = new Comparator() { @Override @@ -2340,36 +2426,319 @@ public int compare(CodegenProperty one, CodegenProperty another) { return m; } - protected CodegenDiscriminator createDiscriminator(String schemaName, Schema schema) { - if (schema.getDiscriminator() == null) { + /** + * Recursively look in Schema sc for the discriminator discPropName + * and return a CodegenProperty with the dataType and required params set + * the returned CodegenProperty may not be required and it may not be of type string + * + * @param composedSchemaName The name of the sc Schema + * @param sc The Schema that may contain the discriminator + * @param discPropName The String that is the discriminator propertyName in the schema + */ + private CodegenProperty discriminatorFound(String composedSchemaName, Schema sc, String discPropName, OpenAPI openAPI) { + Schema refSchema = ModelUtils.getReferencedSchema(openAPI, sc); + if (refSchema.getProperties() != null && refSchema.getProperties().get(discPropName) != null) { + Schema discSchema = (Schema) refSchema.getProperties().get(discPropName); + CodegenProperty cp = new CodegenProperty(); + if (ModelUtils.isStringSchema(discSchema)) { + cp.isString = true; + } + cp.setRequired(false); + if (refSchema.getRequired() != null && refSchema.getRequired().contains(discPropName)) { + cp.setRequired(true); + } + return cp; + } + if (ModelUtils.isComposedSchema(refSchema)) { + ComposedSchema composedSchema = (ComposedSchema) refSchema; + if (composedSchema.getAllOf() != null) { + // If our discriminator is in one of the allOf schemas break when we find it + for (Schema allOf : composedSchema.getAllOf()) { + CodegenProperty cp = discriminatorFound(composedSchemaName, allOf, discPropName, openAPI); + if (cp != null) { + return cp; + } + } + } + if (composedSchema.getOneOf() != null && composedSchema.getOneOf().size() != 0) { + // All oneOf definitions must contain the discriminator + CodegenProperty cp = new CodegenProperty(); + for (Schema oneOf : composedSchema.getOneOf()) { + String modelName = ModelUtils.getSimpleRef(oneOf.get$ref()); + CodegenProperty thisCp = discriminatorFound(composedSchemaName, oneOf, discPropName, openAPI); + if (thisCp == null) { + throw new RuntimeException("'" + composedSchemaName + "' defines discriminator '" + discPropName + "', but the referenced OneOf schema '" + modelName + "' is missing " + discPropName); + } + if (cp.dataType == null) { + cp = thisCp; + continue; + } + if (cp != thisCp) { + throw new RuntimeException("'" + composedSchemaName + "' defines discriminator '" + discPropName + "', but the OneOf schema '" + modelName + "' has a different " + discPropName + " definition than the prior OneOf schema's. Make sure the " + discPropName + " type and required values are the same"); + } + } + return cp; + } + if (composedSchema.getAnyOf() != null && composedSchema.getAnyOf().size() != 0) { + // All anyOf definitions must contain the discriminator because a min of one must be selected + CodegenProperty cp = new CodegenProperty(); + for (Schema anyOf : composedSchema.getAnyOf()) { + String modelName = ModelUtils.getSimpleRef(anyOf.get$ref()); + CodegenProperty thisCp = discriminatorFound(composedSchemaName, anyOf, discPropName, openAPI); + if (thisCp == null) { + throw new RuntimeException("'" + composedSchemaName + "' defines discriminator '" + discPropName + "', but the referenced AnyOf schema '" + modelName + "' is missing " + discPropName); + } + if (cp.dataType == null) { + cp = thisCp; + continue; + } + if (cp != thisCp) { + throw new RuntimeException("'" + composedSchemaName + "' defines discriminator '" + discPropName + "', but the AnyOf schema '" + modelName + "' has a different " + discPropName + " definition than the prior AnyOf schema's. Make sure the " + discPropName + " type and required values are the same"); + } + } + return cp; + + } + } + return null; + } + + /** + * Recursively look in Schema sc for the discriminator and return it + * Schema sc location + * OpenAPI openAPI the spec where we are searching for the discriminator + * + * @param sc The Schema that may contain the discriminator + */ + private Discriminator recursiveGetDiscriminator(Schema sc, OpenAPI openAPI) { + Schema refSchema = ModelUtils.getReferencedSchema(openAPI, sc); + Discriminator foundDisc = refSchema.getDiscriminator(); + if (foundDisc != null) { + return foundDisc; + } + if (!!this.getLegacyDiscriminatorBehavior()) { + return null; + } + Discriminator disc = new Discriminator(); + if (ModelUtils.isComposedSchema(refSchema)) { + ComposedSchema composedSchema = (ComposedSchema) refSchema; + if (composedSchema.getAllOf() != null) { + // If our discriminator is in one of the allOf schemas break when we find it + for (Schema allOf : composedSchema.getAllOf()) { + foundDisc = recursiveGetDiscriminator(allOf, openAPI); + if (foundDisc != null) { + disc.setPropertyName(foundDisc.getPropertyName()); + disc.setMapping(foundDisc.getMapping()); + return disc; + } + } + } + if (composedSchema.getOneOf() != null && composedSchema.getOneOf().size() != 0) { + // All oneOf definitions must contain the discriminator + Integer hasDiscriminatorCnt = 0; + Set discriminatorsPropNames = new HashSet<>(); + for (Schema oneOf : composedSchema.getOneOf()) { + foundDisc = recursiveGetDiscriminator(oneOf, openAPI); + if (foundDisc != null) { + discriminatorsPropNames.add(foundDisc.getPropertyName()); + hasDiscriminatorCnt++; + } + } + if (hasDiscriminatorCnt == composedSchema.getOneOf().size() && discriminatorsPropNames.size() == 1) { + disc.setPropertyName(foundDisc.getPropertyName()); + disc.setMapping(foundDisc.getMapping()); + return disc; + } + } + if (composedSchema.getAnyOf() != null && composedSchema.getAnyOf().size() != 0) { + // All anyOf definitions must contain the discriminator because a min of one must be selected + Integer hasDiscriminatorCnt = 0; + Set discriminatorsPropNames = new HashSet<>(); + for (Schema anyOf : composedSchema.getAnyOf()) { + foundDisc = recursiveGetDiscriminator(anyOf, openAPI); + if (foundDisc != null) { + discriminatorsPropNames.add(foundDisc.getPropertyName()); + hasDiscriminatorCnt++; + } + } + if (hasDiscriminatorCnt == composedSchema.getAnyOf().size() && discriminatorsPropNames.size() == 1) { + disc.setPropertyName(foundDisc.getPropertyName()); + disc.setMapping(foundDisc.getMapping()); + return disc; + } + } + } + return null; + } + + /** + * This function is only used for composed schemas which have a discriminator + * Process oneOf and anyOf models in a composed schema and adds them into + * a list if the oneOf and anyOf models contain + * the required discriminator. If they don't contain the required + * discriminator or the discriminator is the wrong type then an error is + * thrown + * + * @param composedSchemaName The String model name of the composed schema where we are setting the discriminator map + * @param discPropName The String that is the discriminator propertyName in the schema + * @param c The ComposedSchema that contains the discriminator and oneOf/anyOf schemas + * @param openAPI The OpenAPI spec that we are using + * @return the list of oneOf and anyOf MappedModel that need to be added to the discriminator map + */ + protected List getOneOfAnyOfDescendants(String composedSchemaName, String discPropName, ComposedSchema c, OpenAPI openAPI) { + ArrayList> listOLists = new ArrayList>(); + listOLists.add(c.getOneOf()); + listOLists.add(c.getAnyOf()); + List descendentSchemas = new ArrayList(); + for (List schemaList : listOLists) { + if (schemaList == null) { + continue; + } + for (Schema sc : schemaList) { + String ref = sc.get$ref(); + if (ref == null) { + // for schemas with no ref, it is not possible to build the discriminator map + // because ref is how we get the model name + // we only hit this use case for a schema with inline composed schemas, and one of those + // schemas also has inline composed schemas + // Note: if it is only inline one level, then the inline model resolver will move it into its own + // schema and make it a $ref schema in the oneOf/anyOf location + throw new RuntimeException("Invalid inline schema defined in oneOf/anyOf in '" + composedSchemaName + "'. Per the OpenApi spec, for this case when a composed schema defines a discriminator, the oneOf/anyOf schemas must use $ref. Change this inline definition to a $ref definition"); + } + CodegenProperty df = discriminatorFound(composedSchemaName, sc, discPropName, openAPI); + String modelName = ModelUtils.getSimpleRef(ref); + if (df == null || !df.isString || df.required != true) { + String msgSuffix = ""; + if (df == null) { + msgSuffix += discPropName + " is missing from the schema, define it as required and type string"; + } else { + if (!df.isString) { + msgSuffix += "invalid type for " + discPropName + ", set it to string"; + } + if (df.required != true) { + String spacer = ""; + if (msgSuffix.length() != 0) { + spacer = ". "; + } + msgSuffix += spacer + "invalid optional definition of " + discPropName + ", include it in required"; + } + } + throw new RuntimeException("'" + composedSchemaName + "' defines discriminator '" + discPropName + "', but the referenced schema '" + modelName + "' is incorrect. " + msgSuffix); + } + MappedModel mm = new MappedModel(modelName, toModelName(modelName)); + descendentSchemas.add(mm); + Schema cs = ModelUtils.getSchema(openAPI, modelName); + Map vendorExtensions = cs.getExtensions(); + if (vendorExtensions != null && !vendorExtensions.isEmpty() && vendorExtensions.containsKey("x-discriminator-value")) { + String xDiscriminatorValue = (String) vendorExtensions.get("x-discriminator-value"); + mm = new MappedModel(xDiscriminatorValue, toModelName(modelName)); + descendentSchemas.add(mm); + } + + } + } + return descendentSchemas; + } + + protected List getAllOfDescendants(String thisSchemaName, OpenAPI openAPI) { + ArrayList queue = new ArrayList(); + List descendentSchemas = new ArrayList(); + Map schemas = ModelUtils.getSchemas(openAPI); + String currentSchemaName = thisSchemaName; + while (true) { + for (String childName : schemas.keySet()) { + if (childName == thisSchemaName) { + continue; + } + Schema child = schemas.get(childName); + if (ModelUtils.isComposedSchema(child)) { + ComposedSchema composedChild = (ComposedSchema) child; + List parents = composedChild.getAllOf(); + if (parents != null) { + for (Schema parent : parents) { + String ref = parent.get$ref(); + if (ref == null) { + // for schemas with no ref, it is not possible to build the discriminator map + // because ref is how we get the model name + // we only hit this use case for a schema with inline composed schemas, and one of those + // schemas also has inline composed schemas + throw new RuntimeException("Invalid inline schema defined in allOf in '" + childName + "'. Per the OpenApi spec, for this case when a composed schema defines a discriminator, the allOf schemas must use $ref. Change this inline definition to a $ref definition"); + } + String parentName = ModelUtils.getSimpleRef(ref); + if (parentName.equals(currentSchemaName)) { + if (queue.contains(childName) || descendentSchemas.contains(childName)) { + throw new RuntimeException("Stack overflow hit when looking for " + thisSchemaName + " an infinite loop starting and ending at " + childName + " was seen"); + } + queue.add(childName); + break; + } + } + } + } + } + if (queue.size() == 0) { + break; + } + currentSchemaName = queue.remove(0); + MappedModel mm = new MappedModel(currentSchemaName, toModelName(currentSchemaName)); + descendentSchemas.add(mm); + Schema cs = schemas.get(currentSchemaName); + Map vendorExtensions = cs.getExtensions(); + if (vendorExtensions != null && !vendorExtensions.isEmpty() && vendorExtensions.containsKey("x-discriminator-value")) { + String xDiscriminatorValue = (String) vendorExtensions.get("x-discriminator-value"); + mm = new MappedModel(xDiscriminatorValue, toModelName(currentSchemaName)); + descendentSchemas.add(mm); + } + } + return descendentSchemas; + } + + protected CodegenDiscriminator createDiscriminator(String schemaName, Schema schema, OpenAPI openAPI) { + Discriminator sourceDiscriminator = recursiveGetDiscriminator(schema, openAPI); + if (sourceDiscriminator == null) { return null; } CodegenDiscriminator discriminator = new CodegenDiscriminator(); - discriminator.setPropertyName(toVarName(schema.getDiscriminator().getPropertyName())); - discriminator.setPropertyBaseName(schema.getDiscriminator().getPropertyName()); + String discPropName = sourceDiscriminator.getPropertyName(); + discriminator.setPropertyName(toVarName(discPropName)); + discriminator.setPropertyBaseName(sourceDiscriminator.getPropertyName()); discriminator.setPropertyGetter(toGetter(discriminator.getPropertyName())); // FIXME: for now, we assume that the discriminator property is String discriminator.setPropertyType(typeMapping.get("string")); - discriminator.setMapping(schema.getDiscriminator().getMapping()); - if (schema.getDiscriminator().getMapping() != null && !schema.getDiscriminator().getMapping().isEmpty()) { - for (Entry e : schema.getDiscriminator().getMapping().entrySet()) { + discriminator.setMapping(sourceDiscriminator.getMapping()); + List uniqueDescendants = new ArrayList(); + if (sourceDiscriminator.getMapping() != null && !sourceDiscriminator.getMapping().isEmpty()) { + for (Entry e : sourceDiscriminator.getMapping().entrySet()) { String nameOrRef = e.getValue(); String name = nameOrRef.indexOf('/') >= 0 ? ModelUtils.getSimpleRef(nameOrRef) : nameOrRef; String modelName = toModelName(name); - discriminator.getMappedModels().add(new MappedModel(e.getKey(), modelName)); + uniqueDescendants.add(new MappedModel(e.getKey(), modelName)); } - } else { - Map allDefinitions = ModelUtils.getSchemas(this.openAPI); - allDefinitions.forEach((childName, child) -> { - if (child instanceof ComposedSchema && ((ComposedSchema) child).getAllOf() != null) { + } - final List parentSchemas = ModelUtils.getAllParentsName((ComposedSchema) child, allDefinitions, true); - if (parentSchemas.contains(schemaName)) { - discriminator.getMappedModels().add(new MappedModel(childName, toModelName(childName))); - } + boolean legacyUseCase = (this.getLegacyDiscriminatorBehavior() && uniqueDescendants.isEmpty()); + if (!this.getLegacyDiscriminatorBehavior() || legacyUseCase) { + // for schemas that allOf inherit from this schema, add those descendants to this discriminator map + List otherDescendants = getAllOfDescendants(schemaName, openAPI); + for (MappedModel otherDescendant : otherDescendants) { + if (!uniqueDescendants.contains(otherDescendant)) { + uniqueDescendants.add(otherDescendant); } - }); + } } + // if there are composed oneOf/anyOf schemas, add them to this discriminator + if (ModelUtils.isComposedSchema(schema) && !this.getLegacyDiscriminatorBehavior()) { + List otherDescendants = getOneOfAnyOfDescendants(schemaName, discPropName, (ComposedSchema) schema, openAPI); + for (MappedModel otherDescendant : otherDescendants) { + if (!uniqueDescendants.contains(otherDescendant)) { + uniqueDescendants.add(otherDescendant); + } + } + } + if (!this.getLegacyDiscriminatorBehavior()) { + Collections.sort(uniqueDescendants); + } + discriminator.getMappedModels().addAll(uniqueDescendants); return discriminator; } @@ -2388,8 +2757,10 @@ protected void addProperties(Map properties, List requir if (schema instanceof ComposedSchema) { ComposedSchema composedSchema = (ComposedSchema) schema; - for (Schema component : composedSchema.getAllOf()) { - addProperties(properties, required, component); + if (composedSchema.getAllOf() != null) { + for (Schema component : composedSchema.getAllOf()) { + addProperties(properties, required, component); + } } if (schema.getRequired() != null) { @@ -2397,11 +2768,15 @@ protected void addProperties(Map properties, List requir } if (composedSchema.getOneOf() != null) { - throw new RuntimeException("Please report the issue: Cannot process oneOf (Composed Scheme) in addProperties: " + schema); + for (Schema component : composedSchema.getOneOf()) { + addProperties(properties, required, component); + } } if (composedSchema.getAnyOf() != null) { - throw new RuntimeException("Please report the issue: Cannot process anyOf (Composed Schema) in addProperties: " + schema); + for (Schema component : composedSchema.getAnyOf()) { + addProperties(properties, required, component); + } } return; @@ -2475,6 +2850,17 @@ public CodegenProperty fromProperty(String name, Schema p) { if (p.getDeprecated() != null) { property.deprecated = p.getDeprecated(); + } else if (p.get$ref() != null) { + // Since $ref should be replaced with the model it refers + // to, $ref'ing a model with 'deprecated' set should cause + // the property to reflect the model's 'deprecated' value. + String ref = ModelUtils.getSimpleRef(p.get$ref()); + if (ref != null) { + Schema referencedSchema = ModelUtils.getSchemas(this.openAPI).get(ref); + if (referencedSchema != null && referencedSchema.getDeprecated() != null) { + property.deprecated = referencedSchema.getDeprecated(); + } + } } if (p.getReadOnly() != null) { property.isReadOnly = p.getReadOnly(); @@ -2599,6 +2985,8 @@ public CodegenProperty fromProperty(String name, Schema p) { } else if (ModelUtils.isFreeFormObject(p)) { property.isFreeFormObject = true; + } else if (ModelUtils.isAnyTypeSchema(p)) { + property.isAnyType = true; } else if (ModelUtils.isArraySchema(p)) { // default to string if inner item is undefined ArraySchema arraySchema = (ArraySchema) p; @@ -2705,18 +3093,13 @@ public CodegenProperty fromProperty(String name, Schema p) { } else if (ModelUtils.isFreeFormObject(p)) { property.isFreeFormObject = true; property.baseType = getSchemaType(p); + } else if (ModelUtils.isAnyTypeSchema(p)) { + property.isAnyType = true; + property.baseType = getSchemaType(p); } else { // model - // TODO revise the logic below - //if (StringUtils.isNotBlank(p.get$ref())) { - // property.baseType = getSimpleRef(p.get$ref()); - //} - // --END of revision setNonArrayMapProperty(property, type); Schema refOrCurrent = ModelUtils.getReferencedSchema(this.openAPI, p); property.isModel = (ModelUtils.isComposedSchema(refOrCurrent) || ModelUtils.isObjectSchema(refOrCurrent)) && ModelUtils.isModel(refOrCurrent); - if (ModelUtils.isAnyTypeSchema(p)) { - property.isAnyType = true; - } } LOGGER.debug("debugging from property return: " + property); @@ -3299,10 +3682,29 @@ public CodegenResponse fromResponse(String responseCode, ApiResponse response) { } } - if ("default".equals(responseCode)) { + if ("default".equals(responseCode) || "defaultResponse".equals(responseCode)) { r.code = "0"; } else { r.code = responseCode; + switch (r.code.charAt(0)) { + case '1': + r.is1xx = true; + break; + case '2': + r.is2xx = true; + break; + case '3': + r.is3xx = true; + break; + case '4': + r.is4xx = true; + break; + case '5': + r.is5xx = true; + break; + default: + throw new RuntimeException("Invalid response code " + responseCode); + } } Schema responseSchema; if (this.openAPI != null && this.openAPI.getComponents() != null) { @@ -3385,6 +3787,8 @@ public CodegenResponse fromResponse(String responseCode, ApiResponse response) { r.isDateTime = true; } else if (Boolean.TRUE.equals(cp.isFreeFormObject)) { r.isFreeFormObject = true; + } else if (Boolean.TRUE.equals(cp.isAnyType)) { + r.isAnyType = true; } else { LOGGER.debug("Property type is not primitive: " + cp.dataType); } @@ -3530,7 +3934,7 @@ public CodegenParameter fromParameter(Parameter parameter, Set imports) } else if (parameter.getContent() != null) { Content content = parameter.getContent(); if (content.size() > 1) { - LOGGER.warn("Multiple schemas found in content, returning only the first one"); + once(LOGGER).warn("Multiple schemas found in content, returning only the first one"); } MediaType mediaType = content.values().iterator().next(); s = mediaType.getSchema(); @@ -3686,91 +4090,6 @@ public CodegenParameter fromParameter(Parameter parameter, Set imports) } else { LOGGER.error("ERROR! Not handling " + parameter + " as Body Parameter at the moment"); - /* TODO need to revise the logic below to handle body parameter - if (!(parameter instanceof BodyParameter)) { - LOGGER.error("Cannot use Parameter " + parameter + " as Body Parameter"); - } - - BodyParameter bp = (BodyParameter) param; - Model model = bp.getSchema(); - - if (model instanceof ModelImpl) { - ModelImpl impl = (ModelImpl) model; - CodegenModel cm = fromModel(bp.getName(), impl); - if (!cm.emptyVars) { - codegen.dataType = getTypeDeclaration(cm.classname); - imports.add(p.dataType); - } else { - Property prop = PropertyBuilder.build(impl.getType(), impl.getFormat(), null); - prop.setRequired(bp.getRequired()); - CodegenProperty cp = fromProperty("property", prop); - if (cp != null) { - p.baseType = cp.baseType; - p.dataType = cp.datatype; - p.isPrimitiveType = cp.isPrimitiveType; - p.isBinary = isDataTypeBinary(cp.datatype); - p.isFile = isDataTypeFile(cp.datatype); - if (cp.complexType != null) { - imports.add(cp.complexType); - } - } - - // set boolean flag (e.g. isString) - setParameterBooleanFlagWithCodegenProperty(p, cp); - } - } else if (model instanceof ArrayModel) { - // to use the built-in model parsing, we unwrap the ArrayModel - // and get a single property from it - ArrayModel impl = (ArrayModel) model; - // get the single property - ArrayProperty ap = new ArrayProperty().items(impl.getItems()); - ap.setRequired(param.getRequired()); - CodegenProperty cp = fromProperty("inner", ap); - if (cp.complexType != null) { - imports.add(cp.complexType); - } - imports.add(cp.baseType); - - // recursively add import - CodegenProperty innerCp = cp; - while(innerCp != null) { - if(innerCp.complexType != null) { - imports.add(innerCp.complexType); - } - innerCp = innerCp.items; - } - - p.items = cp; - p.dataType = cp.datatype; - p.baseType = cp.complexType; - p.isPrimitiveType = cp.isPrimitiveType; - p.isContainer = true; - p.isListContainer = true; - - // set boolean flag (e.g. isString) - setParameterBooleanFlagWithCodegenProperty(p, cp); - } else { - Model sub = bp.getSchema(); - if (sub instanceof RefModel) { - String name = ((RefModel) sub).getSimpleRef(); - name = getAlias(name); - if (typeMapping.containsKey(name)) { - name = typeMapping.get(name); - p.baseType = name; - } else { - name = toModelName(name); - p.baseType = name; - if (defaultIncludes.contains(name)) { - imports.add(name); - } - imports.add(name); - name = getTypeDeclaration(name); - } - p.dataType = name; - } - } - p.paramName = toParamName(bp.getName()); - */ } if (parameter instanceof QueryParameter || "query".equalsIgnoreCase(parameter.getIn())) { @@ -3884,7 +4203,7 @@ public List fromSecurity(Map securitySc // As of January 2020, the "signature" scheme has not been registered with IANA yet. // This scheme may have to be changed when it is officially registered with IANA. cs.isHttpSignature = true; - LOGGER.warn("Security scheme 'HTTP signature' is a draft IETF RFC and subject to change."); + once(LOGGER).warn("Security scheme 'HTTP signature' is a draft IETF RFC and subject to change."); } } else if (SecurityScheme.Type.OAUTH2.equals(securityScheme.getType())) { cs.isKeyInHeader = cs.isKeyInQuery = cs.isKeyInCookie = cs.isApiKey = cs.isBasic = false; @@ -4740,6 +5059,8 @@ public void setParameterBooleanFlagWithCodegenProperty(CodegenParameter paramete parameter.isPrimitiveType = true; } else if (Boolean.TRUE.equals(property.isFreeFormObject)) { parameter.isFreeFormObject = true; + } else if (Boolean.TRUE.equals(property.isAnyType)) { + parameter.isAnyType = true; } else { LOGGER.debug("Property type is not primitive: " + property.dataType); } @@ -5280,6 +5601,83 @@ public CodegenParameter fromFormProperty(String name, Schema propertySchema, Set return codegenParameter; } + private void addBodyModelSchema(CodegenParameter codegenParameter, String name, Schema schema, Set imports, String bodyParameterName, boolean forceSimpleRef) { + CodegenModel codegenModel = null; + if (StringUtils.isNotBlank(name)) { + schema.setName(name); + codegenModel = fromModel(name, schema); + } + if (codegenModel != null) { + codegenParameter.isModel = true; + } + + if (codegenModel != null && (codegenModel.hasVars || forceSimpleRef)) { + if (StringUtils.isEmpty(bodyParameterName)) { + codegenParameter.baseName = codegenModel.classname; + } else { + codegenParameter.baseName = bodyParameterName; + } + codegenParameter.paramName = toParamName(codegenParameter.baseName); + codegenParameter.baseType = codegenModel.classname; + codegenParameter.dataType = getTypeDeclaration(codegenModel.classname); + codegenParameter.description = codegenModel.description; + imports.add(codegenParameter.baseType); + } else { + CodegenProperty codegenProperty = fromProperty("property", schema); + + if (codegenProperty != null && codegenProperty.getComplexType() != null && codegenProperty.getComplexType().contains(" | ")) { + List parts = Arrays.asList(codegenProperty.getComplexType().split(" \\| ")); + imports.addAll(parts); + String codegenModelName = codegenProperty.getComplexType(); + codegenParameter.baseName = codegenModelName; + codegenParameter.paramName = toParamName(codegenParameter.baseName); + codegenParameter.baseType = codegenParameter.baseName; + codegenParameter.dataType = getTypeDeclaration(codegenModelName); + codegenParameter.description = codegenProperty.getDescription(); + } else { + if (ModelUtils.isMapSchema(schema)) {// http body is map + LOGGER.error("Map should be supported. Please report to openapi-generator github repo about the issue."); + } else if (codegenProperty != null) { + String codegenModelName, codegenModelDescription; + + if (codegenModel != null) { + codegenModelName = codegenModel.classname; + codegenModelDescription = codegenModel.description; + } else { + LOGGER.warn("The following schema has undefined (null) baseType. " + + "It could be due to form parameter defined in OpenAPI v2 spec with incorrect consumes. " + + "A correct 'consumes' for form parameters should be " + + "'application/x-www-form-urlencoded' or 'multipart/?'"); + LOGGER.warn("schema: " + schema); + LOGGER.warn("codegenModel is null. Default to UNKNOWN_BASE_TYPE"); + codegenModelName = "UNKNOWN_BASE_TYPE"; + codegenModelDescription = "UNKNOWN_DESCRIPTION"; + } + + if (StringUtils.isEmpty(bodyParameterName)) { + codegenParameter.baseName = codegenModelName; + } else { + codegenParameter.baseName = bodyParameterName; + } + + codegenParameter.paramName = toParamName(codegenParameter.baseName); + codegenParameter.baseType = codegenModelName; + codegenParameter.dataType = getTypeDeclaration(codegenModelName); + codegenParameter.description = codegenModelDescription; + imports.add(codegenParameter.baseType); + + if (codegenProperty.complexType != null) { + imports.add(codegenProperty.complexType); + } + } + } + + setParameterBooleanFlagWithCodegenProperty(codegenParameter, codegenProperty); + // set nullable + setParameterNullable(codegenParameter, codegenProperty); + } + } + public CodegenParameter fromRequestBody(RequestBody body, Set imports, String bodyParameterName) { if (body == null) { LOGGER.error("body in fromRequestBody cannot be null!"); @@ -5308,84 +5706,91 @@ public CodegenParameter fromRequestBody(RequestBody body, Set imports, S if (ModelUtils.isMapSchema(schema)) { // Schema with additionalproperties: true (including composed schemas with additionalproperties: true) - Schema inner = ModelUtils.getAdditionalProperties(schema); - if (inner == null) { - LOGGER.error("No inner type supplied for map parameter `{}`. Default to type:string", schema.getName()); - inner = new StringSchema().description("//TODO automatically added by openapi-generator"); - schema.setAdditionalProperties(inner); - } - CodegenProperty codegenProperty = fromProperty("property", schema); + if (ModelUtils.isGenerateAliasAsModel() && StringUtils.isNotBlank(name)) { + this.addBodyModelSchema(codegenParameter, name, schema, imports, bodyParameterName, true); + } else { + Schema inner = ModelUtils.getAdditionalProperties(schema); + if (inner == null) { + LOGGER.error("No inner type supplied for map parameter `{}`. Default to type:string", schema.getName()); + inner = new StringSchema().description("//TODO automatically added by openapi-generator"); + schema.setAdditionalProperties(inner); + } + CodegenProperty codegenProperty = fromProperty("property", schema); - imports.add(codegenProperty.baseType); + imports.add(codegenProperty.baseType); - CodegenProperty innerCp = codegenProperty; - while (innerCp != null) { - if (innerCp.complexType != null) { - imports.add(innerCp.complexType); + CodegenProperty innerCp = codegenProperty; + while (innerCp != null) { + if (innerCp.complexType != null) { + imports.add(innerCp.complexType); + } + innerCp = innerCp.items; } - innerCp = innerCp.items; - } - if (StringUtils.isEmpty(bodyParameterName)) { - codegenParameter.baseName = "request_body"; - } else { - codegenParameter.baseName = bodyParameterName; - } - codegenParameter.paramName = toParamName(codegenParameter.baseName); - codegenParameter.items = codegenProperty.items; - codegenParameter.mostInnerItems = codegenProperty.mostInnerItems; - codegenParameter.dataType = getTypeDeclaration(schema); - codegenParameter.baseType = getSchemaType(inner); - codegenParameter.isContainer = Boolean.TRUE; - codegenParameter.isMapContainer = Boolean.TRUE; + if (StringUtils.isEmpty(bodyParameterName)) { + codegenParameter.baseName = "request_body"; + } else { + codegenParameter.baseName = bodyParameterName; + } + codegenParameter.paramName = toParamName(codegenParameter.baseName); + codegenParameter.items = codegenProperty.items; + codegenParameter.mostInnerItems = codegenProperty.mostInnerItems; + codegenParameter.dataType = getTypeDeclaration(schema); + codegenParameter.baseType = getSchemaType(inner); + codegenParameter.isContainer = Boolean.TRUE; + codegenParameter.isMapContainer = Boolean.TRUE; - setParameterBooleanFlagWithCodegenProperty(codegenParameter, codegenProperty); + setParameterBooleanFlagWithCodegenProperty(codegenParameter, codegenProperty); - // set nullable - setParameterNullable(codegenParameter, codegenProperty); + // set nullable + setParameterNullable(codegenParameter, codegenProperty); + } } else if (ModelUtils.isArraySchema(schema)) { - final ArraySchema arraySchema = (ArraySchema) schema; - Schema inner = getSchemaItems(arraySchema); - CodegenProperty codegenProperty = fromProperty("property", arraySchema); - imports.add(codegenProperty.baseType); - CodegenProperty innerCp = codegenProperty; - CodegenProperty mostInnerItem = innerCp; - // loop through multidimensional array to add proper import - // also find the most inner item - while (innerCp != null) { - if (innerCp.complexType != null) { - imports.add(innerCp.complexType); + if (ModelUtils.isGenerateAliasAsModel() && StringUtils.isNotBlank(name)) { + this.addBodyModelSchema(codegenParameter, name, schema, imports, bodyParameterName, true); + } else { + final ArraySchema arraySchema = (ArraySchema) schema; + Schema inner = getSchemaItems(arraySchema); + CodegenProperty codegenProperty = fromProperty("property", arraySchema); + imports.add(codegenProperty.baseType); + CodegenProperty innerCp = codegenProperty; + CodegenProperty mostInnerItem = innerCp; + // loop through multidimensional array to add proper import + // also find the most inner item + while (innerCp != null) { + if (innerCp.complexType != null) { + imports.add(innerCp.complexType); + } + mostInnerItem = innerCp; + innerCp = innerCp.items; } - mostInnerItem = innerCp; - innerCp = innerCp.items; - } - if (StringUtils.isEmpty(bodyParameterName)) { - if (StringUtils.isEmpty(mostInnerItem.complexType)) { - codegenParameter.baseName = "request_body"; + if (StringUtils.isEmpty(bodyParameterName)) { + if (StringUtils.isEmpty(mostInnerItem.complexType)) { + codegenParameter.baseName = "request_body"; + } else { + codegenParameter.baseName = mostInnerItem.complexType; + } } else { - codegenParameter.baseName = mostInnerItem.complexType; + codegenParameter.baseName = bodyParameterName; } - } else { - codegenParameter.baseName = bodyParameterName; - } - codegenParameter.paramName = toArrayModelParamName(codegenParameter.baseName); - codegenParameter.items = codegenProperty.items; - codegenParameter.mostInnerItems = codegenProperty.mostInnerItems; - codegenParameter.dataType = getTypeDeclaration(arraySchema); - codegenParameter.baseType = getSchemaType(inner); - codegenParameter.isContainer = Boolean.TRUE; - codegenParameter.isListContainer = Boolean.TRUE; + codegenParameter.paramName = toArrayModelParamName(codegenParameter.baseName); + codegenParameter.items = codegenProperty.items; + codegenParameter.mostInnerItems = codegenProperty.mostInnerItems; + codegenParameter.dataType = getTypeDeclaration(arraySchema); + codegenParameter.baseType = getSchemaType(inner); + codegenParameter.isContainer = Boolean.TRUE; + codegenParameter.isListContainer = Boolean.TRUE; - setParameterBooleanFlagWithCodegenProperty(codegenParameter, codegenProperty); - // set nullable - setParameterNullable(codegenParameter, codegenProperty); + setParameterBooleanFlagWithCodegenProperty(codegenParameter, codegenProperty); + // set nullable + setParameterNullable(codegenParameter, codegenProperty); - while (codegenProperty != null) { - imports.add(codegenProperty.baseType); - codegenProperty = codegenProperty.items; + while (codegenProperty != null) { + imports.add(codegenProperty.baseType); + codegenProperty = codegenProperty.items; + } } - } else if (ModelUtils.isFreeFormObject(schema)) { // HTTP request body is free form object CodegenProperty codegenProperty = fromProperty("FREE_FORM_REQUEST_BODY", schema); @@ -5406,81 +5811,7 @@ public CodegenParameter fromRequestBody(RequestBody body, Set imports, S setParameterNullable(codegenParameter, codegenProperty); } else if (ModelUtils.isObjectSchema(schema) || ModelUtils.isComposedSchema(schema)) { - CodegenModel codegenModel = null; - if (StringUtils.isNotBlank(name)) { - schema.setName(name); - codegenModel = fromModel(name, schema); - } - if (codegenModel != null) { - codegenParameter.isModel = true; - } - - if (codegenModel != null && !codegenModel.emptyVars) { - if (StringUtils.isEmpty(bodyParameterName)) { - codegenParameter.baseName = codegenModel.classname; - } else { - codegenParameter.baseName = bodyParameterName; - } - codegenParameter.paramName = toParamName(codegenParameter.baseName); - codegenParameter.baseType = codegenModel.classname; - codegenParameter.dataType = getTypeDeclaration(codegenModel.classname); - codegenParameter.description = codegenModel.description; - imports.add(codegenParameter.baseType); - } else { - CodegenProperty codegenProperty = fromProperty("property", schema); - - if (codegenProperty != null && codegenProperty.getComplexType() != null && codegenProperty.getComplexType().contains(" | ")) { - List parts = Arrays.asList(codegenProperty.getComplexType().split(" \\| ")); - imports.addAll(parts); - String codegenModelName = codegenProperty.getComplexType(); - codegenParameter.baseName = codegenModelName; - codegenParameter.paramName = toParamName(codegenParameter.baseName); - codegenParameter.baseType = codegenParameter.baseName; - codegenParameter.dataType = getTypeDeclaration(codegenModelName); - codegenParameter.description = codegenProperty.getDescription(); - } else { - if (ModelUtils.getAdditionalProperties(schema) != null) {// http body is map - LOGGER.error("Map should be supported. Please report to openapi-generator github repo about the issue."); - } else if (codegenProperty != null) { - String codegenModelName, codegenModelDescription; - - if (codegenModel != null) { - codegenModelName = codegenModel.classname; - codegenModelDescription = codegenModel.description; - } else { - LOGGER.warn("The following schema has undefined (null) baseType. " + - "It could be due to form parameter defined in OpenAPI v2 spec with incorrect consumes. " + - "A correct 'consumes' for form parameters should be " + - "'application/x-www-form-urlencoded' or 'multipart/?'"); - LOGGER.warn("schema: " + schema); - LOGGER.warn("codegenModel is null. Default to UNKNOWN_BASE_TYPE"); - codegenModelName = "UNKNOWN_BASE_TYPE"; - codegenModelDescription = "UNKNOWN_DESCRIPTION"; - } - - if (StringUtils.isEmpty(bodyParameterName)) { - codegenParameter.baseName = codegenModelName; - } else { - codegenParameter.baseName = bodyParameterName; - } - - codegenParameter.paramName = toParamName(codegenParameter.baseName); - codegenParameter.baseType = codegenModelName; - codegenParameter.dataType = getTypeDeclaration(codegenModelName); - codegenParameter.description = codegenModelDescription; - imports.add(codegenParameter.baseType); - - if (codegenProperty.complexType != null) { - imports.add(codegenProperty.complexType); - } - } - } - - setParameterBooleanFlagWithCodegenProperty(codegenParameter, codegenProperty); - // set nullable - setParameterNullable(codegenParameter, codegenProperty); - } - + this.addBodyModelSchema(codegenParameter, name, schema, imports, bodyParameterName, false); } else { // HTTP request body is primitive type (e.g. integer, string, etc) CodegenProperty codegenProperty = fromProperty("PRIMITIVE_REQUEST_BODY", schema); @@ -5513,6 +5844,8 @@ public CodegenParameter fromRequestBody(RequestBody body, Set imports, S setParameterNullable(codegenParameter, codegenProperty); } + addJsonSchemaForBodyRequestInCaseItsNotPresent(codegenParameter, body); + // set the parameter's example value // should be overridden by lang codegen setParameterExampleValue(codegenParameter, body); @@ -5520,6 +5853,11 @@ public CodegenParameter fromRequestBody(RequestBody body, Set imports, S return codegenParameter; } + private void addJsonSchemaForBodyRequestInCaseItsNotPresent(CodegenParameter codegenParameter, RequestBody body) { + if (codegenParameter.jsonSchema == null) + codegenParameter.jsonSchema = Json.pretty(body); + } + protected void addOption(String key, String description, String defaultValue) { CliOption option = new CliOption(key, description); if (defaultValue != null) @@ -5745,30 +6083,37 @@ public void setRemoveEnumValuePrefix(final boolean removeEnumValuePrefix) { } //// Following methods are related to the "useOneOfInterfaces" feature + /** - * Add "x-oneOf-name" extension to a given oneOf schema (assuming it has at least 1 oneOf elements) - * @param s schema to add the extension to + * Add "x-one-of-name" extension to a given oneOf schema (assuming it has at least 1 oneOf elements) + * + * @param s schema to add the extension to * @param name name of the parent oneOf schema */ public void addOneOfNameExtension(ComposedSchema s, String name) { if (s.getOneOf() != null && s.getOneOf().size() > 0) { - s.addExtension("x-oneOf-name", name); + s.addExtension("x-one-of-name", name); } } /** * Add a given ComposedSchema as an interface model to be generated, assuming it has `oneOf` defined - * @param cs ComposedSchema object to create as interface model - * @param type name to use for the generated interface model + * + * @param cs ComposedSchema object to create as interface model + * @param type name to use for the generated interface model + * @param openAPI OpenAPI spec that we are using */ - public void addOneOfInterfaceModel(ComposedSchema cs, String type) { + public void addOneOfInterfaceModel(ComposedSchema cs, String type, OpenAPI openAPI) { if (cs.getOneOf() == null) { return; } - CodegenModel cm = new CodegenModel(); - cm.discriminator = createDiscriminator("", (Schema) cs); + CodegenModel cm = new CodegenModel(); + cm.discriminator = createDiscriminator("", (Schema) cs, openAPI); + if (!this.getLegacyDiscriminatorBehavior()) { + cm.addDiscriminatorMappedModelsImports(); + } for (Schema o : Optional.ofNullable(cs.getOneOf()).orElse(Collections.emptyList())) { if (o.get$ref() == null) { if (cm.discriminator != null && o.get$ref() == null) { @@ -5790,7 +6135,8 @@ public void addOneOfInterfaceModel(ComposedSchema cs, String type) { addOneOfInterfaces.add(cm); } - public void addImportsToOneOfInterface(List> imports) {} + public void addImportsToOneOfInterface(List> imports) { + } //// End of methods related to the "useOneOfInterfaces" feature protected void modifyFeatureSet(Consumer processor) { diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/DefaultGenerator.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/DefaultGenerator.java index e8dab26d05f9..1681434c4424 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/DefaultGenerator.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/DefaultGenerator.java @@ -156,7 +156,7 @@ private Boolean getGeneratorPropertyDefaultSwitch(final String key, final Boolea return defaultValue; } - private void configureGeneratorProperties() { + void configureGeneratorProperties() { // allows generating only models by specifying a CSV of models to generate, or empty for all // NOTE: Boolean.TRUE is required below rather than `true` because of JVM boxing constraints and type inference. generateApis = GlobalSettings.getProperty(CodegenConstants.APIS) != null ? Boolean.TRUE : getGeneratorPropertyDefaultSwitch(CodegenConstants.APIS, null); @@ -394,7 +394,7 @@ private void generateModel(List files, Map models, String } @SuppressWarnings("unchecked") - private void generateModels(List files, List allModels, List unusedModels) { + void generateModels(List files, List allModels, List unusedModels) { if (!generateModels) { // TODO: Process these anyway and add to dryRun info LOGGER.info("Skipping generation of models."); diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/InlineModelResolver.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/InlineModelResolver.java index 32f6023d6951..c1f26c8ad771 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/InlineModelResolver.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/InlineModelResolver.java @@ -332,11 +332,11 @@ private void flattenResponses(OpenAPI openAPI, String pathname, Operation operat * Flattens properties of inline object schemas that belong to a composed schema into a * single flat list of properties. This is useful to generate a single or multiple * inheritance model. - * + * * In the example below, codegen may generate a 'Dog' class that extends from the * generated 'Animal' class. 'Dog' has additional properties 'name', 'age' and 'breed' that * are flattened as a single list of properties. - * + * * Dog: * allOf: * - $ref: '#/components/schemas/Animal' @@ -350,7 +350,7 @@ private void flattenResponses(OpenAPI openAPI, String pathname, Operation operat * properties: * breed: * type: string - * + * * @param openAPI the OpenAPI document * @param key a unique name ofr the composed schema. * @param children the list of nested schemas within a composed schema (allOf, anyOf, oneOf). @@ -362,8 +362,10 @@ private void flattenComposedChildren(OpenAPI openAPI, String key, List c ListIterator listIterator = children.listIterator(); while (listIterator.hasNext()) { Schema component = listIterator.next(); - if (component instanceof ObjectSchema) { - ObjectSchema op = (ObjectSchema) component; + if (component instanceof ObjectSchema || // for inline schema with type:object + (component != null && component.getProperties() != null && + !component.getProperties().isEmpty())) { // for inline schema without type:object + Schema op = component; if (op.get$ref() == null && op.getProperties() != null && op.getProperties().size() > 0) { // If a `title` attribute is defined in the inline schema, codegen uses it to name the // inline schema. Otherwise, we'll use the default naming such as InlineObject1, etc. @@ -390,6 +392,8 @@ private void flattenComposedChildren(OpenAPI openAPI, String key, List c listIterator.set(schema); } } + } else { + // likely a reference to schema (not inline schema) } } } @@ -465,7 +469,7 @@ private void fixStringModel(Schema m) { * with underscores * * e.g. io.schema.User_name => io_schema_User_name - * + * * @param title String title field in the schema if present * @param key String model name * @@ -607,7 +611,7 @@ private void flattenProperties(Map properties, String path) { } } - private Schema modelFromProperty(ObjectSchema object, String path) { + private Schema modelFromProperty(Schema object, String path) { String description = object.getDescription(); String example = null; Object obj = object.getExample(); diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/config/CodegenConfigurator.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/config/CodegenConfigurator.java index b2ad527e2f04..840790ed4c8d 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/config/CodegenConfigurator.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/config/CodegenConfigurator.java @@ -79,67 +79,72 @@ public CodegenConfigurator() { public static CodegenConfigurator fromFile(String configFile, Module... modules) { if (isNotEmpty(configFile)) { - ObjectMapper mapper; + DynamicSettings settings = readDynamicSettings(configFile, modules); - if (FilenameUtils.isExtension(configFile, new String[]{"yml", "yaml"})) { - mapper = Yaml.mapper(); - } else { - mapper = Json.mapper(); - } + CodegenConfigurator configurator = new CodegenConfigurator(); - if (modules != null && modules.length > 0) { - mapper.registerModules(modules); + GeneratorSettings generatorSettings = settings.getGeneratorSettings(); + WorkflowSettings workflowSettings = settings.getWorkflowSettings(); + + // We copy "cached" properties into configurator so it is appropriately configured with all settings in external files. + // FIXME: target is to eventually move away from CodegenConfigurator properties except gen/workflow settings. + configurator.generatorName = generatorSettings.getGeneratorName(); + configurator.inputSpec = workflowSettings.getInputSpec(); + configurator.templatingEngineName = workflowSettings.getTemplatingEngineName(); + if (workflowSettings.getSystemProperties() != null) { + configurator.systemProperties.putAll(workflowSettings.getSystemProperties()); + } + if(generatorSettings.getInstantiationTypes() != null) { + configurator.instantiationTypes.putAll(generatorSettings.getInstantiationTypes()); + } + if(generatorSettings.getTypeMappings() != null) { + configurator.typeMappings.putAll(generatorSettings.getTypeMappings()); + } + if(generatorSettings.getAdditionalProperties() != null) { + configurator.additionalProperties.putAll(generatorSettings.getAdditionalProperties()); + } + if(generatorSettings.getImportMappings() != null) { + configurator.importMappings.putAll(generatorSettings.getImportMappings()); + } + if(generatorSettings.getLanguageSpecificPrimitives() != null) { + configurator.languageSpecificPrimitives.addAll(generatorSettings.getLanguageSpecificPrimitives()); + } + if(generatorSettings.getReservedWordMappings() != null) { + configurator.reservedWordMappings.putAll(generatorSettings.getReservedWordMappings()); + } + if(generatorSettings.getServerVariables() != null) { + configurator.serverVariables.putAll(generatorSettings.getServerVariables()); } - mapper.registerModule(new GuavaModule()); + configurator.generatorSettingsBuilder = GeneratorSettings.newBuilder(generatorSettings); + configurator.workflowSettingsBuilder = WorkflowSettings.newBuilder(workflowSettings); - try { - DynamicSettings settings = mapper.readValue(new File(configFile), DynamicSettings.class); - CodegenConfigurator configurator = new CodegenConfigurator(); + return configurator; + } + return null; + } - GeneratorSettings generatorSettings = settings.getGeneratorSettings(); - WorkflowSettings workflowSettings = settings.getWorkflowSettings(); + private static DynamicSettings readDynamicSettings(String configFile, Module... modules) { + ObjectMapper mapper; - // We copy "cached" properties into configurator so it is appropriately configured with all settings in external files. - // FIXME: target is to eventually move away from CodegenConfigurator properties except gen/workflow settings. - configurator.generatorName = generatorSettings.getGeneratorName(); - configurator.inputSpec = workflowSettings.getInputSpec(); - configurator.templatingEngineName = workflowSettings.getTemplatingEngineName(); - if (workflowSettings.getSystemProperties() != null) { - configurator.systemProperties.putAll(workflowSettings.getSystemProperties()); - } - if(generatorSettings.getInstantiationTypes() != null) { - configurator.instantiationTypes.putAll(generatorSettings.getInstantiationTypes()); - } - if(generatorSettings.getTypeMappings() != null) { - configurator.typeMappings.putAll(generatorSettings.getTypeMappings()); - } - if(generatorSettings.getAdditionalProperties() != null) { - configurator.additionalProperties.putAll(generatorSettings.getAdditionalProperties()); - } - if(generatorSettings.getImportMappings() != null) { - configurator.importMappings.putAll(generatorSettings.getImportMappings()); - } - if(generatorSettings.getLanguageSpecificPrimitives() != null) { - configurator.languageSpecificPrimitives.addAll(generatorSettings.getLanguageSpecificPrimitives()); - } - if(generatorSettings.getReservedWordMappings() != null) { - configurator.reservedWordMappings.putAll(generatorSettings.getReservedWordMappings()); - } - if(generatorSettings.getServerVariables() != null) { - configurator.serverVariables.putAll(generatorSettings.getServerVariables()); - } + if (FilenameUtils.isExtension(configFile.toLowerCase(Locale.ROOT), new String[]{"yml", "yaml"})) { + mapper = Yaml.mapper().copy(); + } else { + mapper = Json.mapper().copy(); + } + + if (modules != null && modules.length > 0) { + mapper.registerModules(modules); + } - configurator.generatorSettingsBuilder = GeneratorSettings.newBuilder(generatorSettings); - configurator.workflowSettingsBuilder = WorkflowSettings.newBuilder(workflowSettings); + mapper.registerModule(new GuavaModule()); - return configurator; - } catch (IOException ex) { - LOGGER.error(ex.getMessage()); - throw new RuntimeException("Unable to deserialize config file: " + configFile); - } + try { + return mapper.readValue(new File(configFile), DynamicSettings.class); + } catch (IOException ex) { + LOGGER.error(ex.getMessage()); + throw new RuntimeException("Unable to deserialize config file: " + configFile); } - return null; } public CodegenConfigurator addServerVariable(String key, String value) { @@ -178,6 +183,7 @@ public CodegenConfigurator addLanguageSpecificPrimitive(String value) { return this; } + // TODO: rename this and other references to "global property" rather than "system property" public CodegenConfigurator addSystemProperty(String key, String value) { this.systemProperties.put(key, value); workflowSettingsBuilder.withSystemProperty(key, value); diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/config/CodegenConfiguratorUtils.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/config/CodegenConfiguratorUtils.java index 3c5b6c919b8f..b3154db6407a 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/config/CodegenConfiguratorUtils.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/config/CodegenConfiguratorUtils.java @@ -42,14 +42,47 @@ */ public final class CodegenConfiguratorUtils { + /** + * Applies "system" properties to the configurator as global properties. + * + * @deprecated + * This method is deprecated due to confusion around the tool's use of system properties. We called these system properties + * in the past and accepted them via CLI option -D. This lead to confusion between true Java System Properties and generator-specific + * "system level properties". They've since been renamed as "Global Properties". Please use {@link CodegenConfiguratorUtils#applyGlobalPropertiesKvpList(List, CodegenConfigurator)}. + * + * @param systemProperties List of properties to be globally available throughout the generator execution. + * @param configurator The {@link CodegenConfigurator} instance to configure. + */ + @Deprecated public static void applySystemPropertiesKvpList(List systemProperties, CodegenConfigurator configurator) { - for(String propString : systemProperties) { - applySystemPropertiesKvp(propString, configurator); + // TODO: Remove in 5.0 + applyGlobalPropertiesKvpList(systemProperties, configurator); + } + + /** + * Applies a key-value pair of strings as "system" properties to the configurator as global properties. + * + * @deprecated + * This method is deprecated due to confusing between Java Sytsem Properties and generator-specific "system-level properties". + * They've since been renamed as "Global Properties". Please use {@link CodegenConfiguratorUtils#applyGlobalPropertiesKvp(String, CodegenConfigurator)}. + * + * @param systemProperties List of properties to be globally available throughout the generator execution. + * @param configurator The {@link CodegenConfigurator} instance to configure. + */ + @Deprecated + public static void applySystemPropertiesKvp(String systemProperties, CodegenConfigurator configurator) { + // TODO: Remove in 5.0 + applyGlobalPropertiesKvp(systemProperties, configurator); + } + + public static void applyGlobalPropertiesKvpList(List globalProperties, CodegenConfigurator configurator) { + for(String propString : globalProperties) { + applyGlobalPropertiesKvp(propString, configurator); } } - public static void applySystemPropertiesKvp(String systemProperties, CodegenConfigurator configurator) { - final Map map = createMapFromKeyValuePairs(systemProperties); + public static void applyGlobalPropertiesKvp(String globalProperties, CodegenConfigurator configurator) { + final Map map = createMapFromKeyValuePairs(globalProperties); for (Map.Entry entry : map.entrySet()) { configurator.addSystemProperty(entry.getKey(), entry.getValue()); } diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AbstractCSharpCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AbstractCSharpCodegen.java index 2a0b97066b49..a3411f68a2a4 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AbstractCSharpCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AbstractCSharpCodegen.java @@ -470,6 +470,32 @@ private void postProcessEnumRefs(final Map models) { var.isPrimitiveType = true; } } + for (CodegenProperty var : model.readWriteVars) { + if (enumRefs.containsKey(var.dataType)) { + // Handle any enum properties referred to by $ref. + // This is different in C# than most other generators, because enums in C# are compiled to integral types, + // while enums in many other languages are true objects. + CodegenModel refModel = enumRefs.get(var.dataType); + var.allowableValues = refModel.allowableValues; + var.isEnum = true; + + // We do these after updateCodegenPropertyEnum to avoid generalities that don't mesh with C#. + var.isPrimitiveType = true; + } + } + for (CodegenProperty var : model.readOnlyVars) { + if (enumRefs.containsKey(var.dataType)) { + // Handle any enum properties referred to by $ref. + // This is different in C# than most other generators, because enums in C# are compiled to integral types, + // while enums in many other languages are true objects. + CodegenModel refModel = enumRefs.get(var.dataType); + var.allowableValues = refModel.allowableValues; + var.isEnum = true; + + // We do these after updateCodegenPropertyEnum to avoid generalities that don't mesh with C#. + var.isPrimitiveType = true; + } + } // We're looping all models here. if (model.isEnum) { diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AbstractGoCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AbstractGoCodegen.java index d4c0a8514e6e..b018d22707a6 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AbstractGoCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AbstractGoCodegen.java @@ -130,6 +130,7 @@ public AbstractGoCodegen() { // See issue #5387 for more details. typeMapping.put("object", "map[string]interface{}"); typeMapping.put("interface{}", "interface{}"); + typeMapping.put("AnyType", "interface{}"); numberTypes = new HashSet( Arrays.asList( diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AbstractJavaCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AbstractJavaCodegen.java index e93197b37f46..c516814b8dfa 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AbstractJavaCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AbstractJavaCodegen.java @@ -59,6 +59,7 @@ public abstract class AbstractJavaCodegen extends DefaultCodegen implements Code public static final String DISABLE_HTML_ESCAPING = "disableHtmlEscaping"; public static final String BOOLEAN_GETTER_PREFIX = "booleanGetterPrefix"; public static final String ADDITIONAL_MODEL_TYPE_ANNOTATIONS = "additionalModelTypeAnnotations"; + public static final String DISCRIMINATOR_CASE_SENSITIVE = "discriminatorCaseSensitive"; protected String dateLibrary = "threetenbp"; protected boolean supportAsync = false; @@ -81,9 +82,10 @@ public abstract class AbstractJavaCodegen extends DefaultCodegen implements Code protected String licenseUrl = "http://unlicense.org"; protected String projectFolder = "src/main"; protected String projectTestFolder = "src/test"; - protected String sourceFolder = projectFolder + "/java"; + protected String sourceFolder = projectFolder + File.separator +"java"; protected String testFolder = projectTestFolder + "/java"; protected boolean fullJavaUtil; + protected boolean discriminatorCaseSensitive = true; // True if the discriminator value lookup should be case-sensitive. protected String javaUtilPrefix = ""; protected Boolean serializableModel = false; protected boolean serializeBigDecimalAsString = false; @@ -189,6 +191,7 @@ public AbstractJavaCodegen() { cliOptions.add(CliOption.newBoolean(CodegenConstants.SERIALIZABLE_MODEL, CodegenConstants.SERIALIZABLE_MODEL_DESC, this.getSerializableModel())); cliOptions.add(CliOption.newBoolean(CodegenConstants.SERIALIZE_BIG_DECIMAL_AS_STRING, CodegenConstants.SERIALIZE_BIG_DECIMAL_AS_STRING_DESC, serializeBigDecimalAsString)); cliOptions.add(CliOption.newBoolean(FULL_JAVA_UTIL, "whether to use fully qualified name for classes under java.util. This option only works for Java API client", fullJavaUtil)); + cliOptions.add(CliOption.newBoolean(DISCRIMINATOR_CASE_SENSITIVE, "Whether the discriminator value lookup should be case-sensitive or not. This option only works for Java API client", discriminatorCaseSensitive)); cliOptions.add(CliOption.newBoolean(CodegenConstants.HIDE_GENERATION_TIMESTAMP, CodegenConstants.HIDE_GENERATION_TIMESTAMP_DESC, this.isHideGenerationTimestamp())); cliOptions.add(CliOption.newBoolean(WITH_XML, "whether to include support for application/xml content type and include XML annotations in the model (works with libraries that provide support for JSON and XML)")); @@ -385,6 +388,15 @@ public void processOpts() { if (additionalProperties.containsKey(FULL_JAVA_UTIL)) { this.setFullJavaUtil(Boolean.valueOf(additionalProperties.get(FULL_JAVA_UTIL).toString())); } + if (additionalProperties.containsKey(DISCRIMINATOR_CASE_SENSITIVE)) { + this.setDiscriminatorCaseSensitive(Boolean.valueOf(additionalProperties.get(DISCRIMINATOR_CASE_SENSITIVE).toString())); + } else { + // By default, the discriminator lookup should be case sensitive. There is nothing in the OpenAPI specification + // that indicates the lookup should be case insensitive. However, some implementations perform + // a case-insensitive lookup. + this.setDiscriminatorCaseSensitive(Boolean.TRUE); + } + additionalProperties.put(DISCRIMINATOR_CASE_SENSITIVE, this.discriminatorCaseSensitive); if (fullJavaUtil) { javaUtilPrefix = "java.util."; @@ -1431,6 +1443,15 @@ public void setFullJavaUtil(boolean fullJavaUtil) { this.fullJavaUtil = fullJavaUtil; } + /** + * Set whether discriminator value lookup is case-sensitive or not. + * + * @param discriminatorCaseSensitive true if the discriminator value lookup should be case sensitive. + */ + public void setDiscriminatorCaseSensitive(boolean discriminatorCaseSensitive) { + this.discriminatorCaseSensitive = discriminatorCaseSensitive; + } + public void setWithXml(boolean withXml) { this.withXml = withXml; } diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AbstractKotlinCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AbstractKotlinCodegen.java index aa4015303392..bc582f756160 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AbstractKotlinCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AbstractKotlinCodegen.java @@ -940,7 +940,7 @@ public String toDefaultValue(Schema p) { } } else if (ModelUtils.isStringSchema(p)) { if (p.getDefault() != null) { - return "'" + p.getDefault() + "'"; + return "\"" + p.getDefault() + "\""; } } diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/CLibcurlClientCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/CLibcurlClientCodegen.java index a5bab8b9c628..c059ff91397d 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/CLibcurlClientCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/CLibcurlClientCodegen.java @@ -87,7 +87,7 @@ public CLibcurlClientCodegen() { embeddedTemplateDir = templateDir = "C-libcurl"; // TODO add auto-generated test files - //modelTestTemplateFiles.put("model_test.mustache", ".c"); + modelTestTemplateFiles.put("model_test.mustache", ".c"); //apiTestTemplateFiles.put("api_test.mustache", ".c"); // default HIDE_GENERATION_TIMESTAMP to true @@ -223,10 +223,12 @@ public void processOpts() { supportingFiles.add(new SupportingFile("apiClient.c.mustache", "src", "apiClient.c")); supportingFiles.add(new SupportingFile("apiKey.c.mustache", "src", "apiKey.c")); supportingFiles.add(new SupportingFile("list.c.mustache", "src", "list.c")); + supportingFiles.add(new SupportingFile("binary.c.mustache", "src", "binary.c")); // include folder supportingFiles.add(new SupportingFile("apiClient.h.mustache", "include", "apiClient.h")); supportingFiles.add(new SupportingFile("keyValuePair.h.mustache", "include", "keyValuePair.h")); supportingFiles.add(new SupportingFile("list.h.mustache", "include", "list.h")); + supportingFiles.add(new SupportingFile("binary.h.mustache", "include", "binary.h")); // external folder supportingFiles.add(new SupportingFile("cJSON.licence.mustache", "external", "cJSON.licence")); supportingFiles.add(new SupportingFile("cJSON.c.mustache", "external", "cJSON.c")); @@ -321,6 +323,104 @@ public String toDefaultValue(Schema p) { return null; } + @Override + public String toExampleValue(Schema schema) { + String example = super.toExampleValue(schema); + + if (ModelUtils.isNullType(schema) && null != example) { + // The 'null' type is allowed in OAS 3.1 and above. It is not supported by OAS 3.0.x, + // though this tooling supports it. + return "NULL"; + } + // correct "'"s into "'"s after toString() + if (ModelUtils.isStringSchema(schema) && schema.getDefault() != null) { + example = (String) schema.getDefault(); + } + if (StringUtils.isNotBlank(example) && !"null".equals(example)) { + if (ModelUtils.isStringSchema(schema)) { + example = "\"" + example + "\""; + } + return example; + } + + if (schema.getEnum() != null && !schema.getEnum().isEmpty()) { + // Enum case: + example = schema.getEnum().get(0).toString(); +/* if (ModelUtils.isStringSchema(schema)) { + example = "'" + escapeText(example) + "'"; + }*/ + if (null == example) + LOGGER.warn("Empty enum. Cannot built an example!"); + + return example; + } else if (null != schema.get$ref()) { + // $ref case: + Map allDefinitions = ModelUtils.getSchemas(this.openAPI); + String ref = ModelUtils.getSimpleRef(schema.get$ref()); + if (allDefinitions != null) { + Schema refSchema = allDefinitions.get(ref); + if (null == refSchema) { + return "None"; + } else { + String refTitle = refSchema.getTitle(); + if (StringUtils.isBlank(refTitle) || "null".equals(refTitle)) { + refSchema.setTitle(ref); + } + return toExampleValue(refSchema); + } + } else { + LOGGER.warn("allDefinitions not defined in toExampleValue!\n"); + } + } + if (ModelUtils.isDateSchema(schema)) { + example = "\"2013-10-20\""; + return example; + } else if (ModelUtils.isDateTimeSchema(schema)) { + example = "\"2013-10-20T19:20:30+01:00\""; + return example; + } else if (ModelUtils.isBinarySchema(schema)) { + example = "instantiate_binary_t(\"blah\", 5)"; + return example; + } else if (ModelUtils.isByteArraySchema(schema)) { + example = "YQ=="; + } else if (ModelUtils.isStringSchema(schema)) { + // a BigDecimal: + if ("Number".equalsIgnoreCase(schema.getFormat())) {return "1";} + if (StringUtils.isNotBlank(schema.getPattern())) return "\"a\""; // I cheat here, since it would be too complicated to generate a string from a regexp + int len = 0; + if (null != schema.getMinLength()) len = schema.getMinLength().intValue(); + if (len < 1) len = 1; + example = ""; + for (int i=0;i() .put(NET35, ".NET Framework 3.5 compatible") .put(NET40, ".NET Framework 4.0 compatible") - .put(NET45, ".NET Framework 4.5+ compatible") + .put(NET45, ".NET Framework 4.5 compatible") + .put(NET452, ".NET Framework 4.5.2+ compatible") .put(NETSTANDARD, ".NET Standard 1.3 compatible (DEPRECATED. Please use `csharp-netcore` generator instead)") .put(UWP, "Universal Windows Platform (DEPRECATED. Please use `csharp-netcore` generator instead)") .build(); @@ -328,8 +336,6 @@ public void processOpts() { setSupportsUWP(Boolean.TRUE); } else if (NET40.equals(this.targetFramework)) { additionalProperties.put(MCS_NET_VERSION_KEY, "4"); - additionalProperties.put("isNet40", true); - if (additionalProperties.containsKey(CodegenConstants.SUPPORTS_ASYNC)) { LOGGER.warn(".NET " + NET40 + " generator does not support async."); additionalProperties.remove(CodegenConstants.SUPPORTS_ASYNC); @@ -337,6 +343,10 @@ public void processOpts() { setTargetFrameworkNuget("net40"); setSupportsAsync(Boolean.FALSE); + } else if (NET452.equals(this.targetFramework)) { + additionalProperties.put(MCS_NET_VERSION_KEY, "4.5.2-api"); + setTargetFrameworkNuget("net452"); + setSupportsAsync(Boolean.TRUE); } else { additionalProperties.put(MCS_NET_VERSION_KEY, "4.5.2-api"); setTargetFrameworkNuget("net45"); @@ -651,6 +661,14 @@ public void postProcessParameter(CodegenParameter parameter) { postProcessPattern(parameter.pattern, parameter.vendorExtensions); postProcessEmitDefaultValue(parameter.vendorExtensions); super.postProcessParameter(parameter); + + if (nullableType.contains(parameter.dataType)) { + if (!parameter.required) { //optional + parameter.dataType = parameter.dataType + "?"; + } else { + parameter.vendorExtensions.put("x-csharp-value-type", true); + } + } } @Override @@ -658,6 +676,10 @@ public void postProcessModelProperty(CodegenModel model, CodegenProperty propert postProcessPattern(property.pattern, property.vendorExtensions); postProcessEmitDefaultValue(property.vendorExtensions); super.postProcessModelProperty(model, property); + + if (!property.isContainer && (nullableType.contains(property.dataType) || property.isEnum)) { + property.vendorExtensions.put("x-csharp-value-type", true); + } } /* @@ -706,6 +728,46 @@ public void setTargetFramework(String dotnetFramework) { } else { this.targetFramework = dotnetFramework; } + switch (targetFramework) { + case NET35: + additionalProperties.put(RESTSHARP, new LibraryDependency("105.1.0", "net35")); + additionalProperties.put(JSON_SUBTYPES, new LibraryDependency("1.6.0", "net35")); + additionalProperties.put(NEWTONSOFT_JSON, new LibraryDependency("12.0.3", "net35")); + additionalProperties.put(NUNIT, new LibraryDependency("3.11.0", "net35")); + break; + case NET40: + additionalProperties.put(RESTSHARP, new LibraryDependency("105.1.0", "net4")); + additionalProperties.put(JSON_SUBTYPES, new LibraryDependency("1.6.0", "net40")); + additionalProperties.put(NEWTONSOFT_JSON, new LibraryDependency("12.0.3", "net40")); + additionalProperties.put(NUNIT, new LibraryDependency("3.11.0", "net40")); + break; + case NET45: + additionalProperties.put(RESTSHARP, new LibraryDependency("105.1.0", "net45")); + additionalProperties.put(JSON_SUBTYPES, new LibraryDependency("1.6.0", "net45")); + additionalProperties.put(NEWTONSOFT_JSON, new LibraryDependency("12.0.3", "net45")); + additionalProperties.put(NUNIT, new LibraryDependency("3.11.0", "net45")); + break; + case NET452: + additionalProperties.put(RESTSHARP, new LibraryDependency("106.10.1", "net452")); + additionalProperties.put(JSON_SUBTYPES, new LibraryDependency("1.6.0", "net45")); + additionalProperties.put(NEWTONSOFT_JSON, new LibraryDependency("12.0.3", "net45")); + additionalProperties.put(NUNIT, new LibraryDependency("3.11.0", "net45")); + additionalProperties.put("isRestSharp_106_10_1_above", true); + break; + case UWP: + additionalProperties.put(RESTSHARP, new LibraryDependency("105.1.0", "uwp")); + additionalProperties.put(JSON_SUBTYPES, new LibraryDependency("1.6.0", "uwp")); + additionalProperties.put(NEWTONSOFT_JSON, new LibraryDependency("12.0.3", "uwp")); + additionalProperties.put(NUNIT, new LibraryDependency("3.11.0", "uwp")); + break; + case NETSTANDARD: + additionalProperties.put(RESTSHARP, new LibraryDependency("105.1.0", "netstandard1.3")); + additionalProperties.put(JSON_SUBTYPES, new LibraryDependency("1.6.0", "netstandard1.3")); + additionalProperties.put(NEWTONSOFT_JSON, new LibraryDependency("12.0.3", "netstandard1.3")); + additionalProperties.put(NUNIT, new LibraryDependency("3.11.0", "netstandard1.3")); + break; + } + LOGGER.info("Generating code for .NET Framework " + this.targetFramework); } @@ -854,6 +916,10 @@ public void setNetStandard(Boolean netStandard) { public void setGeneratePropertyChanged(final Boolean generatePropertyChanged) { this.generatePropertyChanged = generatePropertyChanged; + if (this.generatePropertyChanged) { + additionalProperties.put(FODY, new LibraryDependency("1.29.4", targetFrameworkNuget)); + additionalProperties.put(PROPERTYCHANGED_FODY, new LibraryDependency("1.51.3", targetFrameworkNuget)); + } } public void setUseCompareNetObjects(final Boolean useCompareNetObjects) { @@ -945,3 +1011,13 @@ public String getNullableType(Schema p, String type) { } } + +class LibraryDependency { + String version; + String targetFramework; + + public LibraryDependency(String version, String targetFramework) { + this.version = version; + this.targetFramework = targetFramework; + } +} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/DartClientCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/DartClientCodegen.java index 4e966fc43cbd..ae1a2e8fbb06 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/DartClientCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/DartClientCodegen.java @@ -19,6 +19,7 @@ import io.swagger.v3.oas.models.media.ArraySchema; import io.swagger.v3.oas.models.media.Schema; + import org.apache.commons.io.FilenameUtils; import org.apache.commons.lang3.StringUtils; import org.openapitools.codegen.*; @@ -279,6 +280,7 @@ public void processOpts() { final String authFolder = sourceFolder + File.separator + "lib" + File.separator + "auth"; supportingFiles.add(new SupportingFile("auth/authentication.mustache", authFolder, "authentication.dart")); supportingFiles.add(new SupportingFile("auth/http_basic_auth.mustache", authFolder, "http_basic_auth.dart")); + supportingFiles.add(new SupportingFile("auth/http_bearer_auth.mustache", authFolder, "http_bearer_auth.dart")); supportingFiles.add(new SupportingFile("auth/api_key_auth.mustache", authFolder, "api_key_auth.dart")); supportingFiles.add(new SupportingFile("auth/oauth.mustache", authFolder, "oauth.dart")); supportingFiles.add(new SupportingFile("git_push.sh.mustache", "", "git_push.sh")); @@ -366,9 +368,12 @@ public String toModelName(String name) { name = "model_" + name; // e.g. 200Response => Model200Response (after camelize) } - // camelize the model name - // phone_number => PhoneNumber - return camelize(name); + if (typeMapping.containsValue(name)) { + return camelize(name); + } else { + // camelize the model name + return camelize(modelNamePrefix + "_" + name + "_" + modelNameSuffix); + } } @Override @@ -376,6 +381,10 @@ public String toModelFilename(String name) { return underscore(toModelName(name)); } + @Override public String toModelDocFilename(String name) { + return super.toModelDocFilename(toModelName(name)); + } + @Override public String toApiFilename(String name) { return underscore(toApiName(name)); diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/GoClientExperimentalCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/GoClientExperimentalCodegen.java index 56c63ec0c630..0bea07e4dba7 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/GoClientExperimentalCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/GoClientExperimentalCodegen.java @@ -18,10 +18,8 @@ import io.swagger.v3.oas.models.media.Schema; import io.swagger.v3.oas.models.security.SecurityScheme; -import org.openapitools.codegen.CodegenModel; -import org.openapitools.codegen.CodegenProperty; -import org.openapitools.codegen.CodegenSecurity; -import org.openapitools.codegen.SupportingFile; +import org.apache.commons.lang3.StringUtils; +import org.openapitools.codegen.*; import org.openapitools.codegen.meta.GeneratorMetadata; import org.openapitools.codegen.meta.Stability; import org.openapitools.codegen.utils.ModelUtils; @@ -36,6 +34,7 @@ public class GoClientExperimentalCodegen extends GoClientCodegen { private static final Logger LOGGER = LoggerFactory.getLogger(GoClientExperimentalCodegen.class); + protected String goImportAlias = "openapiclient"; public GoClientExperimentalCodegen() { super(); @@ -77,16 +76,28 @@ public String getHelp() { @Override public void processOpts() { + this.setLegacyDiscriminatorBehavior(false); super.processOpts(); supportingFiles.add(new SupportingFile("utils.mustache", "", "utils.go")); // Generate the 'signing.py' module, but only if the 'HTTP signature' security scheme is specified in the OAS. Map securitySchemeMap = openAPI != null ? - (openAPI.getComponents() != null ? openAPI.getComponents().getSecuritySchemes() : null) : null; + (openAPI.getComponents() != null ? openAPI.getComponents().getSecuritySchemes() : null) : null; List authMethods = fromSecurity(securitySchemeMap); if (ProcessUtils.hasHttpSignatureMethods(authMethods)) { supportingFiles.add(new SupportingFile("signing.mustache", "", "signing.go")); } + + if (additionalProperties.containsKey("goImportAlias")) { + setGoImportAlias(additionalProperties.get("goImportAlias").toString()); + } else { + additionalProperties.put("goImportAlias", goImportAlias); + } + + } + + public void setGoImportAlias(String goImportAlias) { + this.goImportAlias = goImportAlias; } @Override @@ -179,7 +190,7 @@ public Map postProcessModels(Map objs) { param.dataType = "NullableTime"; } else { param.dataType = "Nullable" + Character.toUpperCase(param.dataType.charAt(0)) - + param.dataType.substring(1); + + param.dataType.substring(1); } } } @@ -198,4 +209,151 @@ public void addImportsToOneOfInterface(List> imports) { } } } + + @Override + public Map postProcessOperationsWithModels(Map objs, List allModels) { + objs = super.postProcessOperationsWithModels(objs, allModels); + Map operations = (Map) objs.get("operations"); + HashMap modelMaps = new HashMap(); + HashMap processedModelMaps = new HashMap(); + + for (Object o : allModels) { + HashMap h = (HashMap) o; + CodegenModel m = (CodegenModel) h.get("model"); + modelMaps.put(m.classname, m); + } + + List operationList = (List) operations.get("operation"); + for (CodegenOperation op : operationList) { + for (CodegenParameter p : op.allParams) { + p.vendorExtensions.put("x-go-example", constructExampleCode(p, modelMaps, processedModelMaps)); + } + } + + processedModelMaps.clear(); + for (CodegenOperation operation : operationList) { + for (CodegenParameter cp : operation.allParams) { + cp.vendorExtensions.put("x-go-example", constructExampleCode(cp, modelMaps, processedModelMaps)); + } + } + + return objs; + } + + private String constructExampleCode(CodegenParameter codegenParameter, HashMap modelMaps, HashMap processedModelMap) { + if (codegenParameter.isListContainer) { // array + return codegenParameter.dataType + "{" + constructExampleCode(codegenParameter.items, modelMaps, processedModelMap) + "}"; + } else if (codegenParameter.isMapContainer) { + return "map[string]string{ \"Key\" = \"Value\" }"; + } else if (codegenParameter.isPrimitiveType) { // primitive type + if (codegenParameter.isString) { + if (StringUtils.isEmpty(codegenParameter.example)) { + return "\"" + codegenParameter.example + "\""; + } else { + return "\"" + codegenParameter.paramName + "_example\""; + } + } else if (codegenParameter.isBoolean) { // boolean + if (Boolean.parseBoolean(codegenParameter.example)) { + return "true"; + } else { + return "false"; + } + } else if (codegenParameter.isUri) { // URL + return "URL(string: \"https://example.com\")!"; + } else if (codegenParameter.isDateTime || codegenParameter.isDate) { // datetime or date + return "Get-Date"; + } else{ // numeric + if (StringUtils.isEmpty(codegenParameter.example)) { + return codegenParameter.example; + } else { + return "987"; + } + } + } else { // model + // look up the model + if (modelMaps.containsKey(codegenParameter.dataType)) { + return constructExampleCode(modelMaps.get(codegenParameter.dataType), modelMaps, processedModelMap); + } else { + //LOGGER.error("Error in constructing examples. Failed to look up the model " + codegenParameter.dataType); + return "TODO"; + } + } + } + + private String constructExampleCode(CodegenProperty codegenProperty, HashMap modelMaps, HashMap processedModelMap) { + if (codegenProperty.isListContainer) { // array + return codegenProperty.dataType + "{" + constructExampleCode(codegenProperty.items, modelMaps, processedModelMap) + ")"; + } else if (codegenProperty.isMapContainer) { // map + return "map[string]string{ \"Key\" = \"Value\" }"; + } else if (codegenProperty.isPrimitiveType) { // primitive type + if (codegenProperty.isString) { + if (StringUtils.isEmpty(codegenProperty.example)) { + return "\"" + codegenProperty.example + "\""; + } else { + return "\"" + codegenProperty.name + "_example\""; + } + } else if (codegenProperty.isBoolean) { // boolean + if (Boolean.parseBoolean(codegenProperty.example)) { + return "true"; + } else { + return "false"; + } + } else if (codegenProperty.isUri) { // URL + return "\"https://example.com\")!"; + } else if (codegenProperty.isDateTime || codegenProperty.isDate) { // datetime or date + return "time.Now()"; + } else{ // numeric + String example; + if (StringUtils.isEmpty(codegenProperty.example)) { + example = codegenProperty.example; + } else { + example = "123"; + } + + if (codegenProperty.isLong) { + return "int64(" + example + ")"; + } else { + return example; + } + } + } else { + // look up the model + if (modelMaps.containsKey(codegenProperty.dataType)) { + return constructExampleCode(modelMaps.get(codegenProperty.dataType), modelMaps, processedModelMap); + } else { + //LOGGER.error("Error in constructing examples. Failed to look up the model " + codegenProperty.dataType); + return "\"TODO\""; + } + } + } + + private String constructExampleCode(CodegenModel codegenModel, HashMap modelMaps, HashMap processedModelMap) { + String example; + + // break infinite recursion. Return, in case a model is already processed in the current context. + String model = codegenModel.name; + if (processedModelMap.containsKey(model)) { + int count = processedModelMap.get(model); + if (count == 1) { + processedModelMap.put(model, 2); + } else if (count == 2) { + return ""; + } else { + throw new RuntimeException("Invalid count when constructing example: " + count); + } + } else { + processedModelMap.put(model, 1); + } + + example = "" + goImportAlias + "." + codegenModel.name + "{"; + List propertyExamples = new ArrayList<>(); + for (CodegenProperty codegenProperty : codegenModel.allVars) { + propertyExamples.add(codegenProperty.name + ": " + constructExampleCode(codegenProperty, modelMaps, processedModelMap)); + } + example += StringUtils.join(propertyExamples, ", "); + example += "}"; + return example; + } + + } diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/GroovyClientCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/GroovyClientCodegen.java index 1066f2294b90..95b11793cdf5 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/GroovyClientCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/GroovyClientCodegen.java @@ -60,7 +60,7 @@ public GroovyClientCodegen() { languageSpecificPrimitives.add("File"); languageSpecificPrimitives.add("Map"); - sourceFolder = projectFolder + "/groovy"; + sourceFolder = projectFolder + File.separator +"groovy"; outputFolder = "generated-code/groovy"; modelTemplateFiles.put("model.mustache", ".groovy"); apiTemplateFiles.put("api.mustache", ".groovy"); diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/JavaCXFClientCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/JavaCXFClientCodegen.java index bb206b12f663..14a83fa21e06 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/JavaCXFClientCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/JavaCXFClientCodegen.java @@ -54,7 +54,7 @@ public JavaCXFClientCodegen() { supportsInheritance = true; - sourceFolder = "src/gen/java"; + sourceFolder = "src"+ File.separator +"gen"+ File.separator +"java"; invokerPackage = "org.openapitools.api"; artifactId = "openapi-jaxrs-client"; dateLibrary = "legacy"; //TODO: add joda support to all jax-rs diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/JavaClientCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/JavaClientCodegen.java index 07ece9aaea0c..e708b1f7e624 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/JavaClientCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/JavaClientCodegen.java @@ -71,6 +71,7 @@ public class JavaClientCodegen extends AbstractJavaCodegen public static final String GOOGLE_API_CLIENT = "google-api-client"; public static final String JERSEY1 = "jersey1"; public static final String JERSEY2 = "jersey2"; + public static final String JERSEY2_EXPERIMENTAL = "jersey2-experimental"; public static final String NATIVE = "native"; public static final String OKHTTP_GSON = "okhttp-gson"; public static final String RESTEASY = "resteasy"; @@ -144,6 +145,7 @@ public JavaClientCodegen() { 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(JERSEY2_EXPERIMENTAL, "HTTP client: Jersey client 2.25.1. JSON processing: Jackson 2.9.x"); supportedLibraries.put(FEIGN, "HTTP client: OpenFeign 9.x (deprecated) or 10.x (default). 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_1, "HTTP client: OkHttp 2.x. JSON processing: Gson 2.x (Retrofit 1.9.0). IMPORTANT NOTE: retrofit1.x is no longer actively maintained so please upgrade to 'retrofit2' instead."); @@ -153,7 +155,7 @@ public JavaClientCodegen() { supportedLibraries.put(RESTEASY, "HTTP client: Resteasy client 3.x. JSON processing: Jackson 2.9.x"); supportedLibraries.put(VERTX, "HTTP client: VertX client 3.x. JSON processing: Jackson 2.9.x"); supportedLibraries.put(GOOGLE_API_CLIENT, "HTTP client: Google API client 1.x. JSON processing: Jackson 2.9.x"); - supportedLibraries.put(REST_ASSURED, "HTTP client: rest-assured : 4.x. JSON processing: Gson 2.x or Jackson 2.9.x. Only for Java8"); + supportedLibraries.put(REST_ASSURED, "HTTP client: rest-assured : 4.x. JSON processing: Gson 2.x or Jackson 2.10.x. Only for Java 8"); supportedLibraries.put(NATIVE, "HTTP client: Java native HttpClient. JSON processing: Jackson 2.9.x. Only for Java11+"); supportedLibraries.put(MICROPROFILE, "HTTP client: Microprofile client X.x. JSON processing: Jackson 2.9.x"); @@ -293,6 +295,8 @@ public void processOpts() { supportingFiles.add(new SupportingFile("ApiClient.mustache", invokerFolder, "ApiClient.java")); supportingFiles.add(new SupportingFile("ServerConfiguration.mustache", invokerFolder, "ServerConfiguration.java")); supportingFiles.add(new SupportingFile("ServerVariable.mustache", invokerFolder, "ServerVariable.java")); + supportingFiles.add(new SupportingFile("openapi.mustache", "api", "openapi.yaml")); + if (!(RESTTEMPLATE.equals(getLibrary()) || REST_ASSURED.equals(getLibrary()) || NATIVE.equals(getLibrary()) || MICROPROFILE.equals(getLibrary()))) { supportingFiles.add(new SupportingFile("StringUtil.mustache", invokerFolder, "StringUtil.java")); @@ -365,9 +369,13 @@ public void processOpts() { if ("retrofit2".equals(getLibrary()) && !usePlayWS) { supportingFiles.add(new SupportingFile("JSON.mustache", invokerFolder, "JSON.java")); } - } else if (JERSEY2.equals(getLibrary())) { + } else if (JERSEY2.equals(getLibrary()) || JERSEY2_EXPERIMENTAL.equals(getLibrary())) { supportingFiles.add(new SupportingFile("JSON.mustache", invokerFolder, "JSON.java")); supportingFiles.add(new SupportingFile("ApiResponse.mustache", invokerFolder, "ApiResponse.java")); + if (JERSEY2_EXPERIMENTAL.equals(getLibrary())) { + supportingFiles.add(new SupportingFile("auth/HttpSignatureAuth.mustache", authFolder, "HttpSignatureAuth.java")); + supportingFiles.add(new SupportingFile("AbstractOpenApiSchema.mustache", (sourceFolder + File.separator + modelPackage().replace('.', File.separatorChar)).replace('/', File.separatorChar), "AbstractOpenApiSchema.java")); + } forceSerializationLibrary(SERIALIZATION_LIBRARY_JACKSON); } else if (NATIVE.equals(getLibrary())) { setJava8Mode(true); @@ -497,7 +505,7 @@ public void processOpts() { additionalProperties.remove(SERIALIZATION_LIBRARY_GSON); } - if (additionalProperties.containsKey(SERIALIZATION_LIBRARY_JACKSON)) { + if (additionalProperties.containsKey(SERIALIZATION_LIBRARY_JACKSON) && !JERSEY2_EXPERIMENTAL.equals(getLibrary())) { useOneOfInterfaces = true; addOneOfInterfaceImports = true; } @@ -593,6 +601,39 @@ public int compare(CodegenParameter one, CodegenParameter another) { objs = AbstractJavaJAXRSServerCodegen.jaxrsPostProcessOperations(objs); } + if (JERSEY2_EXPERIMENTAL.equals(getLibrary())) { + // index the model + HashMap modelMaps = new HashMap(); + for (Object o : allModels) { + HashMap h = (HashMap) o; + CodegenModel m = (CodegenModel) h.get("model"); + modelMaps.put(m.classname, m); + + } + + // check if return type is oneOf/anyeOf model + Map operations = (Map) objs.get("operations"); + List operationList = (List) operations.get("operation"); + for (CodegenOperation op : operationList) { + if (op.returnType != null) { + // look up the model to see if it's anyOf/oneOf + if (modelMaps.containsKey(op.returnType) && modelMaps.get(op.returnType) != null) { + CodegenModel cm = modelMaps.get(op.returnType); + + if (cm.oneOf != null && !cm.oneOf.isEmpty()) { + op.vendorExtensions.put("x-java-return-type-one-of", true); + } + + if (cm.anyOf != null && !cm.anyOf.isEmpty()) { + op.vendorExtensions.put("x-java-return-type-any-of", true); + } + } else { + //LOGGER.error("cannot lookup model " + op.returnType); + } + } + } + } + return objs; } @@ -767,12 +808,16 @@ public Map postProcessModels(Map objs) { CodegenModel cm = (CodegenModel) mo.get("model"); cm.getVendorExtensions().putIfAbsent("implements", new ArrayList()); // TODO: 5.0 Remove cm.getVendorExtensions().putIfAbsent("x-implements", cm.getVendorExtensions().get("implements")); - List impl = (List) cm.getVendorExtensions().get("implements"); + //List impl = (List) cm.getVendorExtensions().get("x-implements"); + if (JERSEY2_EXPERIMENTAL.equals(getLibrary())) { + cm.getVendorExtensions().put("x-implements", new ArrayList()); + } + if (this.parcelableModel) { - impl.add("Parcelable"); + ((ArrayList) cm.getVendorExtensions().get("x-implements")).add("Parcelable"); } if (this.serializableModel) { - impl.add("Serializable"); + ((ArrayList) cm.getVendorExtensions().get("x-implements")).add("Serializable"); } } @@ -883,6 +928,12 @@ static boolean isJsonVendorMimeType(String mime) { return mime != null && JSON_VENDOR_MIME_PATTERN.matcher(mime).matches(); } + @Override + public Map postProcessSupportingFileData(Map objs) { + generateYAMLSpecFile(objs); + return super.postProcessSupportingFileData(objs); + } + @Override public String toApiVarName(String name) { String apiVarName = super.toApiVarName(name); diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/JavaInflectorServerCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/JavaInflectorServerCodegen.java index 97c7bdb50b39..23036b61e7ed 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/JavaInflectorServerCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/JavaInflectorServerCodegen.java @@ -26,6 +26,7 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import java.io.File; import java.util.*; import static org.openapitools.codegen.utils.StringUtils.camelize; @@ -43,7 +44,7 @@ public JavaInflectorServerCodegen() { modifyFeatureSet(features -> features.includeDocumentationFeatures(DocumentationFeature.Readme)); - sourceFolder = "src/gen/java"; + sourceFolder = "src"+ File.separator+"gen"+ File.separator +"java"; apiTestTemplateFiles.clear(); // TODO: add test template embeddedTemplateDir = templateDir = "JavaInflector"; invokerPackage = "org.openapitools.controllers"; diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/JavaJAXRSSpecServerCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/JavaJAXRSSpecServerCodegen.java index a607dee5ac43..795600fa730a 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/JavaJAXRSSpecServerCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/JavaJAXRSSpecServerCodegen.java @@ -38,6 +38,7 @@ public class JavaJAXRSSpecServerCodegen extends AbstractJavaJAXRSServerCodegen { public static final String USE_SWAGGER_ANNOTATIONS = "useSwaggerAnnotations"; public static final String JACKSON = "jackson"; public static final String OPEN_API_SPEC_FILE_LOCATION = "openApiSpecFileLocation"; + public static final String GENERATE_BUILDERS = "generateBuilders"; public static final String QUARKUS_LIBRARY = "quarkus"; public static final String THORNTAIL_LIBRARY = "thorntail"; @@ -47,6 +48,7 @@ public class JavaJAXRSSpecServerCodegen extends AbstractJavaJAXRSServerCodegen { private boolean interfaceOnly = false; private boolean returnResponse = false; private boolean generatePom = true; + private boolean generateBuilders = false; private boolean useSwaggerAnnotations = true; private boolean useJackson = false; private String openApiSpecFileLocation = "src/main/openapi/openapi.yaml"; @@ -101,6 +103,7 @@ public JavaJAXRSSpecServerCodegen() { cliOptions.add(library); cliOptions.add(CliOption.newBoolean(GENERATE_POM, "Whether to generate pom.xml if the file does not already exist.").defaultValue(String.valueOf(generatePom))); + cliOptions.add(CliOption.newBoolean(GENERATE_BUILDERS, "Whether to generate builders for models.").defaultValue(String.valueOf(generateBuilders))); cliOptions.add(CliOption.newBoolean(INTERFACE_ONLY, "Whether to generate only API interface stubs without the server files.").defaultValue(String.valueOf(interfaceOnly))); cliOptions.add(CliOption.newBoolean(RETURN_RESPONSE, "Whether generate API interface should return javax.ws.rs.core.Response instead of a deserialized entity. Only useful if interfaceOnly is true.").defaultValue(String.valueOf(returnResponse))); cliOptions.add(CliOption.newBoolean(USE_SWAGGER_ANNOTATIONS, "Whether to generate Swagger annotations.", useSwaggerAnnotations)); @@ -124,7 +127,7 @@ public void processOpts() { additionalProperties.remove(RETURN_RESPONSE); } } - if(QUARKUS_LIBRARY.equals(library) || THORNTAIL_LIBRARY.equals(library) || HELIDON_LIBRARY.equals(library) || OPEN_LIBERTY_LIBRARY.equals(library)) { + if (QUARKUS_LIBRARY.equals(library) || THORNTAIL_LIBRARY.equals(library) || HELIDON_LIBRARY.equals(library) || OPEN_LIBERTY_LIBRARY.equals(library)) { useSwaggerAnnotations = false; } else { if (additionalProperties.containsKey(USE_SWAGGER_ANNOTATIONS)) { @@ -132,6 +135,12 @@ public void processOpts() { } } writePropertyBack(USE_SWAGGER_ANNOTATIONS, useSwaggerAnnotations); + + if (additionalProperties.containsKey(GENERATE_BUILDERS)) { + generateBuilders = Boolean.valueOf(additionalProperties.get(GENERATE_BUILDERS).toString()); + } + additionalProperties.put(GENERATE_BUILDERS, generateBuilders); + if (additionalProperties.containsKey(OPEN_API_SPEC_FILE_LOCATION)) { openApiSpecFileLocation = additionalProperties.get(OPEN_API_SPEC_FILE_LOCATION).toString(); } else if(QUARKUS_LIBRARY.equals(library) || THORNTAIL_LIBRARY.equals(library) || HELIDON_LIBRARY.equals(library)) { diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/MysqlSchemaCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/MysqlSchemaCodegen.java index fdf1d994e9ba..334f9579aed0 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/MysqlSchemaCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/MysqlSchemaCodegen.java @@ -20,10 +20,12 @@ import org.openapitools.codegen.meta.features.*; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import org.apache.commons.lang3.StringUtils; import java.util.*; import java.util.regex.Matcher; import java.util.regex.Pattern; +import java.io.File; import static org.openapitools.codegen.utils.StringUtils.underscore; @@ -35,6 +37,7 @@ public class MysqlSchemaCodegen extends DefaultCodegen implements CodegenConfig public static final String DEFAULT_DATABASE_NAME = "defaultDatabaseName"; public static final String JSON_DATA_TYPE_ENABLED = "jsonDataTypeEnabled"; public static final String IDENTIFIER_NAMING_CONVENTION = "identifierNamingConvention"; + public static final String NAMED_PARAMETERS_ENABLED = "namedParametersEnabled"; public static final Integer ENUM_MAX_ELEMENTS = 65535; public static final Integer IDENTIFIER_MAX_LENGTH = 64; @@ -58,6 +61,7 @@ public class MysqlSchemaCodegen extends DefaultCodegen implements CodegenConfig protected String tableNamePrefix = "tbl_", tableNameSuffix = ""; protected String columnNamePrefix = "col_", columnNameSuffix = ""; protected Boolean jsonDataTypeEnabled = true; + protected Boolean namedParametersEnabled = false; protected String identifierNamingConvention = "original"; public MysqlSchemaCodegen() { @@ -81,6 +85,8 @@ public MysqlSchemaCodegen() { // clear import mapping (from default generator) as mysql does not use import directives importMapping.clear(); + setModelPackage("Model"); + modelTemplateFiles.put("sql_query.mustache", ".sql"); //modelTestTemplateFiles.put("model_test.mustache", ".php"); // no doc files // modelDocTemplateFiles.clear(); @@ -179,6 +185,7 @@ public MysqlSchemaCodegen() { cliOptions.clear(); addOption(DEFAULT_DATABASE_NAME, "Default database name for all MySQL queries", defaultDatabaseName); addSwitch(JSON_DATA_TYPE_ENABLED, "Use special JSON MySQL data type for complex model properties. Requires MySQL version 5.7.8. Generates TEXT data type when disabled", jsonDataTypeEnabled); + addSwitch(NAMED_PARAMETERS_ENABLED, "Generates model prepared SQLs with named parameters, eg. :petName. Question mark placeholder used when option disabled.", namedParametersEnabled); // we used to snake_case table/column names, let's add this option CliOption identifierNamingOpt = new CliOption(IDENTIFIER_NAMING_CONVENTION, @@ -226,10 +233,19 @@ public void processOpts() { additionalProperties.put(JSON_DATA_TYPE_ENABLED, getJsonDataTypeEnabled()); } + if (additionalProperties.containsKey(NAMED_PARAMETERS_ENABLED)) { + this.setNamedParametersEnabled(Boolean.valueOf(additionalProperties.get(NAMED_PARAMETERS_ENABLED).toString())); + } + + additionalProperties.put(NAMED_PARAMETERS_ENABLED, getNamedParametersEnabled()); + if (additionalProperties.containsKey(IDENTIFIER_NAMING_CONVENTION)) { this.setIdentifierNamingConvention((String) additionalProperties.get(IDENTIFIER_NAMING_CONVENTION)); } + // make model src path available in mustache template + additionalProperties.put("modelSrcPath", "./" + toSrcPath(modelPackage)); + supportingFiles.add(new SupportingFile("README.mustache", "", "README.md")); supportingFiles.add(new SupportingFile("mysql_schema.mustache", "", "mysql_schema.sql")); } @@ -1158,6 +1174,24 @@ public Boolean getJsonDataTypeEnabled() { return this.jsonDataTypeEnabled; } + /** + * Enables named parameters in prepared SQLs + * + * @param enabled true to enable, otherwise false + */ + public void setNamedParametersEnabled(Boolean enabled) { + this.namedParametersEnabled = enabled; + } + + /** + * Whether named parameters enabled or disabled in prepared SQLs + * + * @return true if enabled otherwise false + */ + public Boolean getNamedParametersEnabled() { + return this.namedParametersEnabled; + } + /** * Sets identifier naming convention for table names and column names. * This is not related to database name which is defined by defaultDatabaseName option. @@ -1184,4 +1218,22 @@ public String getIdentifierNamingConvention() { return this.identifierNamingConvention; } + /** + * Slightly modified version of AbstractPhpCodegen.toSrcPath method. + * + * @param packageName package name + * + * @return path + */ + public String toSrcPath(String packageName) { + // Trim prefix file separators from package path + String packagePath = StringUtils.removeStart( + // Replace period, backslash, forward slash with file separator in package name + packageName.replaceAll("[\\.\\\\/]", Matcher.quoteReplacement("/")), + File.separator + ); + + // Trim trailing file separators from the overall path + return StringUtils.removeEnd(packagePath, File.separator); + } } diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/PhpSymfonyServerCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/PhpSymfonyServerCodegen.java index d0756dacc2a1..ef09fa0caa13 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/PhpSymfonyServerCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/PhpSymfonyServerCodegen.java @@ -55,6 +55,7 @@ public class PhpSymfonyServerCodegen extends AbstractPhpCodegen implements Codeg protected String controllerDirName = "Controller"; protected String serviceDirName = "Service"; protected String controllerPackage; + protected String controllerTestsPackage; protected String servicePackage; protected Boolean phpLegacySupport = Boolean.TRUE; @@ -301,6 +302,7 @@ public void processOpts() { additionalProperties.put("servicePackage", servicePackage); additionalProperties.put("apiTestsPackage", apiTestsPackage); additionalProperties.put("modelTestsPackage", modelTestsPackage); + additionalProperties.put("controllerTestsPackage", controllerTestsPackage); // make Symonfy-specific properties available additionalProperties.put("bundleName", bundleName); @@ -311,11 +313,13 @@ public void processOpts() { // make api and model src path available in mustache template additionalProperties.put("apiSrcPath", "." + "/" + toSrcPath(apiPackage, srcBasePath)); additionalProperties.put("modelSrcPath", "." + "/" + toSrcPath(modelPackage, srcBasePath)); + additionalProperties.put("controllerSrcPath", "." + "/" + toSrcPath(controllerPackage, srcBasePath)); additionalProperties.put("testsSrcPath", "." + "/" + toSrcPath(testsPackage, srcBasePath)); additionalProperties.put("apiTestsSrcPath", "." + "/" + toSrcPath(apiTestsPackage, srcBasePath)); additionalProperties.put("modelTestsSrcPath", "." + "/" + toSrcPath(modelTestsPackage, srcBasePath)); additionalProperties.put("apiTestPath", "." + "/" + testsDirName + "/" + apiDirName); additionalProperties.put("modelTestPath", "." + "/" + testsDirName + "/" + modelDirName); + additionalProperties.put("controllerTestPath", "." + "/" + testsDirName + "/" + controllerDirName); // make api and model doc path available in mustache template additionalProperties.put("apiDocPath", apiDocPath); @@ -346,6 +350,7 @@ public void processOpts() { supportingFiles.add(new SupportingFile("testing/phpunit.xml.mustache", "", "phpunit.xml.dist")); supportingFiles.add(new SupportingFile("testing/pom.xml", "", "pom.xml")); supportingFiles.add(new SupportingFile("testing/AppKernel.php", toSrcPath(testsPackage, srcBasePath), "AppKernel.php")); + supportingFiles.add(new SupportingFile("testing/ControllerTest.mustache", toSrcPath(controllerTestsPackage, srcBasePath), "ControllerTest.php")); supportingFiles.add(new SupportingFile("testing/test_config.yml", toSrcPath(testsPackage, srcBasePath), "test_config.yml")); supportingFiles.add(new SupportingFile("routing.mustache", configDir, "routing.yml")); @@ -540,6 +545,7 @@ public void setInvokerPackage(String invokerPackage) { apiTestsPackage = testsPackage + "\\" + apiDirName; modelTestsPackage = testsPackage + "\\" + modelDirName; controllerPackage = invokerPackage + "\\" + controllerDirName; + controllerTestsPackage = testsPackage + "\\" + controllerDirName; servicePackage = invokerPackage + "\\" + serviceDirName; } diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/PowerShellExperimentalClientCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/PowerShellExperimentalClientCodegen.java index 3e3c32a96fb0..5896ee99efea 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/PowerShellExperimentalClientCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/PowerShellExperimentalClientCodegen.java @@ -18,6 +18,8 @@ import io.swagger.v3.oas.models.media.ArraySchema; import io.swagger.v3.oas.models.media.Schema; +import org.apache.commons.io.FilenameUtils; +import org.apache.commons.lang3.StringEscapeUtils; import org.apache.commons.lang3.StringUtils; import org.openapitools.codegen.*; import org.openapitools.codegen.meta.GeneratorMetadata; @@ -50,6 +52,7 @@ public class PowerShellExperimentalClientCodegen extends DefaultCodegen implemen protected String powershellGalleryUrl; protected HashSet powershellVerbs; protected Map commonVerbs; // verbs not in the official ps verb list but can be mapped to one of the verbs + protected HashSet methodNames; // store a list of method names to detect duplicates /** * Constructs an instance of `PowerShellExperimentalClientCodegen`. @@ -123,9 +126,134 @@ public PowerShellExperimentalClientCodegen() { )); commonVerbs = new HashMap(); - commonVerbs.put("Create", "New"); - commonVerbs.put("Delete", "Remove"); - commonVerbs.put("Update", "Set"); + + Map> verbMappings = new HashMap>(); + + // common + verbMappings.put("Add", Arrays.asList("Append", "Attach", "Concatenate", "Insert")); + verbMappings.put("Clear", Arrays.asList("Flush", "Erase", "Release", "Unmark", "Unset", "Nullify")); + verbMappings.put("Close", Arrays.asList()); + verbMappings.put("Copy", Arrays.asList("Duplicate", "Clone", "Replicate", "Sync")); + verbMappings.put("Enter", Arrays.asList("PushInto")); + verbMappings.put("Exit", Arrays.asList("PopOut")); + verbMappings.put("Find", Arrays.asList()); + verbMappings.put("Format", Arrays.asList()); + verbMappings.put("Get", Arrays.asList("Read", "Open", "Cat", "Type", "Dir", "Obtain", "Dump", "Acquire", "Examine", "Find", "Search")); + verbMappings.put("Hide", Arrays.asList("Block")); + verbMappings.put("Join", Arrays.asList("Combine", "Unite", "Connect", "Associate")); + verbMappings.put("Lock", Arrays.asList("RestrictSecure")); + verbMappings.put("Move", Arrays.asList("Transfer", "Name", "Migrate")); + verbMappings.put("New", Arrays.asList("Create", "Generate", "Build", "Make", "Allocate")); + verbMappings.put("Open", Arrays.asList()); + verbMappings.put("Optimize", Arrays.asList()); + verbMappings.put("Pop", Arrays.asList()); + verbMappings.put("Push", Arrays.asList()); + verbMappings.put("Redo", Arrays.asList()); + verbMappings.put("Remove", Arrays.asList("Clear", "Cut", "Dispose", "Discard", "Erase")); + verbMappings.put("Rename", Arrays.asList("Change")); + verbMappings.put("Reset", Arrays.asList()); + verbMappings.put("Search", Arrays.asList("FindLocate")); + verbMappings.put("Select", Arrays.asList("FindLocate")); + verbMappings.put("Set", Arrays.asList("Write", "Reset", "Assign", "Configure")); + verbMappings.put("Show", Arrays.asList("DisplayProduce")); + verbMappings.put("Skip", Arrays.asList("BypassJump")); + verbMappings.put("Split", Arrays.asList("parate")); + verbMappings.put("Step", Arrays.asList()); + verbMappings.put("Switch", Arrays.asList()); + verbMappings.put("Undo", Arrays.asList()); + verbMappings.put("Unlock", Arrays.asList("Release", "Unrestrict", "Unsecure")); + verbMappings.put("Watch", Arrays.asList()); + + // communication + verbMappings.put("Connect", Arrays.asList("JoinTelnet")); + verbMappings.put("Disconnect", Arrays.asList("BreakLogoff")); + verbMappings.put("Read", Arrays.asList("Acquire", "Prompt", "Get")); + verbMappings.put("Receive", Arrays.asList("Read", "Accept", "Peek")); + verbMappings.put("Send", Arrays.asList("Put", "Broadcast", "Mail", "Fax")); + verbMappings.put("Write", Arrays.asList("PutPrint")); + + // data + verbMappings.put("Backup", Arrays.asList(" Save", " Burn", " Replicate", "Sync")); + verbMappings.put("Checkpoint", Arrays.asList(" Diff")); + verbMappings.put("Compare", Arrays.asList(" Diff")); + verbMappings.put("Compress", Arrays.asList(" Compact")); + verbMappings.put("Convert", Arrays.asList(" Change", " Resize", "Resample")); + verbMappings.put("ConvertFrom", Arrays.asList(" Export", " Output", "Out")); + verbMappings.put("ConvertTo", Arrays.asList(" Import", " Input", "In")); + verbMappings.put("Dismount", Arrays.asList(" UnmountUnlink")); + verbMappings.put("Edit", Arrays.asList(" Change", " Update", "Modify")); + verbMappings.put("Expand", Arrays.asList(" ExplodeUncompress")); + verbMappings.put("Export", Arrays.asList(" ExtractBackup")); + verbMappings.put("Group", Arrays.asList(" Aggregate", " Arrange", " Associate", "Correlate")); + verbMappings.put("Import", Arrays.asList(" BulkLoadLoad")); + verbMappings.put("Initialize", Arrays.asList(" Erase", " Init", " Renew", " Rebuild", " Reinitialize", "Setup")); + verbMappings.put("Limit", Arrays.asList(" Quota")); + verbMappings.put("Merge", Arrays.asList(" CombineJoin")); + verbMappings.put("Mount", Arrays.asList(" Connect")); + verbMappings.put("Out", Arrays.asList()); + verbMappings.put("Publish", Arrays.asList(" Deploy", " Release", "Install")); + verbMappings.put("Restore", Arrays.asList(" Repair", " Return", " Undo", "Fix")); + verbMappings.put("Save", Arrays.asList()); + verbMappings.put("Sync", Arrays.asList(" Replicate", " Coerce", "Match")); + verbMappings.put("Unpublish", Arrays.asList(" Uninstall", " Revert", "Hide")); + verbMappings.put("Update", Arrays.asList(" Refresh", " Renew", " Recalculate", "Re-index")); + + // diagnostic + verbMappings.put("Debug", Arrays.asList("Diagnose")); + verbMappings.put("Measure", Arrays.asList("Calculate", "Determine", "Analyze")); + verbMappings.put("Ping", Arrays.asList()); + verbMappings.put("Repair", Arrays.asList("FixRestore")); + verbMappings.put("Resolve", Arrays.asList("ExpandDetermine")); + verbMappings.put("Test", Arrays.asList("Diagnose", "Analyze", "Salvage", "Verify")); + verbMappings.put("Trace", Arrays.asList("Track", "Follow", "Inspect", "Dig")); + + // lifecycle + verbMappings.put("Approve", Arrays.asList()); + verbMappings.put("Assert", Arrays.asList("Certify")); + verbMappings.put("Build", Arrays.asList()); + verbMappings.put("Complete", Arrays.asList()); + verbMappings.put("Confirm", Arrays.asList("Acknowledge", "Agree", "Certify", "Validate", "Verify")); + verbMappings.put("Deny", Arrays.asList("Block", "Object", "Refuse", "Reject")); + verbMappings.put("Deploy", Arrays.asList()); + verbMappings.put("Disable", Arrays.asList("HaltHide")); + verbMappings.put("Enable", Arrays.asList("StartBegin")); + verbMappings.put("Install", Arrays.asList("Setup")); + verbMappings.put("Invoke", Arrays.asList("RunStart")); + verbMappings.put("Register", Arrays.asList()); + verbMappings.put("Request", Arrays.asList()); + verbMappings.put("Restart", Arrays.asList("Recycle")); + verbMappings.put("Resume", Arrays.asList()); + verbMappings.put("Start", Arrays.asList("Launch", "Initiate", "Boot")); + verbMappings.put("Stop", Arrays.asList("End", "Kill", "Terminate", "Cancel")); + verbMappings.put("Submit", Arrays.asList("Post")); + verbMappings.put("Suspend", Arrays.asList("Pause")); + verbMappings.put("Uninstall", Arrays.asList()); + verbMappings.put("Unregister", Arrays.asList("Remove")); + verbMappings.put("Wait", Arrays.asList("SleepPause")); + + // security + verbMappings.put("Block", Arrays.asList("Prevent", "Limit", "Deny")); + verbMappings.put("Grant", Arrays.asList("AllowEnable")); + verbMappings.put("Protect", Arrays.asList("Encrypt", "Safeguard", "Seal")); + verbMappings.put("Revoke", Arrays.asList("RemoveDisable")); + verbMappings.put("Unblock", Arrays.asList("ClearAllow")); + verbMappings.put("Unprotect", Arrays.asList("DecryptUnseal")); + + // other + verbMappings.put("Use", Arrays.asList()); + + for (Map.Entry> entry : verbMappings.entrySet()) { + // loop through each verb in the list + for (String verb : entry.getValue()) { + if (verbMappings.containsKey(verb)) { + // the verb to be mapped is also a common verb, do nothing + LOGGER.debug("verbmapping: skipped {}", verb); + } else { + commonVerbs.put(verb, entry.getKey()); + LOGGER.debug("verbmapping: adding {} => {}", verb, entry.getKey()); + } + } + } powershellVerbs = new HashSet(Arrays.asList( "Add", @@ -229,6 +357,7 @@ public PowerShellExperimentalClientCodegen() { "Use" )); + methodNames = new HashSet(); nullablePrimitives = new HashSet(Arrays.asList( "System.Nullable[Byte]", @@ -245,42 +374,77 @@ public PowerShellExperimentalClientCodegen() { "System.Nullable[Boolean]" )); - // https://richardspowershellblog.wordpress.com/2009/05/02/powershell-reserved-words/ + // list of reserved words - must be in lower case reservedWords = new HashSet(Arrays.asList( - "Begin", - "Break", - "Catch", - "Continue", - "Data", - "Do", - "Dynamicparam", - "Else", - "Elseif", - "End", - "Exit", - "Filter", - "Finally", - "For", - "Foreach", - "From", - "Function", - "If", - "In", - "Param", - "Process", - "Return", - "Switch", - "Throw", - "Trap", - "Try", - "Until", - "While", - "Local", - "Private", - "Where" + // https://richardspowershellblog.wordpress.com/2009/05/02/powershell-reserved-words/ + "begin", + "break", + "catch", + "continue", + "data", + "do", + "dynamicparam", + "else", + "elseif", + "end", + "exit", + "filter", + "finally", + "for", + "foreach", + "from", + "function", + "if", + "in", + "param", + "process", + "return", + "switch", + "throw", + "trap", + "try", + "until", + "while", + "local", + "private", + "where", + // special variables + "args", + "consolefilename", + "error", + "event", + "eventargs", + "eventsubscriber", + "executioncontext", + "false", + "foreach", + "home", + "host", + "input", + "lastexitcode", + "matches", + "myinvocation", + "nestedpromptlevel", + "null", + "pid", + "profile", + "pscmdlet", + "pscommandpath", + "psculture", + "psdebugcontext", + "pshome", + "psitem", + "psscriptroot", + "pssenderinfo", + "psuiculture", + "psversiontable", + "sender", + "shellid", + "stacktrace", + "this", + "true" )); - defaultIncludes = new HashSet(Arrays.asList( "Byte", "SByte", @@ -333,6 +497,7 @@ public PowerShellExperimentalClientCodegen() { cliOptions.add(new CliOption(CodegenConstants.PACKAGE_VERSION, "Package version (e.g. 0.1.2).").defaultValue(this.packageVersion)); cliOptions.add(new CliOption(CodegenConstants.OPTIONAL_PROJECT_GUID, "GUID for PowerShell module (e.g. a27b908d-2a20-467f-bc32-af6f3a654ac5). A random GUID will be generated by default.")); cliOptions.add(new CliOption(CodegenConstants.API_NAME_PREFIX, "Prefix that will be appended to all PS objects. Default: empty string. e.g. Pet => PSPet.")); + cliOptions.add(new CliOption("commonVerbs", "PS common verb mappings. e.g. Delete=Remove:Patch=Update to map Delete with Remove and Patch with Update accordingly.")); } @@ -374,6 +539,11 @@ public void setPowershellGalleryUrl(String powershellGalleryUrl) { public void processOpts() { super.processOpts(); + if (StringUtils.isEmpty(System.getenv("POWERSHELL_POST_PROCESS_FILE"))) { + LOGGER.info("Environment variable POWERSHELL_POST_PROCESS_FILE not defined so the PowerShell code may not be properly formatted. To define it, try 'export POWERSHELL_POST_PROCESS_FILE=\"Edit-DTWBeautifyScript\"'"); + LOGGER.info("NOTE: To enable file post-processing, 'enablePostProcessFile' must be set to `true` (--enable-post-process-file for CLI)."); + } + if (additionalProperties.containsKey("powershellGalleryUrl")) { setPowershellGalleryUrl((String) additionalProperties.get("powershellGalleryUrl")); } else { @@ -404,6 +574,19 @@ public void processOpts() { additionalProperties.put(CodegenConstants.PACKAGE_VERSION, packageVersion); } + if (additionalProperties.containsKey("commonVerbs")) { + String[] entries = ((String)additionalProperties.get("commonVerbs")).split(":"); + for (String entry : entries) { + String[] pair = entry.split("="); + if (pair.length == 2) { + commonVerbs.put(pair[0], pair[1]); + LOGGER.debug("Add commonVerbs: {} => {}", pair[0], pair[1]); + } else { + LOGGER.error("Failed to parse commonVerbs: {}", entry); + } + } + } + if (additionalProperties.containsKey(CodegenConstants.MODEL_PACKAGE)) { LOGGER.warn(CodegenConstants.MODEL_PACKAGE + " with " + this.getName() + " generator is ignored. Setting this value independently of " + CodegenConstants.PACKAGE_NAME + " is not currently supported."); } @@ -440,6 +623,28 @@ public void processOpts() { supportingFiles.add(new SupportingFile("appveyor.mustache", "", "appveyor.yml")); } + @SuppressWarnings("static-method") + @Override + public String escapeText(String input) { + + if (input == null) { + return input; + } + + // remove \t, \n, \r + // replace \ with \\ + // replace " with \" + // outter unescape to retain the original multi-byte characters + // finally escalate characters avoiding code injection + return escapeUnsafeCharacters( + StringEscapeUtils.unescapeJava( + StringEscapeUtils.escapeJava(input) + .replace("\\/", "/")) + .replaceAll("[\\t\\n\\r]", " ") + .replace("\\", "\\\\") + .replace("\"", "\"\"")); + } + @Override public String escapeUnsafeCharacters(String input) { return input.replace("#>", "#_>").replace("<#", "<_#"); @@ -494,7 +699,7 @@ public String modelFileFolder() { @Override public String escapeReservedWord(String name) { - return "_" + name; + return "Var" + name; } /** @@ -514,23 +719,23 @@ public String toModelName(String name) { name = name + "_" + modelNameSuffix; } - name = sanitizeName(name); + // camelize the model name + // phone_number => PhoneNumber + name = camelize(sanitizeName(name)); // model name cannot use reserved keyword, e.g. return if (isReservedWord(name)) { - LOGGER.warn(name + " (reserved word) cannot be used as model name. Renamed to " + camelize("model_" + name)); - name = "model_" + name; // e.g. return => ModelReturn (after camelize) + LOGGER.warn(name + " (reserved word or special variable name) cannot be used as model name. Renamed to " + camelize("model_" + name)); + name = camelize("model_" + name); // e.g. return => ModelReturn (after camelize) } // model name starts with number if (name.matches("^\\d.*")) { LOGGER.warn(name + " (model name starts with number) cannot be used as model name. Renamed to " + camelize("model_" + name)); - name = "model_" + name; // e.g. 200Response => Model200Response (after camelize) + name = camelize("model_" + name); // e.g. 200Response => Model200Response (after camelize) } - // camelize the model name - // phone_number => PhoneNumber - return camelize(name); + return name; } @Override @@ -596,27 +801,7 @@ public String toOperationId(String operationId) { @Override public String toParamName(String name) { - // sanitize name - name = sanitizeName(name); - - // replace - with _ e.g. created-at => created_at - name = name.replaceAll("-", "_"); - - // if it's all upper case, do nothing - if (name.matches("^[A-Z_]*$")) { - return name; - } - - // camelize the variable name - // pet_id => PetId - name = camelize(name, false); - - // for reserved word or word starting with number, append _ - if (isReservedWord(name) || name.matches("^\\d.*")) { - name = escapeReservedWord(name); - } - - return name; + return toVarName(name); } @Override @@ -648,6 +833,17 @@ public Map postProcessOperationsWithModels(Map o } else { op.vendorExtensions.put("x-powershell-method-name-lowercase", ((String) op.vendorExtensions.get("x-powershell-method-name")).toLowerCase(Locale.ROOT)); } + + // detect duplicated method name + if (methodNames.contains(op.vendorExtensions.get("x-powershell-method-name"))) { + LOGGER.error("Duplicated method name found: {}", op.vendorExtensions.get("x-powershell-method-name")); + } else { + methodNames.add(op.vendorExtensions.get("x-powershell-method-name")); + } + + if (op.produces != null && op.produces.size() > 1) { + op.vendorExtensions.put("x-powershell-select-accept", true); + } } processedModelMaps.clear(); @@ -671,7 +867,7 @@ public Map postProcessModels(Map objs) { Map mo = (Map) _mo; CodegenModel cm = (CodegenModel) mo.get("model"); - for (CodegenProperty cp : cm.vars) { + for (CodegenProperty cp : cm.allVars) { cp.vendorExtensions.put("x-powershell-data-type", getPSDataType(cp)); } } @@ -684,17 +880,13 @@ public String toVarName(String name) { // sanitize name name = sanitizeName(name); - // if it's all uppper case, do nothing - if (name.matches("^[A-Z_]*$")) { - return name; - } - // camelize the variable name // pet_id => PetId name = camelize(name); // for reserved word or word starting with number, append _ if (isReservedWord(name) || name.matches("^\\d.*")) { + LOGGER.warn(name + " (reserved word or special variable name) cannot be used in naming. Renamed to " + escapeReservedWord(name)); name = escapeReservedWord(name); } @@ -805,7 +997,7 @@ private String constructExampleCode(CodegenModel codegenModel, HashMap propertyExamples = new ArrayList<>(); - for (CodegenProperty codegenProperty : codegenModel.vars) { + for (CodegenProperty codegenProperty : codegenModel.allVars) { propertyExamples.add("-" + codegenProperty.name + " " + constructExampleCode(codegenProperty, modelMaps, processedModelMap)); } example += StringUtils.join(propertyExamples, " "); @@ -864,7 +1056,7 @@ private String toMethodName(String operationId) { for (Map.Entry entry : commonVerbs.entrySet()) { if (methodName.startsWith(entry.getKey())) { methodName = entry.getValue() + "-" + apiNamePrefix + methodName.substring(entry.getKey().length()); - LOGGER.info("Naming the method using the common verb (e.g. Create, Delete, Update): {} => {}", operationId, methodName); + LOGGER.info("Naming the method by mapping the common verbs (e.g. Create, Change) to PS verbs: {} => {}", operationId, methodName); return methodName; } } @@ -872,4 +1064,38 @@ private String toMethodName(String operationId) { // not using powershell verb return "Invoke-" + apiNamePrefix + methodName; } + + @Override + public void postProcessFile(File file, String fileType) { + if (file == null) { + return; + } + String powershellPostProcessFile = System.getenv("POWERSHELL_POST_PROCESS_FILE"); + if (StringUtils.isEmpty(powershellPostProcessFile)) { + return; // skip if POWERSHELL_POST_PROCESS_FILE env variable is not defined + } + + // only process files with ps extension + if ("ps".equals(FilenameUtils.getExtension(file.toString()))) { + String command = powershellPostProcessFile + " " + file.toString(); + try { + Process p = Runtime.getRuntime().exec(command); + int exitValue = p.waitFor(); + if (exitValue != 0) { + LOGGER.error("Error running the command ({}). Exit value: {}", command, exitValue); + } else { + LOGGER.info("Successfully executed: " + command); + } + } catch (Exception e) { + LOGGER.error("Error running the command ({}). Exception: {}", command, e.getMessage()); + } + } + + } + + @Override + public String toRegularExpression(String pattern) { + return escapeText(pattern); + } + } diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/PythonAbstractConnexionServerCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/PythonAbstractConnexionServerCodegen.java index 18256382d585..267d14bc83b3 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/PythonAbstractConnexionServerCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/PythonAbstractConnexionServerCodegen.java @@ -51,6 +51,7 @@ public class PythonAbstractConnexionServerCodegen extends DefaultCodegen impleme public static final String SUPPORT_PYTHON2 = "supportPython2"; // nose is a python testing framework, we use pytest if USE_NOSE is unset public static final String USE_NOSE = "useNose"; + public static final String PYTHON_SRC_ROOT = "pythonSrcRoot"; static final String MEDIA_TYPE = "mediaType"; protected int serverPort = 8080; @@ -61,6 +62,7 @@ public class PythonAbstractConnexionServerCodegen extends DefaultCodegen impleme protected Map regexModifiers; protected boolean fixBodyName; protected boolean useNose = Boolean.FALSE; + protected String pythonSrcRoot; public PythonAbstractConnexionServerCodegen(String templateDirectory, boolean fixBodyNameValue) { super(); @@ -165,6 +167,8 @@ public PythonAbstractConnexionServerCodegen(String templateDirectory, boolean fi defaultValue("8080")); cliOptions.add(CliOption.newBoolean(USE_NOSE, "use the nose test framework"). defaultValue(Boolean.FALSE.toString())); + cliOptions.add(new CliOption(PYTHON_SRC_ROOT, "put python sources in this subdirectory of output folder (defaults to \"\" for). Use this for src/ layout."). + defaultValue("")); } protected void addSupportingFiles() { @@ -212,6 +216,12 @@ public void processOpts() { if (additionalProperties.containsKey(USE_NOSE)) { setUseNose((String) additionalProperties.get(USE_NOSE)); } + if (additionalProperties.containsKey(PYTHON_SRC_ROOT)) { + setPythonSrcRoot((String) additionalProperties.get(PYTHON_SRC_ROOT)); + additionalProperties.put(PYTHON_SRC_ROOT, pythonSrcRoot); + } else { + setPythonSrcRoot(""); + } supportingFiles.add(new SupportingFile("__main__.mustache", packagePath(), "__main__.py")); supportingFiles.add(new SupportingFile("util.mustache", packagePath(), "util.py")); supportingFiles.add(new SupportingFile("typing_utils.mustache", packagePath(), "typing_utils.py")); @@ -230,6 +240,25 @@ public void setUseNose(String val) { this.useNose = Boolean.valueOf(val); } + public void setPythonSrcRoot(String val) { + String pySrcRoot; + if (val == null) { + pySrcRoot = ""; + } else { + pySrcRoot = val.replaceAll("[/\\\\]+$", ""); + } + + if (pySrcRoot.isEmpty() || pySrcRoot == ".") { + this.pythonSrcRoot = ""; + } else { + this.pythonSrcRoot = pySrcRoot + File.separator; + } + } + + public String pythonSrcOutputFolder() { + return outputFolder + File.separator + pythonSrcRoot; + } + private static String packageToPath(String pkg) { return pkg.replace(".", File.separator); } @@ -304,7 +333,14 @@ public String escapeReservedWord(String name) { */ @Override public String apiFileFolder() { - return outputFolder + File.separator + apiPackage().replace('.', File.separatorChar); + String pkgPath = apiPackage().replace('.', File.separatorChar); + return pythonSrcOutputFolder() + pkgPath; + } + + @Override + public String modelFileFolder() { + String pkgPath = modelPackage().replace('.', File.separatorChar); + return pythonSrcOutputFolder() + pkgPath; } @Override @@ -558,6 +594,7 @@ public Map postProcessSupportingFileData(Map obj } } + generateJSONSpecFile(objs); generateYAMLSpecFile(objs); for (Map operations : getOperations(objs)) { @@ -799,7 +836,8 @@ public void setPackageVersion(String packageVersion) { } public String packagePath() { - return packageName.replace('.', File.separatorChar); + String pkgPath = packageName.replace('.', File.separatorChar); + return pythonSrcRoot + pkgPath; } @Override diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/PythonAiohttpConnexionServerCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/PythonAiohttpConnexionServerCodegen.java index 7f9dd74bf3d2..1e29687eb8cc 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/PythonAiohttpConnexionServerCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/PythonAiohttpConnexionServerCodegen.java @@ -71,6 +71,7 @@ protected void addSupportingFiles() { supportingFiles.add(new SupportingFile("conftest.mustache", testPackage, "conftest.py")); supportingFiles.add(new SupportingFile("__init__test.mustache", testPackage, "__init__.py")); supportingFiles.add(new SupportingFile("__init__main.mustache", packagePath(), "__init__.py")); + supportingFiles.add(new SupportingFile("setup.mustache", "", "setup.py")); supportingFiles.add(new SupportingFile("tox.mustache", "", "tox.ini")); supportingFiles.add(new SupportingFile("gitignore.mustache", "", ".gitignore")); } diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/PythonClientCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/PythonClientCodegen.java index ca59f763d74c..74796111afd9 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/PythonClientCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/PythonClientCodegen.java @@ -119,6 +119,7 @@ public PythonClientCodegen() { languageSpecificPrimitives.add("object"); // TODO file and binary is mapped as `file` languageSpecificPrimitives.add("file"); + languageSpecificPrimitives.add("bytes"); typeMapping.clear(); typeMapping.put("integer", "int"); @@ -133,6 +134,7 @@ public PythonClientCodegen() { typeMapping.put("date", "date"); typeMapping.put("DateTime", "datetime"); typeMapping.put("object", "object"); + typeMapping.put("AnyType", "object"); typeMapping.put("file", "file"); // TODO binary should be mapped to byte array // mapped to String as a workaround @@ -828,7 +830,7 @@ private String toExampleValueRecursive(Schema schema, List included_sche if (schema.getDiscriminator()!=null) { toExclude = schema.getDiscriminator().getPropertyName(); } - + example = packageName + ".models." + underscore(schema.getTitle())+"."+schema.getTitle()+"("; // if required only: diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/PythonClientExperimentalCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/PythonClientExperimentalCodegen.java index 9ea7c3fbe34a..60a004b6bea8 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/PythonClientExperimentalCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/PythonClientExperimentalCodegen.java @@ -111,6 +111,8 @@ public PythonClientExperimentalCodegen() { @Override public void processOpts() { + this.setLegacyDiscriminatorBehavior(false); + super.processOpts(); supportingFiles.remove(new SupportingFile("api_client.mustache", packagePath(), "api_client.py")); @@ -369,7 +371,7 @@ public Map postProcessAllModels(Map objs) { for (Map mo : models) { CodegenModel cm = (CodegenModel) mo.get("model"); - // make sure discrimonator models are included in imports + // make sure discriminator models are included in imports CodegenDiscriminator discriminator = cm.discriminator; if (discriminator != null) { Set mappedModels = discriminator.getMappedModels(); @@ -882,8 +884,8 @@ public String getSimpleTypeDeclaration(Schema schema) { * Return a string representation of the Python types for the specified schema. * Primitive types in the OAS specification are implemented in Python using the corresponding * Python primitive types. - * Composed types (e.g. allAll, oneOf, anyOf) are represented in Python using list of types. - * + * Composed types (e.g. allAll, oneOf, anyOf) are represented in Python using list of types. + * * @param p The OAS schema. * @param prefix prepended to the returned value. * @param suffix appended to the returned value. diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/ScalaAkkaClientCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/ScalaAkkaClientCodegen.java index 8f1bdde8c63f..c6da992792b9 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/ScalaAkkaClientCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/ScalaAkkaClientCodegen.java @@ -35,7 +35,6 @@ import java.io.Writer; import java.util.*; -import static org.openapitools.codegen.languages.AbstractJavaCodegen.DATE_LIBRARY; import static org.openapitools.codegen.utils.StringUtils.camelize; public class ScalaAkkaClientCodegen extends AbstractScalaCodegen implements CodegenConfig { diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/ScalaAkkaHttpServerCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/ScalaAkkaHttpServerCodegen.java new file mode 100644 index 000000000000..d8c33f499da4 --- /dev/null +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/ScalaAkkaHttpServerCodegen.java @@ -0,0 +1,507 @@ +/* + * Copyright 2018 OpenAPI-Generator Contributors (https://openapi-generator.tech) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.openapitools.codegen.languages; + +import io.swagger.v3.oas.models.Operation; +import io.swagger.v3.oas.models.parameters.Parameter; +import io.swagger.v3.oas.models.servers.Server; +import org.openapitools.codegen.*; +import org.openapitools.codegen.meta.GeneratorMetadata; +import org.openapitools.codegen.meta.Stability; +import org.openapitools.codegen.meta.features.*; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.io.File; +import java.util.*; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +public class ScalaAkkaHttpServerCodegen extends AbstractScalaCodegen implements CodegenConfig { + protected String groupId; + protected String artifactId; + protected String artifactVersion; + protected String invokerPackage; + + protected String akkaHttpVersion; + + public static final String AKKA_HTTP_VERSION = "akkaHttpVersion"; + public static final String AKKA_HTTP_VERSION_DESC = "The version of akka-http"; + public static final String DEFAULT_AKKA_HTTP_VERSION = "10.1.10"; + + static Logger LOGGER = LoggerFactory.getLogger(ScalaAkkaHttpServerCodegen.class); + + public CodegenType getTag() { + return CodegenType.SERVER; + } + + public String getName() { + return "scala-akka-http-server"; + } + + public String getHelp() { + return "Generates a scala-akka-http server (beta)."; + } + + public ScalaAkkaHttpServerCodegen() { + super(); + + modifyFeatureSet(features -> features + .includeDocumentationFeatures(DocumentationFeature.Readme) + .wireFormatFeatures(EnumSet.of(WireFormatFeature.JSON, WireFormatFeature.XML, WireFormatFeature.Custom)) + .securityFeatures(EnumSet.of( + SecurityFeature.BasicAuth, + SecurityFeature.ApiKey, + SecurityFeature.BearerToken + )) + .excludeGlobalFeatures( + GlobalFeature.XMLStructureDefinitions, + GlobalFeature.Callbacks, + GlobalFeature.LinkObjects, + GlobalFeature.ParameterStyling + ) + .excludeSchemaSupportFeatures( + SchemaSupportFeature.Polymorphism + ) + .excludeParameterFeatures( + ParameterFeature.Cookie + ) + ); + generatorMetadata = GeneratorMetadata.newBuilder(generatorMetadata) + .stability(Stability.BETA) + .build(); + + outputFolder = "generated-code" + File.separator + "scala-akka-http"; + modelTemplateFiles.put("model.mustache", ".scala"); + apiTemplateFiles.put("api.mustache", ".scala"); + embeddedTemplateDir = templateDir = "scala-akka-http-server"; + + groupId = "org.openapitools"; + artifactId = "openapi-scala-akka-http-server"; + artifactVersion = "1.0.0"; + apiPackage = "org.openapitools.server.api"; + modelPackage = "org.openapitools.server.model"; + invokerPackage = "org.openapitools.server"; + akkaHttpVersion = DEFAULT_AKKA_HTTP_VERSION; + + setReservedWordsLowerCase( + Arrays.asList( + "abstract", "case", "catch", "class", "def", "do", "else", "extends", + "false", "final", "finally", "for", "forSome", "if", "implicit", + "import", "lazy", "match", "new", "null", "object", "override", "package", + "private", "protected", "return", "sealed", "super", "this", "throw", + "trait", "try", "true", "type", "val", "var", "while", "with", "yield") + ); + + cliOptions.add(CliOption.newString(CodegenConstants.INVOKER_PACKAGE, CodegenConstants.INVOKER_PACKAGE_DESC).defaultValue(invokerPackage)); + cliOptions.add(CliOption.newString(CodegenConstants.GROUP_ID, CodegenConstants.GROUP_ID_DESC).defaultValue(groupId)); + cliOptions.add(CliOption.newString(CodegenConstants.ARTIFACT_ID, CodegenConstants.ARTIFACT_ID).defaultValue(artifactId)); + cliOptions.add(CliOption.newString(CodegenConstants.ARTIFACT_VERSION, CodegenConstants.ARTIFACT_VERSION_DESC).defaultValue(artifactVersion)); + cliOptions.add(CliOption.newString(AKKA_HTTP_VERSION, AKKA_HTTP_VERSION_DESC).defaultValue(akkaHttpVersion)); + + importMapping.remove("Seq"); + importMapping.remove("List"); + importMapping.remove("Set"); + importMapping.remove("Map"); + + typeMapping = new HashMap<>(); + typeMapping.put("array", "Seq"); + typeMapping.put("set", "Set"); + typeMapping.put("boolean", "Boolean"); + typeMapping.put("string", "String"); + typeMapping.put("int", "Int"); + typeMapping.put("integer", "Int"); + typeMapping.put("long", "Long"); + typeMapping.put("float", "Float"); + typeMapping.put("byte", "Byte"); + typeMapping.put("short", "Short"); + typeMapping.put("char", "Char"); + typeMapping.put("double", "Double"); + typeMapping.put("object", "Any"); + typeMapping.put("file", "File"); + typeMapping.put("binary", "File"); + typeMapping.put("number", "Double"); + + instantiationTypes.put("array", "ListBuffer"); + instantiationTypes.put("map", "Map"); + + supportingFiles.add(new SupportingFile("README.mustache", "", "README.md")); + } + + @Override + public void processOpts() { + super.processOpts(); + + if (additionalProperties.containsKey(CodegenConstants.INVOKER_PACKAGE)) { + invokerPackage = (String) additionalProperties.get(CodegenConstants.INVOKER_PACKAGE); + } else { + additionalProperties.put(CodegenConstants.INVOKER_PACKAGE, invokerPackage); + } + + if (additionalProperties.containsKey(CodegenConstants.GROUP_ID)) { + groupId = (String) additionalProperties.get(CodegenConstants.GROUP_ID); + } else { + additionalProperties.put(CodegenConstants.GROUP_ID, groupId); + } + + if (additionalProperties.containsKey(CodegenConstants.ARTIFACT_ID)) { + artifactId = (String) additionalProperties.get(CodegenConstants.ARTIFACT_ID); + } else { + additionalProperties.put(CodegenConstants.ARTIFACT_ID, artifactId); + } + + if (additionalProperties.containsKey(CodegenConstants.ARTIFACT_VERSION)) { + artifactVersion = (String) additionalProperties.get(CodegenConstants.ARTIFACT_VERSION); + } else { + additionalProperties.put(CodegenConstants.ARTIFACT_VERSION, artifactVersion); + } + + if (additionalProperties.containsKey(AKKA_HTTP_VERSION)) { + akkaHttpVersion = (String) additionalProperties.get(AKKA_HTTP_VERSION); + } else { + additionalProperties.put(AKKA_HTTP_VERSION, akkaHttpVersion); + } + + parseAkkaHttpVersion(); + + supportingFiles.add(new SupportingFile("build.sbt.mustache", "", "build.sbt")); + supportingFiles.add(new SupportingFile("controller.mustache", + (sourceFolder + File.separator + invokerPackage).replace(".", java.io.File.separator), "Controller.scala")); + supportingFiles.add(new SupportingFile("helper.mustache", + (sourceFolder + File.separator + invokerPackage).replace(".", java.io.File.separator), "AkkaHttpHelper.scala")); + supportingFiles.add(new SupportingFile("stringDirectives.mustache", + (sourceFolder + File.separator + invokerPackage).replace(".", java.io.File.separator), "StringDirectives.scala")); + supportingFiles.add(new SupportingFile("multipartDirectives.mustache", + (sourceFolder + File.separator + invokerPackage).replace(".", java.io.File.separator), "MultipartDirectives.scala")); + } + + private static final String IS_10_1_10_PLUS = "akkaHttp10_1_10_plus"; + private boolean is10_1_10AndAbove = false; + + private static final Pattern akkaVersionPattern = Pattern.compile("([0-9]+)(\\.([0-9]+))?(\\.([0-9]+))?(.\\+)?"); + + private void parseAkkaHttpVersion() { + Matcher matcher = akkaVersionPattern.matcher(akkaHttpVersion); + if (matcher.matches()) { + String majorS = matcher.group(1); + String minorS = matcher.group(3); + String patchS = matcher.group(5); + boolean andAbove = matcher.group(6) != null; + int major = -1, minor = -1, patch = -1; + try { + if (majorS != null) { + major = Integer.parseInt(majorS); + if (minorS != null) { + minor = Integer.parseInt(minorS); + if (patchS != null) { + patch = Integer.parseInt(patchS); + } + } + } + + + if (major > 10 || major == -1 && andAbove) { + is10_1_10AndAbove = true; + } else if (major == 10) { + if (minor > 1 || minor == -1 && andAbove) { + is10_1_10AndAbove = true; + } else if (minor == 1) { + if (patch >= 10 || patch == -1 && andAbove) { + is10_1_10AndAbove = true; + } + } + } + + } catch (NumberFormatException e) { + LOGGER.warn("Unable to parse " + AKKA_HTTP_VERSION + ": " + akkaHttpVersion + ", fallback to " + DEFAULT_AKKA_HTTP_VERSION); + akkaHttpVersion = DEFAULT_AKKA_HTTP_VERSION; + is10_1_10AndAbove = true; + } + } + + additionalProperties.put(IS_10_1_10_PLUS, is10_1_10AndAbove); + } + + @Override + public CodegenOperation fromOperation(String path, String httpMethod, Operation operation, List servers) { + CodegenOperation codegenOperation = super.fromOperation(path, httpMethod, operation, servers); + addPathMatcher(codegenOperation); + return codegenOperation; + } + + @Override + public CodegenParameter fromParameter(Parameter parameter, Set imports) { + CodegenParameter param = super.fromParameter(parameter, imports); + // Removing unhandled types + if (!primitiveParamTypes.contains(param.dataType)) { + param.dataType = "String"; + } + if (!param.required) { + param.vendorExtensions.put("x-has-default-value", param.defaultValue != null); + // Escaping default string values + if (param.defaultValue != null && param.dataType.equals("String")) { + param.defaultValue = String.format(Locale.ROOT, "\"%s\"", param.defaultValue); + } + } + return param; + } + + + @Override + public Map postProcessOperationsWithModels(Map objs, List allModels) { + Map baseObjs = super.postProcessOperationsWithModels(objs, allModels); + pathMatcherPatternsPostProcessor(baseObjs); + marshallingPostProcessor(baseObjs); + return baseObjs; + } + + private static Set primitiveParamTypes = new HashSet() {{ + addAll(Arrays.asList( + "Int", + "Long", + "Float", + "Double", + "Boolean", + "String" + )); + }}; + + private static Map pathTypeToMatcher = new HashMap() {{ + put("Int", "IntNumber"); + put("Long", "LongNumber"); + put("Float", "FloatNumber"); + put("Double", "DoubleNumber"); + put("Boolean", "Boolean"); + put("String", "Segment"); + }}; + + protected static void addPathMatcher(CodegenOperation codegenOperation) { + LinkedList allPaths = new LinkedList<>(Arrays.asList(codegenOperation.path.split("/"))); + allPaths.removeIf(""::equals); + + LinkedList pathMatchers = new LinkedList<>(); + for (String path : allPaths) { + TextOrMatcher textOrMatcher = new TextOrMatcher("", true, true); + if (path.startsWith("{") && path.endsWith("}")) { + String parameterName = path.substring(1, path.length() - 1); + for (CodegenParameter pathParam : codegenOperation.pathParams) { + if (pathParam.baseName.equals(parameterName)) { + String matcher = pathTypeToMatcher.get(pathParam.dataType); + if (matcher == null) { + LOGGER.warn("The path parameter " + pathParam.baseName + + " with the datatype " + pathParam.dataType + + " could not be translated to a corresponding path matcher of akka http" + + " and therefore has been translated to string."); + matcher = pathTypeToMatcher.get("String"); + } + if (pathParam.pattern != null && !pathParam.pattern.isEmpty()) { + matcher = pathMatcherPatternName(pathParam); + } + textOrMatcher.value = matcher; + textOrMatcher.isText = false; + pathMatchers.add(textOrMatcher); + } + } + } else { + textOrMatcher.value = path; + textOrMatcher.isText = true; + pathMatchers.add(textOrMatcher); + } + } + pathMatchers.getLast().hasMore = false; + + codegenOperation.vendorExtensions.put("x-paths", pathMatchers); + } + + public static String PATH_MATCHER_PATTERNS_KEY = "pathMatcherPatterns"; + + @SuppressWarnings("unchecked") + private static void pathMatcherPatternsPostProcessor(Map objs) { + if (objs != null) { + HashMap patternMap = new HashMap<>(); + Map operations = (Map) objs.get("operations"); + if (operations != null) { + List ops = (List) operations.get("operation"); + for (CodegenOperation operation : ops) { + for (CodegenParameter parameter : operation.pathParams) { + if (parameter.pattern != null && !parameter.pattern.isEmpty()) { + String name = pathMatcherPatternName(parameter); + if (!patternMap.containsKey(name)) { + patternMap.put(name, new PathMatcherPattern(name, parameter.pattern.substring(1, parameter.pattern.length() - 1))); + } + } + } + } + } + objs.put(PATH_MATCHER_PATTERNS_KEY, new ArrayList<>(patternMap.values())); + } + } + + private static String pathMatcherPatternName(CodegenParameter parameter) { + return parameter.paramName + "Pattern"; + } + + // Responsible for setting up Marshallers/Unmarshallers + @SuppressWarnings("unchecked") + public static void marshallingPostProcessor(Map objs) { + + if (objs == null) { + return; + } + + Set entityUnmarshallerTypes = new HashSet<>(); + Set entityMarshallerTypes = new HashSet<>(); + Set stringUnmarshallerTypes = new HashSet<>(); + boolean hasCookieParams = false; + boolean hasMultipart = false; + + Map operations = (Map) objs.get("operations"); + if (operations != null) { + List operationList = (List) operations.get("operation"); + + for (CodegenOperation op : operationList) { + boolean isMultipart = op.isMultipart; + hasMultipart |= isMultipart; + hasCookieParams |= op.getHasCookieParams(); + ArrayList fileParams = new ArrayList<>(); + ArrayList nonFileParams = new ArrayList<>(); + for (CodegenParameter parameter : op.allParams) { + if (parameter.isBodyParam || parameter.isFormParam) { + if (parameter.isFile) { + fileParams.add(parameter.copy()); + } else { + nonFileParams.add(parameter.copy()); + } + if (!parameter.isPrimitiveType) { + if (isMultipart) { + stringUnmarshallerTypes.add(new Marshaller(parameter)); + } else { + entityUnmarshallerTypes.add(new Marshaller(parameter)); + } + } + } + } + for (int i = 0, size = fileParams.size(); i < size; ++i) { + fileParams.get(i).hasMore = i < size - 1; + } + for (int i = 0, size = nonFileParams.size(); i < size; ++i) { + nonFileParams.get(i).hasMore = i < size - 1; + } + + HashSet operationSpecificMarshallers = new HashSet<>(); + for (CodegenResponse response : op.responses) { + if (!response.primitiveType) { + Marshaller marshaller = new Marshaller(response); + entityMarshallerTypes.add(marshaller); + operationSpecificMarshallers.add(marshaller); + } + response.vendorExtensions.put("x-empty-response", response.baseType == null && response.message == null); + response.vendorExtensions.put("x-is-default", response.code.equals("0")); + } + op.vendorExtensions.put("x-specific-marshallers", operationSpecificMarshallers); + op.vendorExtensions.put("x-file-params", fileParams); + op.vendorExtensions.put("x-non-file-params", nonFileParams); + } + } + + objs.put("hasCookieParams", hasCookieParams); + objs.put("entityMarshallers", entityMarshallerTypes); + objs.put("entityUnmarshallers", entityUnmarshallerTypes); + objs.put("stringUnmarshallers", stringUnmarshallerTypes); + objs.put("hasMarshalling", !entityMarshallerTypes.isEmpty() || !entityUnmarshallerTypes.isEmpty() || !stringUnmarshallerTypes.isEmpty()); + objs.put("hasMultipart", hasMultipart); + } + +} + +class Marshaller { + String varName; + String dataType; + + public Marshaller(CodegenResponse response) { + if (response.containerType != null) { + this.varName = response.baseType + response.containerType; + } else { + this.varName = response.baseType; + } + this.dataType = response.dataType; + } + + public Marshaller(CodegenParameter parameter) { + if (parameter.isListContainer) { + this.varName = parameter.baseType + "List"; + } else if (parameter.isMapContainer) { + this.varName = parameter.baseType + "Map"; + } else if (parameter.isContainer) { + this.varName = parameter.baseType + "Container"; + } else { + this.varName = parameter.baseType; + } + this.dataType = parameter.dataType; + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + Marshaller that = (Marshaller) o; + return varName.equals(that.varName) && + dataType.equals(that.dataType); + } + + @Override + public int hashCode() { + return Objects.hash(varName, dataType); + } +} + +class PathMatcherPattern { + String pathMatcherVarName; + String pattern; + + public PathMatcherPattern(String pathMatcherVarName, String pattern) { + this.pathMatcherVarName = pathMatcherVarName; + this.pattern = pattern; + } +} + +class TextOrMatcher { + String value; + boolean isText; + boolean hasMore; + + public TextOrMatcher(String value, boolean isText, boolean hasMore) { + this.value = value; + this.isText = isText; + this.hasMore = hasMore; + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + TextOrMatcher that = (TextOrMatcher) o; + return isText == that.isText && + hasMore == that.hasMore && + value.equals(that.value); + } + + @Override + public int hashCode() { + return Objects.hash(value, isText, hasMore); + } +} diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/ScalaSttpClientCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/ScalaSttpClientCodegen.java index dd1e88468602..43b48cb3114b 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/ScalaSttpClientCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/ScalaSttpClientCodegen.java @@ -28,8 +28,6 @@ import java.util.List; public class ScalaSttpClientCodegen extends ScalaAkkaClientCodegen implements CodegenConfig { - protected String mainPackage = "org.openapitools.client"; - public ScalaSttpClientCodegen() { super(); generatorMetadata = GeneratorMetadata.newBuilder(generatorMetadata) diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/SpringCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/SpringCodegen.java index 8450fbd5f4de..4daf182d0f93 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/SpringCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/SpringCodegen.java @@ -652,7 +652,7 @@ private void doDataTypeAssignment(String returnType, DataTypeAssigner dataTypeAs } else if (rt.startsWith("Map")) { int end = rt.lastIndexOf(">"); if (end > 0) { - dataTypeAssigner.setReturnType(rt.substring("Map<".length(), end).split(",")[1].trim()); + dataTypeAssigner.setReturnType(rt.substring("Map<".length(), end).split(",", 2)[1].trim()); dataTypeAssigner.setReturnContainer("Map"); } } else if (rt.startsWith("Set")) { diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/Swift5ClientCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/Swift5ClientCodegen.java index b660a83dcb2f..445069455d49 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/Swift5ClientCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/Swift5ClientCodegen.java @@ -53,6 +53,7 @@ public class Swift5ClientCodegen extends DefaultCodegen implements CodegenConfig public static final String POD_DESCRIPTION = "podDescription"; public static final String POD_SCREENSHOTS = "podScreenshots"; public static final String POD_DOCUMENTATION_URL = "podDocumentationURL"; + public static final String READONLY_PROPERTIES = "readonlyProperties"; public static final String SWIFT_USE_API_NAMESPACE = "swiftUseApiNamespace"; public static final String DEFAULT_POD_AUTHORS = "OpenAPI Generator"; public static final String LENIENT_TYPE_CAST = "lenientTypeCast"; @@ -67,6 +68,7 @@ public class Swift5ClientCodegen extends DefaultCodegen implements CodegenConfig protected boolean nonPublicApi = false; protected boolean objcCompatible = false; protected boolean lenientTypeCast = false; + protected boolean readonlyProperties = false; protected boolean swiftUseApiNamespace; protected String[] responseAs = new String[0]; protected String sourceFolder = "Classes" + File.separator + "OpenAPIs"; @@ -237,6 +239,8 @@ public Swift5ClientCodegen() { cliOptions.add(new CliOption(POD_SCREENSHOTS, "Screenshots used for Podspec")); cliOptions.add(new CliOption(POD_DOCUMENTATION_URL, "Documentation URL used for Podspec")); + cliOptions.add(new CliOption(READONLY_PROPERTIES, "Make properties " + + "readonly (default: false)")); cliOptions.add(new CliOption(SWIFT_USE_API_NAMESPACE, "Flag to make all the API classes inner-class " + "of {{projectName}}API")); @@ -392,6 +396,13 @@ public void processOpts() { additionalProperties.put("useCombine", true); } + // Setup readonlyProperties option, which declares properties so they can only + // be set at initialization + if (additionalProperties.containsKey(READONLY_PROPERTIES)) { + setReadonlyProperties(convertPropertyToBooleanAndWriteBack(READONLY_PROPERTIES)); + } + additionalProperties.put(READONLY_PROPERTIES, readonlyProperties); + // Setup swiftUseApiNamespace option, which makes all the API // classes inner-class of {{projectName}}API if (additionalProperties.containsKey(SWIFT_USE_API_NAMESPACE)) { @@ -777,6 +788,10 @@ public void setLenientTypeCast(boolean lenientTypeCast) { this.lenientTypeCast = lenientTypeCast; } + public void setReadonlyProperties(boolean readonlyProperties) { + this.readonlyProperties = readonlyProperties; + } + public void setResponseAs(String[] responseAs) { this.responseAs = responseAs; } diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/TypeScriptAxiosClientCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/TypeScriptAxiosClientCodegen.java index a441027bff06..1b6e80926395 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/TypeScriptAxiosClientCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/TypeScriptAxiosClientCodegen.java @@ -110,6 +110,7 @@ public void processOpts() { supportingFiles.add(new SupportingFile("configuration.mustache", "", "configuration.ts")); supportingFiles.add(new SupportingFile("git_push.sh.mustache", "", "git_push.sh")); supportingFiles.add(new SupportingFile("gitignore", "", ".gitignore")); + supportingFiles.add(new SupportingFile("npmignore", "", ".npmignore")); if (additionalProperties.containsKey(SEPARATE_MODELS_AND_API)) { boolean separateModelsAndApi = Boolean.parseBoolean(additionalProperties.get(SEPARATE_MODELS_AND_API).toString()); @@ -216,6 +217,15 @@ public Map postProcessModels(Map objs) { return objs; } + /** + * Overriding toRegularExpression() to avoid escapeText() being called, + * as it would return a broken regular expression if any escaped character / metacharacter were present. + */ + @Override + public String toRegularExpression(String pattern) { + return addRegularExpressionDelimiter(pattern); + } + @Override public String toModelFilename(String name) { return super.toModelFilename(name).replaceAll("([a-z0-9])([A-Z])", "$1-$2").toLowerCase(Locale.ROOT); diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/TypeScriptFetchClientCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/TypeScriptFetchClientCodegen.java index b1ab5e4fa818..208d42834eb7 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/TypeScriptFetchClientCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/TypeScriptFetchClientCodegen.java @@ -17,11 +17,14 @@ package org.openapitools.codegen.languages; +import com.google.common.collect.ImmutableMap; +import com.samskivert.mustache.Mustache; import io.swagger.v3.oas.models.media.ArraySchema; import io.swagger.v3.oas.models.media.Schema; import io.swagger.v3.parser.util.SchemaTypeUtil; import org.openapitools.codegen.*; import org.openapitools.codegen.meta.features.DocumentationFeature; +import org.openapitools.codegen.templating.mustache.IndentedLambda; import org.openapitools.codegen.utils.ModelUtils; import java.io.File; @@ -134,6 +137,14 @@ public void processOpts() { } } + @Override + protected ImmutableMap.Builder addMustacheLambdas() { + ImmutableMap.Builder lambdas = super.addMustacheLambdas(); + lambdas.put("indented_star_1", new IndentedLambda(1, " ", "* ")); + lambdas.put("indented_star_4", new IndentedLambda(5, " ", "* ")); + return lambdas; + } + @Override public String getTypeDeclaration(Schema p) { if (ModelUtils.isFileSchema(p)) { @@ -235,9 +246,38 @@ public Map postProcessOperationsWithModels(Map o this.updateOperationParameterEnumInformation(operations); this.addOperationObjectResponseInformation(operations); this.addOperationPrefixParameterInterfacesInformation(operations); + this.escapeOperationIds(operations); + this.addDeepObjectVendorExtension(operations); return operations; } + private void addDeepObjectVendorExtension(Map operations) { + Map _operations = (Map) operations.get("operations"); + List operationList = (List) _operations.get("operation"); + + for (CodegenOperation op : operationList) { + for (CodegenParameter param : op.queryParams) { + if (param.style != null && param.style.equals("deepObject")) { + param.vendorExtensions.put("x-codegen-isDeepObject", true); + } + } + } + } + + private void escapeOperationIds(Map operations) { + Map _operations = (Map) operations.get("operations"); + List operationList = (List) _operations.get("operation"); + for (CodegenOperation op : operationList) { + String param = op.operationIdCamelCase + "Request"; + if (op.imports.contains(param)) { + // we import a model with the same name as the generated operation, escape it + op.operationIdCamelCase += "Operation"; + op.operationIdLowerCase += "operation"; + op.operationIdSnakeCase += "_operation"; + } + } + } + private void addOperationModelImportInfomation(Map operations) { // This method will add extra infomation to the operations.imports array. // The api template uses this infomation to import all the required @@ -312,6 +352,9 @@ private void addExtraReservedWords() { this.reservedWords.add("VoidApiResponse"); this.reservedWords.add("BlobApiResponse"); this.reservedWords.add("TextApiResponse"); + // "Index" would create a file "Index.ts" which on case insensitive filesystems + // would override our "index.js" file + this.reservedWords.add("Index"); } private boolean getUseSingleRequestParameter() { diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/serializer/SerializerUtils.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/serializer/SerializerUtils.java index 16a8af68a7e1..833ad2e24180 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/serializer/SerializerUtils.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/serializer/SerializerUtils.java @@ -2,25 +2,38 @@ import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.MapperFeature; +import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.module.SimpleModule; -import io.swagger.v3.core.util.Yaml; +import com.fasterxml.jackson.dataformat.yaml.YAMLFactory; +import com.fasterxml.jackson.dataformat.yaml.YAMLGenerator; import io.swagger.v3.core.util.Json; +import io.swagger.v3.core.util.Yaml; import io.swagger.v3.oas.models.OpenAPI; +import org.openapitools.codegen.config.GlobalSettings; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class SerializerUtils { private static final Logger LOGGER = LoggerFactory.getLogger(SerializerUtils.class); + private static final String YAML_MINIMIZE_QUOTES_PROPERTY = "org.openapitools.codegen.utils.yaml.minimize.quotes"; + private static final boolean minimizeYamlQuotes = Boolean.parseBoolean(GlobalSettings.getProperty(YAML_MINIMIZE_QUOTES_PROPERTY, "true")); public static String toYamlString(OpenAPI openAPI) { - if(openAPI == null) { + if (openAPI == null) { return null; } SimpleModule module = createModule(); try { - return Yaml.mapper() - .copy() - .registerModule(module) + ObjectMapper yamlMapper = Yaml.mapper().copy(); + // there is an unfortunate YAML condition where user inputs should be treated as strings (e.g. "1234_1234"), but in yaml this is a valid number and + // removing quotes forcibly by default means we are potentially doing a data conversion resulting in an unexpected change to the user's YAML outputs. + // We may allow for property-based enable/disable, retaining the default of enabled for backward compatibility. + if (minimizeYamlQuotes) { + ((YAMLFactory) yamlMapper.getFactory()).enable(YAMLGenerator.Feature.MINIMIZE_QUOTES); + } else { + ((YAMLFactory) yamlMapper.getFactory()).disable(YAMLGenerator.Feature.MINIMIZE_QUOTES); + } + return yamlMapper.registerModule(module) .configure(MapperFeature.SORT_PROPERTIES_ALPHABETICALLY, true) .writeValueAsString(openAPI) .replace("\r\n", "\n"); @@ -34,7 +47,7 @@ public static String toJsonString(OpenAPI openAPI) { if (openAPI == null) { return null; } - + SimpleModule module = createModule(); try { return Json.mapper() diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/utils/ModelUtils.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/utils/ModelUtils.java index 44373cd8c3bd..7092f2961715 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/utils/ModelUtils.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/utils/ModelUtils.java @@ -118,7 +118,7 @@ public static List getAllUsedSchemas(OpenAPI openAPI) { * @return schemas a list of unused schemas */ public static List getUnusedSchemas(OpenAPI openAPI) { - final Map> childrenMap; + final Map> childrenMap; Map> tmpChildrenMap; try { tmpChildrenMap = getChildrenMap(openAPI); @@ -661,7 +661,7 @@ public static boolean isModel(Schema schema) { * Return true if the schema value can be any type, i.e. it can be * the null value, integer, number, string, object or array. * One use case is when the "type" attribute in the OAS schema is unspecified. - * + * * Examples: * * arbitraryTypeValue: @@ -675,13 +675,19 @@ public static boolean isModel(Schema schema) { * nullable: true * * @param schema the OAS schema. - * @return true if the schema value can be an arbitrary type. + * @return true if the schema value can be an arbitrary type. */ public static boolean isAnyTypeSchema(Schema schema) { if (schema == null) { once(LOGGER).error("Schema cannot be null in isAnyTypeSchema check"); return false; } + + if (isFreeFormObject(schema)) { + // make sure it's not free form object + return false; + } + if (schema.getClass().equals(Schema.class) && schema.get$ref() == null && schema.getType() == null && (schema.getProperties() == null || schema.getProperties().isEmpty()) && schema.getAdditionalProperties() == null && schema.getNot() == null && @@ -702,7 +708,7 @@ public static boolean isAnyTypeSchema(Schema schema) { * 3) additionalproperties is not defined, or additionalproperties: true, or additionalproperties: {}. * * Examples: - * + * * components: * schemas: * arbitraryObject: @@ -719,7 +725,7 @@ public static boolean isAnyTypeSchema(Schema schema) { * arbitraryTypeValue: * description: This is NOT a free-form object. * The value can be any type except the 'null' value. - * + * * @param schema potentially containing a '$ref' * @return true if it's a free-form object */ @@ -754,6 +760,11 @@ public static boolean isFreeFormObject(Schema schema) { if (objSchema.getProperties() == null || objSchema.getProperties().isEmpty()) { return true; } + } else if (addlProps instanceof Schema) { + // additionalProperties defined as {} + if (addlProps.getType() == null && (addlProps.getProperties() == null || addlProps.getProperties().isEmpty())) { + return true; + } } } } @@ -985,8 +996,8 @@ private static Schema getSchemaFromContent(Content content) { if (content.size() > 1) { // Other content types are currently ignored by codegen. If you see this warning, // reorder the OAS spec to put the desired content type first. - LOGGER.warn("Multiple schemas found in the OAS 'content' section, returning only the first one ({})", - entry.getKey()); + once(LOGGER).warn("Multiple schemas found in the OAS 'content' section, returning only the first one ({})", + entry.getKey()); } return entry.getValue().getSchema(); } @@ -1104,10 +1115,10 @@ public static Header getHeader(OpenAPI openAPI, String name) { public static Map> getChildrenMap(OpenAPI openAPI) { Map allSchemas = getSchemas(openAPI); - // FIXME: The collect here will throw NPE if a spec document has only a single oneOf hierarchy. Map>> groupedByParent = allSchemas.entrySet().stream() - .filter(entry -> isComposedSchema(entry.getValue())) - .collect(Collectors.groupingBy(entry -> getParentName((ComposedSchema) entry.getValue(), allSchemas))); + .filter(entry -> isComposedSchema(entry.getValue())) + .filter(entry -> getParentName((ComposedSchema) entry.getValue(), allSchemas)!=null) + .collect(Collectors.groupingBy(entry -> getParentName((ComposedSchema) entry.getValue(), allSchemas))); return groupedByParent.entrySet().stream() .collect(Collectors.toMap(entry -> entry.getKey(), entry -> entry.getValue().stream().map(e -> e.getKey()).collect(Collectors.toList()))); @@ -1165,14 +1176,6 @@ public static String getParentName(ComposedSchema composedSchema, Map refedWithoutDiscriminator = new ArrayList<>(); - String schemaName = ""; - for (String thisSchemaName : allSchemas.keySet()) { - Schema sc = allSchemas.get(thisSchemaName); - if (isComposedSchema(sc) && (ComposedSchema) sc == composedSchema) { - schemaName = thisSchemaName; - break; - } - } if (interfaces != null && !interfaces.isEmpty()) { for (Schema schema : interfaces) { @@ -1189,10 +1192,7 @@ public static String getParentName(ComposedSchema composedSchema, Map getAllParentsName(ComposedSchema composedSchema, Map allSchemas, boolean includeAncestors) { List interfaces = getInterfaces(composedSchema); List names = new ArrayList(); - List refedWithoutDiscriminator = new ArrayList<>(); if (interfaces != null && !interfaces.isEmpty()) { for (Schema schema : interfaces) { @@ -1255,7 +1254,6 @@ public static List getAllParentsName(ComposedSchema composedSchema, Map< } } else { // not a parent since discriminator.propertyName is not set - refedWithoutDiscriminator.add(parentName); } } else { // not a ref, doing nothing @@ -1263,10 +1261,11 @@ public static List getAllParentsName(ComposedSchema composedSchema, Map< } } - if (names.size() == 0 && refedWithoutDiscriminator.size() == 1) { - LOGGER.warn("[deprecated] inheritance without use of 'discriminator.propertyName' is deprecated " + - "and will be removed in a future release. Generating model for {}. Title: {}", composedSchema.getName(), composedSchema.getTitle()); - return refedWithoutDiscriminator; + // ensure `allParents` always includes `parent` + // this is more robust than keeping logic in getParentName() and getAllParentsName() in sync + String parentName = getParentName(composedSchema, allSchemas); + if (parentName != null && !names.contains(parentName)) { + names.add(parentName); } return names; @@ -1281,12 +1280,10 @@ else if (StringUtils.isNotEmpty(schema.get$ref())) { Schema s = allSchemas.get(parentName); if (s != null) { return hasOrInheritsDiscriminator(s, allSchemas); - } - else { + } else { LOGGER.error("Failed to obtain schema from {}", parentName); } - } - else if (schema instanceof ComposedSchema) { + } else if (schema instanceof ComposedSchema) { final ComposedSchema composed = (ComposedSchema) schema; final List interfaces = getInterfaces(composed); for (Schema i : interfaces) { @@ -1388,7 +1385,7 @@ public static boolean isNullType(Schema schema) { return false; } - public static void syncValidationProperties(Schema schema, IJsonSchemaValidationProperties target){ + public static void syncValidationProperties(Schema schema, IJsonSchemaValidationProperties target) { if (schema != null && target != null) { target.setPattern(schema.getPattern()); BigDecimal minimum = schema.getMinimum(); diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/utils/StringUtils.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/utils/StringUtils.java index a0a4acd7ebaa..8f70d05b9e80 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/utils/StringUtils.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/utils/StringUtils.java @@ -5,6 +5,7 @@ import com.github.benmanes.caffeine.cache.Ticker; import org.apache.commons.lang3.tuple.ImmutablePair; import org.apache.commons.lang3.tuple.Pair; +import org.openapitools.codegen.config.GlobalSettings; import java.util.List; import java.util.Locale; @@ -16,6 +17,15 @@ public class StringUtils { + /** + * Set the cache size (entry count) of the sanitizedNameCache, camelizedWordsCache and underscoreWords. + */ + public static final String NAME_CACHE_SIZE_PROPERTY = "org.openapitools.codegen.utils.namecache.cachesize"; + /** + * Set the cache expiry (in seconds) of the sanitizedNameCache, camelizedWordsCache and underscoreWords. + */ + public static final String NAME_CACHE_EXPIRY_PROPERTY = "org.openapitools.codegen.utils.namecache.expireafter.seconds"; + // A cache of camelized words. The camelize() method is invoked many times with the same // arguments, this cache is used to optimized performance. private static Cache, String> camelizedWordsCache; @@ -23,15 +33,17 @@ public class StringUtils { // A cache of underscored words, used to optimize the performance of the underscore() method. private static Cache underscoreWords; static { + int cacheSize = Integer.parseInt(GlobalSettings.getProperty(NAME_CACHE_SIZE_PROPERTY, "200")); + int cacheExpiry = Integer.parseInt(GlobalSettings.getProperty(NAME_CACHE_EXPIRY_PROPERTY, "5")); camelizedWordsCache = Caffeine.newBuilder() - .maximumSize(200) - .expireAfterAccess(5, TimeUnit.SECONDS) + .maximumSize(cacheSize) + .expireAfterAccess(cacheExpiry, TimeUnit.SECONDS) .ticker(Ticker.systemTicker()) .build(); underscoreWords = Caffeine.newBuilder() - .maximumSize(200) - .expireAfterAccess(5, TimeUnit.SECONDS) + .maximumSize(cacheSize) + .expireAfterAccess(cacheExpiry, TimeUnit.SECONDS) .ticker(Ticker.systemTicker()) .build(); } diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/validations/oas/OpenApiEvaluator.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/validations/oas/OpenApiEvaluator.java index 5cbe4c9eb894..56097b74d0fd 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/validations/oas/OpenApiEvaluator.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/validations/oas/OpenApiEvaluator.java @@ -6,12 +6,11 @@ import io.swagger.v3.oas.models.media.Schema; import io.swagger.v3.oas.models.parameters.Parameter; import io.swagger.v3.oas.models.security.SecurityScheme; +import io.swagger.v3.oas.models.tags.Tag; import org.openapitools.codegen.utils.ModelUtils; import org.openapitools.codegen.validation.*; -import java.util.ArrayList; -import java.util.List; -import java.util.Map; +import java.util.*; /** * A validator which evaluates an OpenAPI 3.x specification document @@ -101,6 +100,27 @@ public ValidationResult validate(OpenAPI specification) { validationResult.consume(parameterValidations.validate(wrapper)); }); + List tags = specification.getTags(); + if (tags != null && tags.size() > 1) { + Set distinct = new HashSet<>(); + Set duplicated = new HashSet<>(); + tags.forEach(tag -> { + // add returns false if it already exists… + if (!distinct.add(tag.getName())) { + duplicated.add(tag.getName()); + } + }); + if (duplicated.size() > 0) { + // From https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.2.md#fixed-fields + // A list of tags used by the specification with additional metadata. The order of the tags can be used + // to reflect on their order by the parsing tools. Not all tags that are used by the Operation Object + // must be declared. The tags that are not declared MAY be organized randomly or based on the tools' + // logic. Each tag name in the list MUST be unique. + ValidationRule rule = ValidationRule.warn("Duplicate tags", "The specification requires that tag names are unique.", s -> ValidationRule.Fail.empty()); + validationResult.addResult(Validated.invalid(rule, "Duplicated tag(s): " + String.join(",", duplicated))); + } + } + return validationResult; } } diff --git a/modules/openapi-generator/src/main/resources/C-libcurl/CMakeLists.txt.mustache b/modules/openapi-generator/src/main/resources/C-libcurl/CMakeLists.txt.mustache index 76c0470f008b..41e5faf3e662 100644 --- a/modules/openapi-generator/src/main/resources/C-libcurl/CMakeLists.txt.mustache +++ b/modules/openapi-generator/src/main/resources/C-libcurl/CMakeLists.txt.mustache @@ -8,6 +8,19 @@ set(CMAKE_CXX_VISIBILITY_PRESET default) set(CMAKE_VISIBILITY_INLINES_HIDDEN OFF) set(CMAKE_BUILD_TYPE Debug) +find_package(OpenSSL) + +if (OPENSSL_FOUND) + message (STATUS "OPENSSL found") + set (CMAKE_C_FLAGS "-DOPENSSL") + include_directories(${OPENSSL_INCLUDE_DIR}) + include_directories(${OPENSSL_INCLUDE_DIRS}) + link_directories(${OPENSSL_LIBRARIES}) + message(STATUS "Using OpenSSL ${OPENSSL_VERSION}") +else() + message (STATUS "OpenSSL Not found.") +endif() + set(pkgName "{{projectName}}") find_package(CURL 7.58.0 REQUIRED) @@ -22,6 +35,7 @@ set(SRCS src/list.c src/apiKey.c src/apiClient.c + src/binary.c external/cJSON.c model/object.c {{#models}} @@ -42,6 +56,7 @@ set(SRCS set(HDRS include/apiClient.h include/list.h + include/binary.h include/keyValuePair.h external/cJSON.h model/object.h diff --git a/modules/openapi-generator/src/main/resources/C-libcurl/api-body.mustache b/modules/openapi-generator/src/main/resources/C-libcurl/api-body.mustache index d2016014fad0..58443cabc3a0 100644 --- a/modules/openapi-generator/src/main/resources/C-libcurl/api-body.mustache +++ b/modules/openapi-generator/src/main/resources/C-libcurl/api-body.mustache @@ -373,6 +373,8 @@ end: {{/returnTypeIsPrimitive}} if (apiClient->dataReceived) { free(apiClient->dataReceived); + apiClient->dataReceived = NULL; + apiClient->dataReceivedLen = 0; } {{#hasQueryParams}}list_free(localVarQueryParameters);{{/hasQueryParams}} {{#hasHeaderParams}}list_free(localVarHeaderParameters);{{/hasHeaderParams}} @@ -463,6 +465,8 @@ end: end: if (apiClient->dataReceived) { free(apiClient->dataReceived); + apiClient->dataReceived = NULL; + apiClient->dataReceivedLen = 0; } {{#hasQueryParams}}list_free(localVarQueryParameters);{{/hasQueryParams}} {{#hasHeaderParams}}list_free(localVarHeaderParameters);{{/hasHeaderParams}} diff --git a/modules/openapi-generator/src/main/resources/C-libcurl/api-header.mustache b/modules/openapi-generator/src/main/resources/C-libcurl/api-header.mustache index 6247c6d97dca..7631aa03554c 100644 --- a/modules/openapi-generator/src/main/resources/C-libcurl/api-header.mustache +++ b/modules/openapi-generator/src/main/resources/C-libcurl/api-header.mustache @@ -4,6 +4,7 @@ #include "../include/list.h" #include "../external/cJSON.h" #include "../include/keyValuePair.h" +#include "../include/binary.h" {{#imports}}{{{import}}} {{/imports}} diff --git a/modules/openapi-generator/src/main/resources/C-libcurl/apiClient.c.mustache b/modules/openapi-generator/src/main/resources/C-libcurl/apiClient.c.mustache index b9cd08f40b62..c4bb4cf0e0cf 100644 --- a/modules/openapi-generator/src/main/resources/C-libcurl/apiClient.c.mustache +++ b/modules/openapi-generator/src/main/resources/C-libcurl/apiClient.c.mustache @@ -3,9 +3,6 @@ #include #include #include "../include/apiClient.h" -#ifdef OPENSSL -#include "openssl/pem.h" -#endif size_t writeDataCallback(void *buffer, size_t size, size_t nmemb, void *userp); @@ -15,6 +12,7 @@ apiClient_t *apiClient_create() { apiClient->basePath = strdup("{{{basePath}}}"); apiClient->sslConfig = NULL; apiClient->dataReceived = NULL; + apiClient->dataReceivedLen = 0; apiClient->response_code = 0; {{#hasAuthMethods}} {{#authMethods}} @@ -26,7 +24,7 @@ apiClient_t *apiClient_create() { apiClient->accessToken = NULL; {{/isOAuth}} {{#isApiKey}} - apiClient->apiKeys = NULL; + apiClient->apiKeys_{{name}} = NULL; {{/isApiKey}} {{/authMethods}} {{/hasAuthMethods}} @@ -39,7 +37,7 @@ apiClient_t *apiClient_create_with_base_path(const char *basePath {{#hasAuthMethods}} {{#authMethods}} {{#isApiKey}} -, list_t *apiKeys +, list_t *apiKeys_{{name}} {{/isApiKey}} {{/authMethods}} {{/hasAuthMethods}} @@ -59,6 +57,7 @@ apiClient_t *apiClient_create_with_base_path(const char *basePath } apiClient->dataReceived = NULL; + apiClient->dataReceivedLen = 0; apiClient->response_code = 0; {{#hasAuthMethods}} {{#authMethods}} @@ -70,16 +69,16 @@ apiClient_t *apiClient_create_with_base_path(const char *basePath apiClient->accessToken = NULL; {{/isOAuth}} {{#isApiKey}} - if(apiKeys!= NULL) { - apiClient->apiKeys = list_create(); + if(apiKeys_{{name}}!= NULL) { + apiClient->apiKeys_{{name}} = list_create(); listEntry_t *listEntry = NULL; - list_ForEach(listEntry, apiKeys) { + list_ForEach(listEntry, apiKeys_{{name}}) { keyValuePair_t *pair = listEntry->data; keyValuePair_t *pairDup = keyValuePair_create(strdup(pair->key), strdup(pair->value)); - list_addElement(apiClient->apiKeys, pairDup); + list_addElement(apiClient->apiKeys_{{name}}, pairDup); } }else{ - apiClient->apiKeys = NULL; + apiClient->apiKeys_{{name}} = NULL; } {{/isApiKey}} {{/authMethods}} @@ -108,9 +107,9 @@ void apiClient_free(apiClient_t *apiClient) { } {{/isOAuth}} {{#isApiKey}} - if(apiClient->apiKeys) { + if(apiClient->apiKeys_{{name}}) { listEntry_t *listEntry = NULL; - list_ForEach(listEntry, apiClient->apiKeys) { + list_ForEach(listEntry, apiClient->apiKeys_{{name}}) { keyValuePair_t *pair = listEntry->data; if(pair->key){ free(pair->key); @@ -120,7 +119,7 @@ void apiClient_free(apiClient_t *apiClient) { } keyValuePair_free(pair); } - list_free(apiClient->apiKeys); + list_free(apiClient->apiKeys_{{name}}); } {{/isApiKey}} {{/authMethods}} @@ -440,9 +439,9 @@ void apiClient_invoke(apiClient_t *apiClient, {{#authMethods}} {{#isApiKey}} // this would only be generated for apiKey authentication - if (apiClient->apiKeys != NULL) + if (apiClient->apiKeys_{{name}} != NULL) { - list_ForEach(listEntry, apiClient->apiKeys) { + list_ForEach(listEntry, apiClient->apiKeys_{{name}}) { keyValuePair_t *apiKey = listEntry->data; if((apiKey->key != NULL) && (apiKey->value != NULL) ) @@ -469,7 +468,7 @@ void apiClient_invoke(apiClient_t *apiClient, writeDataCallback); curl_easy_setopt(handle, CURLOPT_WRITEDATA, - &apiClient->dataReceived); + apiClient); curl_easy_setopt(handle, CURLOPT_HTTPHEADER, headers); curl_easy_setopt(handle, CURLOPT_VERBOSE, 0); // to get curl debug msg 0: to disable, 1L:to enable @@ -559,9 +558,12 @@ void apiClient_invoke(apiClient_t *apiClient, } size_t writeDataCallback(void *buffer, size_t size, size_t nmemb, void *userp) { - *(char **) userp = strdup(buffer); - - return size * nmemb; + size_t size_this_time = nmemb * size; + apiClient_t *apiClient = (apiClient_t *)userp; + apiClient->dataReceived = (char *)realloc( apiClient->dataReceived, apiClient->dataReceivedLen + size_this_time + 1); + memcpy(apiClient->dataReceived + apiClient->dataReceivedLen, buffer, size_this_time); + apiClient->dataReceivedLen += size_this_time; + return size_this_time; } char *strReplace(char *orig, char *rep, char *with) { @@ -616,40 +618,3 @@ char *strReplace(char *orig, char *rep, char *with) { return result; } -char *base64encode (const void *b64_encode_this, int encode_this_many_bytes){ -#ifdef OPENSSL - BIO *b64_bio, *mem_bio; //Declares two OpenSSL BIOs: a base64 filter and a memory BIO. - BUF_MEM *mem_bio_mem_ptr; //Pointer to a "memory BIO" structure holding our base64 data. - b64_bio = BIO_new(BIO_f_base64()); //Initialize our base64 filter BIO. - mem_bio = BIO_new(BIO_s_mem()); //Initialize our memory sink BIO. - BIO_push(b64_bio, mem_bio); //Link the BIOs by creating a filter-sink BIO chain. - BIO_set_flags(b64_bio, BIO_FLAGS_BASE64_NO_NL); //No newlines every 64 characters or less. - BIO_write(b64_bio, b64_encode_this, encode_this_many_bytes); //Records base64 encoded data. - BIO_flush(b64_bio); //Flush data. Necessary for b64 encoding, because of pad characters. - BIO_get_mem_ptr(mem_bio, &mem_bio_mem_ptr); //Store address of mem_bio's memory structure. - BIO_set_close(mem_bio, BIO_NOCLOSE); //Permit access to mem_ptr after BIOs are destroyed. - BIO_free_all(b64_bio); //Destroys all BIOs in chain, starting with b64 (i.e. the 1st one). - BUF_MEM_grow(mem_bio_mem_ptr, (*mem_bio_mem_ptr).length + 1); //Makes space for end null. - (*mem_bio_mem_ptr).data[(*mem_bio_mem_ptr).length] = '\0'; //Adds null-terminator to tail. - return (*mem_bio_mem_ptr).data; //Returns base-64 encoded data. (See: "buf_mem_st" struct). -#endif -} - -char *base64decode (const void *b64_decode_this, int decode_this_many_bytes, int *decoded_bytes){ -#ifdef OPENSSL - BIO *b64_bio, *mem_bio; //Declares two OpenSSL BIOs: a base64 filter and a memory BIO. - char *base64_decoded = calloc( (decode_this_many_bytes*3)/4+1, sizeof(char) ); //+1 = null. - b64_bio = BIO_new(BIO_f_base64()); //Initialize our base64 filter BIO. - mem_bio = BIO_new(BIO_s_mem()); //Initialize our memory source BIO. - BIO_write(mem_bio, b64_decode_this, decode_this_many_bytes); //Base64 data saved in source. - BIO_push(b64_bio, mem_bio); //Link the BIOs by creating a filter-source BIO chain. - BIO_set_flags(b64_bio, BIO_FLAGS_BASE64_NO_NL); //Don't require trailing newlines. - int decoded_byte_index = 0; //Index where the next base64_decoded byte should be written. - while ( 0 < BIO_read(b64_bio, base64_decoded+decoded_byte_index, 1) ){ //Read byte-by-byte. - decoded_byte_index++; //Increment the index until read of BIO decoded data is complete. - } //Once we're done reading decoded data, BIO_read returns -1 even though there's no error. - BIO_free_all(b64_bio); //Destroys all BIOs in chain, starting with b64 (i.e. the 1st one). - *decoded_bytes = decoded_byte_index; - return base64_decoded; //Returns base-64 decoded data with trailing null terminator. -#endif -} diff --git a/modules/openapi-generator/src/main/resources/C-libcurl/apiClient.h.mustache b/modules/openapi-generator/src/main/resources/C-libcurl/apiClient.h.mustache index 034205fc2481..29d8d3998195 100644 --- a/modules/openapi-generator/src/main/resources/C-libcurl/apiClient.h.mustache +++ b/modules/openapi-generator/src/main/resources/C-libcurl/apiClient.h.mustache @@ -8,6 +8,7 @@ #include #include "../include/list.h" #include "../include/keyValuePair.h" +#include "../include/binary.h" typedef struct sslConfig_t { char *clientCertFile; /* client certificate */ @@ -21,6 +22,7 @@ typedef struct apiClient_t { char *basePath; sslConfig_t *sslConfig; void *dataReceived; + long dataReceivedLen; long response_code; {{#hasAuthMethods}} {{#authMethods}} @@ -32,18 +34,12 @@ typedef struct apiClient_t { char *accessToken; {{/isOAuth}} {{#isApiKey}} - list_t *apiKeys; + list_t *apiKeys_{{name}}; {{/isApiKey}} {{/authMethods}} {{/hasAuthMethods}} } apiClient_t; -typedef struct binary_t -{ - uint8_t* data; - unsigned int len; -} binary_t; - apiClient_t* apiClient_create(); apiClient_t* apiClient_create_with_base_path(const char *basePath @@ -51,7 +47,7 @@ apiClient_t* apiClient_create_with_base_path(const char *basePath {{#hasAuthMethods}} {{#authMethods}} {{#isApiKey}} -, list_t *apiKeys +, list_t *apiKeys_{{name}} {{/isApiKey}} {{/authMethods}} {{/hasAuthMethods}} @@ -67,8 +63,4 @@ void sslConfig_free(sslConfig_t *sslConfig); char *strReplace(char *orig, char *rep, char *with); -char *base64encode(const void *b64_encode_this, int encode_this_many_bytes); - -char *base64decode(const void *b64_decode_this, int decode_this_many_bytes); - #endif // INCLUDE_API_CLIENT_H diff --git a/modules/openapi-generator/src/main/resources/C-libcurl/binary.c.mustache b/modules/openapi-generator/src/main/resources/C-libcurl/binary.c.mustache new file mode 100644 index 000000000000..ddd162a91f3d --- /dev/null +++ b/modules/openapi-generator/src/main/resources/C-libcurl/binary.c.mustache @@ -0,0 +1,58 @@ +#include +#include +#include "../include/binary.h" +#ifdef OPENSSL +#include "openssl/pem.h" +#endif + +binary_t* instantiate_binary_t(char* data, int len) { + binary_t* ret = malloc(sizeof(struct binary_t)); + ret->len=len; + ret->data = malloc(len); + memcpy(ret->data, data, len); + return ret; +} + +char *base64encode (const void *b64_encode_this, int encode_this_many_bytes){ +#ifdef OPENSSL + BIO *b64_bio, *mem_bio; //Declares two OpenSSL BIOs: a base64 filter and a memory BIO. + BUF_MEM *mem_bio_mem_ptr; //Pointer to a "memory BIO" structure holding our base64 data. + b64_bio = BIO_new(BIO_f_base64()); //Initialize our base64 filter BIO. + mem_bio = BIO_new(BIO_s_mem()); //Initialize our memory sink BIO. + BIO_push(b64_bio, mem_bio); //Link the BIOs by creating a filter-sink BIO chain. + BIO_set_flags(b64_bio, BIO_FLAGS_BASE64_NO_NL); //No newlines every 64 characters or less. + BIO_write(b64_bio, b64_encode_this, encode_this_many_bytes); //Records base64 encoded data. + BIO_flush(b64_bio); //Flush data. Necessary for b64 encoding, because of pad characters. + BIO_get_mem_ptr(mem_bio, &mem_bio_mem_ptr); //Store address of mem_bio's memory structure. + BIO_set_close(mem_bio, BIO_NOCLOSE); //Permit access to mem_ptr after BIOs are destroyed. + BIO_free_all(b64_bio); //Destroys all BIOs in chain, starting with b64 (i.e. the 1st one). + BUF_MEM_grow(mem_bio_mem_ptr, (*mem_bio_mem_ptr).length + 1); //Makes space for end null. + (*mem_bio_mem_ptr).data[(*mem_bio_mem_ptr).length] = '\0'; //Adds null-terminator to tail. + return (*mem_bio_mem_ptr).data; //Returns base-64 encoded data. (See: "buf_mem_st" struct). +#else // OPENSSL +#warning Data will not be encoded. If you want to use function "base64encode", please define "-DOPENSSL" when building the library. + return NULL; +#endif // OPENSSL +} + +char *base64decode (const void *b64_decode_this, int decode_this_many_bytes, int *decoded_bytes){ +#ifdef OPENSSL + BIO *b64_bio, *mem_bio; //Declares two OpenSSL BIOs: a base64 filter and a memory BIO. + char *base64_decoded = calloc( (decode_this_many_bytes*3)/4+1, sizeof(char) ); //+1 = null. + b64_bio = BIO_new(BIO_f_base64()); //Initialize our base64 filter BIO. + mem_bio = BIO_new(BIO_s_mem()); //Initialize our memory source BIO. + BIO_write(mem_bio, b64_decode_this, decode_this_many_bytes); //Base64 data saved in source. + BIO_push(b64_bio, mem_bio); //Link the BIOs by creating a filter-source BIO chain. + BIO_set_flags(b64_bio, BIO_FLAGS_BASE64_NO_NL); //Don't require trailing newlines. + int decoded_byte_index = 0; //Index where the next base64_decoded byte should be written. + while ( 0 < BIO_read(b64_bio, base64_decoded+decoded_byte_index, 1) ){ //Read byte-by-byte. + decoded_byte_index++; //Increment the index until read of BIO decoded data is complete. + } //Once we're done reading decoded data, BIO_read returns -1 even though there's no error. + BIO_free_all(b64_bio); //Destroys all BIOs in chain, starting with b64 (i.e. the 1st one). + *decoded_bytes = decoded_byte_index; + return base64_decoded; //Returns base-64 decoded data with trailing null terminator. +#else // OPENSSL +#warning Data will not be decoded. If you want to use function "base64decode", please define "-DOPENSSL" when building the library. + return NULL; +#endif // OPENSSL +} diff --git a/modules/openapi-generator/src/main/resources/C-libcurl/binary.h.mustache b/modules/openapi-generator/src/main/resources/C-libcurl/binary.h.mustache new file mode 100644 index 000000000000..571df5b35fba --- /dev/null +++ b/modules/openapi-generator/src/main/resources/C-libcurl/binary.h.mustache @@ -0,0 +1,18 @@ +#ifndef INCLUDE_BINARY_H +#define INCLUDE_BINARY_H + +#include + +typedef struct binary_t +{ + uint8_t* data; + unsigned int len; +} binary_t; + +binary_t* instantiate_binary_t(char* data, int len); + +char *base64encode(const void *b64_encode_this, int encode_this_many_bytes); + +char *base64decode(const void *b64_decode_this, int decode_this_many_bytes, int *decoded_bytes); + +#endif // INCLUDE_BINARY_H diff --git a/modules/openapi-generator/src/main/resources/C-libcurl/model-body.mustache b/modules/openapi-generator/src/main/resources/C-libcurl/model-body.mustache index 7a911ec67965..06f23c4d9422 100644 --- a/modules/openapi-generator/src/main/resources/C-libcurl/model-body.mustache +++ b/modules/openapi-generator/src/main/resources/C-libcurl/model-body.mustache @@ -534,7 +534,7 @@ fail: } {{/isByteArray}} {{#isBinary}} - binary_t* decoded_str_{{{name}}}; + binary_t* decoded_str_{{{name}}} = malloc(sizeof(struct binary_t)); {{^required}}if ({{{name}}}) { {{/required}} if(!cJSON_IsString({{{name}}})) { diff --git a/modules/openapi-generator/src/main/resources/C-libcurl/model-header.mustache b/modules/openapi-generator/src/main/resources/C-libcurl/model-header.mustache index 03a03276f66e..1fa938ed4a22 100644 --- a/modules/openapi-generator/src/main/resources/C-libcurl/model-header.mustache +++ b/modules/openapi-generator/src/main/resources/C-libcurl/model-header.mustache @@ -11,6 +11,10 @@ #include "../external/cJSON.h" #include "../include/list.h" #include "../include/keyValuePair.h" +#include "../include/binary.h" + +typedef struct {{classname}}_t {{classname}}_t; + {{#imports}} #include "{{{.}}}.h" {{/imports}} diff --git a/modules/openapi-generator/src/main/resources/C-libcurl/model_test.mustache b/modules/openapi-generator/src/main/resources/C-libcurl/model_test.mustache index 2f17b588076a..77e338bea5f6 100644 --- a/modules/openapi-generator/src/main/resources/C-libcurl/model_test.mustache +++ b/modules/openapi-generator/src/main/resources/C-libcurl/model_test.mustache @@ -1,11 +1,74 @@ +{{#models}} +{{#model}} +#ifndef {{classFilename}}_TEST +#define {{classFilename}}_TEST + +// the following is to include only the main from the first c file +#ifndef TEST_MAIN +#define TEST_MAIN +#define {{classFilename}}_MAIN +#endif // TEST_MAIN + #include #include #include -#include "cJSON.h" -{{#imports}}{{{import}}} -{{/imports}} +#include +#include "../external/cJSON.h" + +#include "../model/{{classFilename}}.h" +{{classname}}_t* instantiate_{{classname}}(int include_optional); + +{{#vars}}{{#isModel}}{{#isEnum}} +// it is enum. Work in Progress +{{/isEnum}}{{^isEnum}}#include "test_{{{dataType}}}.c" +{{/isEnum}}{{/isModel}}{{/vars}} + +{{classname}}_t* instantiate_{{classname}}(int include_optional) { + {{classname}}_t* {{classname}} = NULL; + if (include_optional) { + {{classname}} = {{classname}}_create( +{{#vars}} {{#isEnum}}{{^isContainer}}{{#example}}{{projectName}}_{{classVarName}}_{{enumName}}_{{{.}}}{{/example}}{{/isContainer}}{{#isContainer}}{{#example}}{{{.}}}{{/example}}{{/isContainer}}{{/isEnum}}{{^isEnum}}{{#example}}{{{.}}}{{/example}}{{/isEnum}}{{^example}}{{#isModel}}{{#isEnum}}// enum {{datatypeWithEnum}}_e Work in Progress +{{/isEnum}}{{^isEnum}} // false, not to have infinite recursion + instantiate_{{{dataType}}}(0){{/isEnum}}{{/isModel}}{{^isModel}}0{{/isModel}}{{/example}}{{#hasMore}},{{/hasMore}} +{{/vars}} + ); + } else { + {{classname}} = {{classname}}_create( +{{#vars}} {{#isEnum}}{{^isContainer}}{{#example}}{{projectName}}_{{classVarName}}_{{enumName}}_{{{.}}}{{/example}}{{/isContainer}}{{#isContainer}}{{#example}}{{{.}}}{{/example}}{{/isContainer}}{{/isEnum}}{{^isEnum}}{{#example}}{{{.}}}{{/example}}{{/isEnum}}{{^example}}{{#isModel}}{{#isEnum}}// enum {{datatypeWithEnum}}_e Work in Progress +{{/isEnum}}{{^isEnum}}NULL{{/isEnum}}{{/isModel}}{{^isModel}}0{{/isModel}}{{/example}}{{#hasMore}},{{/hasMore}} +{{/vars}} + ); + } + + return {{classname}}; +} + + +#ifdef {{classFilename}}_MAIN + +void test_{{classname}}(int include_optional) { + {{classname}}_t* {{classname}}_1 = instantiate_{{classname}}(include_optional); + + cJSON* json{{classname}}_1 = {{classname}}_convertToJSON({{classname}}_1); + printf("{{classname}} :\n%s\n", cJSON_Print(json{{classname}}_1)); + {{classname}}_t* {{classname}}_2 = {{classname}}_parseFromJSON(json{{classname}}_1); + cJSON* json{{classname}}_2 = {{classname}}_convertToJSON({{classname}}_2); + printf("repeating {{classname}}:\n%s\n", cJSON_Print(json{{classname}}_2)); +} int main() { -printf("Hello world \n"); +{{#models}} +{{#model}} + test_{{classname}}(1); + test_{{classname}}(0); +{{/model}} +{{/models}} + printf("Hello world \n"); + return 0; } + +#endif // {{classFilename}}_MAIN +#endif // {{classFilename}}_TEST +{{/model}} +{{/models}} diff --git a/modules/openapi-generator/src/main/resources/C-libcurl/object-header.mustache b/modules/openapi-generator/src/main/resources/C-libcurl/object-header.mustache index 6b1a77fc508a..18503e0c276f 100644 --- a/modules/openapi-generator/src/main/resources/C-libcurl/object-header.mustache +++ b/modules/openapi-generator/src/main/resources/C-libcurl/object-header.mustache @@ -9,6 +9,7 @@ #include "../external/cJSON.h" #include "../include/list.h" #include "../include/keyValuePair.h" +#include "../include/binary.h" typedef struct object_t { diff --git a/modules/openapi-generator/src/main/resources/Java/JSON.mustache b/modules/openapi-generator/src/main/resources/Java/JSON.mustache index b951c3c555db..590ba386ea29 100644 --- a/modules/openapi-generator/src/main/resources/Java/JSON.mustache +++ b/modules/openapi-generator/src/main/resources/Java/JSON.mustache @@ -69,11 +69,11 @@ public class JSON { .registerTypeSelector({{classname}}.class, new TypeSelector() { @Override public Class getClassForElement(JsonElement readElement) { - Map classByDiscriminatorValue = new HashMap(); + Map classByDiscriminatorValue = new HashMap(); {{#mappedModels}} - classByDiscriminatorValue.put("{{mappingName}}".toUpperCase(Locale.ROOT), {{modelName}}.class); + classByDiscriminatorValue.put("{{mappingName}}"{{^discriminatorCaseSensitive}}.toUpperCase(Locale.ROOT){{/discriminatorCaseSensitive}}, {{modelName}}.class); {{/mappedModels}} - classByDiscriminatorValue.put("{{classname}}".toUpperCase(Locale.ROOT), {{classname}}.class); + classByDiscriminatorValue.put("{{name}}"{{^discriminatorCaseSensitive}}.toUpperCase(Locale.ROOT){{/discriminatorCaseSensitive}}, {{classname}}.class); return getClassByDiscriminator(classByDiscriminatorValue, getDiscriminatorValue(readElement, "{{{propertyBaseName}}}")); } @@ -97,8 +97,15 @@ public class JSON { return element.getAsString(); } + /** + * Returns the Java class that implements the OpenAPI schema for the specified discriminator value. + * + * @param classByDiscriminatorValue The map of discriminator values to Java classes. + * @param discriminatorValue The value of the OpenAPI discriminator in the input data. + * @return The Java class that implements the OpenAPI schema + */ private static Class getClassByDiscriminator(Map classByDiscriminatorValue, String discriminatorValue) { - Class clazz = (Class) classByDiscriminatorValue.get(discriminatorValue.toUpperCase(Locale.ROOT)); + Class clazz = (Class) classByDiscriminatorValue.get(discriminatorValue{{^discriminatorCaseSensitive}}.toUpperCase(Locale.ROOT){{/discriminatorCaseSensitive}}); if (null == clazz) { throw new IllegalArgumentException("cannot determine model class of name: <" + discriminatorValue + ">"); } diff --git a/modules/openapi-generator/src/main/resources/Java/api_test.mustache b/modules/openapi-generator/src/main/resources/Java/api_test.mustache index 1d95ac2ed89a..7011191c80a3 100644 --- a/modules/openapi-generator/src/main/resources/Java/api_test.mustache +++ b/modules/openapi-generator/src/main/resources/Java/api_test.mustache @@ -7,39 +7,45 @@ import {{invokerPackage}}.ApiException; {{/imports}} import org.junit.Test; import org.junit.Ignore; +import org.junit.Assert; {{^fullJavaUtil}} import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; -{{/fullJavaUtil}} +{{/fullJavaUtil}} /** * API tests for {{classname}} */ -@Ignore public class {{classname}}Test { private final {{classname}} api = new {{classname}}(); - {{#operations}}{{#operation}} + {{#operations}} + {{#operation}} /** + {{#summary}} * {{summary}} * + {{/summary}} + {{#notes}} * {{notes}} * + {{/notes}} * @throws ApiException * if the Api call fails */ @Test public void {{operationId}}Test() throws ApiException { - {{#allParams}} - {{{dataType}}} {{paramName}} = null; - {{/allParams}} - {{#returnType}}{{{returnType}}} response = {{/returnType}}api.{{operationId}}({{#allParams}}{{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}}); + //{{#allParams}} + //{{{dataType}}} {{paramName}} = null; + //{{/allParams}} + //{{#returnType}}{{{returnType}}} response = {{/returnType}}api.{{operationId}}({{#allParams}}{{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}}); // TODO: test validations } - {{/operation}}{{/operations}} + {{/operation}} + {{/operations}} } diff --git a/modules/openapi-generator/src/main/resources/Java/beanValidationCore.mustache b/modules/openapi-generator/src/main/resources/Java/beanValidationCore.mustache index d107c037b9a7..ae26b2739f1e 100644 --- a/modules/openapi-generator/src/main/resources/Java/beanValidationCore.mustache +++ b/modules/openapi-generator/src/main/resources/Java/beanValidationCore.mustache @@ -17,4 +17,4 @@ isInteger set isLong set }}{{#isLong}}{{#minimum}} @Min({{minimum}}L){{/minimum}}{{#maximum}} @Max({{maximum}}L){{/maximum}}{{/isLong}}{{! Not Integer, not Long => we have a decimal value! -}}{{^isInteger}}{{^isLong}}{{#minimum}} @DecimalMin({{#exclusiveMinimum}}value={{/exclusiveMinimum}}"{{minimum}}"{{#exclusiveMinimum}},inclusive=false{{/exclusiveMinimum}}){{/minimum}}{{#maximum}} @DecimalMax({{#exclusiveMinimum}}value={{/exclusiveMinimum}}"{{maximum}}"{{#exclusiveMinimum}},inclusive=false{{/exclusiveMinimum}}){{/maximum}}{{/isLong}}{{/isInteger}} \ No newline at end of file +}}{{^isInteger}}{{^isLong}}{{#minimum}} @DecimalMin({{#exclusiveMinimum}}value={{/exclusiveMinimum}}"{{minimum}}"{{#exclusiveMinimum}},inclusive=false{{/exclusiveMinimum}}){{/minimum}}{{#maximum}} @DecimalMax({{#exclusiveMaximum}}value={{/exclusiveMaximum}}"{{maximum}}"{{#exclusiveMaximum}},inclusive=false{{/exclusiveMaximum}}){{/maximum}}{{/isLong}}{{/isInteger}} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/Java/libraries/feign/api.mustache b/modules/openapi-generator/src/main/resources/Java/libraries/feign/api.mustache index 238079ca27c0..cff48fcd2e4c 100644 --- a/modules/openapi-generator/src/main/resources/Java/libraries/feign/api.mustache +++ b/modules/openapi-generator/src/main/resources/Java/libraries/feign/api.mustache @@ -42,7 +42,7 @@ public interface {{classname}} extends ApiClient.Api { "{{baseName}}: {{=<% %>=}}{<%paramName%>}<%={{ }}=%>"{{#hasMore}}, {{/hasMore}}{{/headerParams}} }) - {{#returnType}}{{{returnType}}} {{/returnType}}{{^returnType}}void {{/returnType}}{{nickname}}({{#allParams}}{{^isBodyParam}}{{^legacyDates}}@Param("{{baseName}}") {{/legacyDates}}{{#legacyDates}}@Param(value="{{baseName}}", expander=ParamExpander.class) {{/legacyDates}}{{/isBodyParam}}{{{dataType}}} {{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}}); + {{#returnType}}{{{returnType}}} {{/returnType}}{{^returnType}}void {{/returnType}}{{nickname}}({{#allParams}}{{^isBodyParam}}{{^legacyDates}}@Param("{{paramName}}") {{/legacyDates}}{{#legacyDates}}@Param(value="{{baseName}}", expander=ParamExpander.class) {{/legacyDates}}{{/isBodyParam}}{{{dataType}}} {{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}}); {{#hasQueryParams}} /** @@ -80,7 +80,7 @@ public interface {{classname}} extends ApiClient.Api { "{{baseName}}: {{=<% %>=}}{<%paramName%>}<%={{ }}=%>"{{#hasMore}}, {{/hasMore}}{{/headerParams}} }) - {{#returnType}}{{{returnType}}} {{/returnType}}{{^returnType}}void {{/returnType}}{{nickname}}({{#allParams}}{{^isQueryParam}}{{^isBodyParam}}{{^legacyDates}}@Param("{{baseName}}") {{/legacyDates}}{{#legacyDates}}@Param(value="{{baseName}}", expander=ParamExpander.class) {{/legacyDates}}{{/isBodyParam}}{{{dataType}}} {{paramName}}, {{/isQueryParam}}{{/allParams}}@QueryMap(encoded=true) Map queryParams); + {{#returnType}}{{{returnType}}} {{/returnType}}{{^returnType}}void {{/returnType}}{{nickname}}({{#allParams}}{{^isQueryParam}}{{^isBodyParam}}{{^legacyDates}}@Param("{{paramName}}") {{/legacyDates}}{{#legacyDates}}@Param(value="{{baseName}}", expander=ParamExpander.class) {{/legacyDates}}{{/isBodyParam}}{{{dataType}}} {{paramName}}, {{/isQueryParam}}{{/allParams}}@QueryMap(encoded=true) Map queryParams); /** * A convenience class for generating query parameters for the diff --git a/modules/openapi-generator/src/main/resources/Java/libraries/feign/build.gradle.mustache b/modules/openapi-generator/src/main/resources/Java/libraries/feign/build.gradle.mustache index 2a6c4c79fbc5..86cdad95f82f 100644 --- a/modules/openapi-generator/src/main/resources/Java/libraries/feign/build.gradle.mustache +++ b/modules/openapi-generator/src/main/resources/Java/libraries/feign/build.gradle.mustache @@ -119,14 +119,14 @@ if(hasProperty('target') && target == 'android') { } ext { - swagger_annotations_version = "1.5.22" + swagger_annotations_version = "1.5.24" jackson_version = "2.10.3" jackson_databind_version = "2.10.3" jackson_databind_nullable_version = "0.2.1" {{#threetenbp}} jackson_threetenbp_version = "2.9.10" {{/threetenbp}} - feign_version = "{{#useFeign10}}10.7.4{{/useFeign10}}{{^useFeign10}}9.7.0{{/useFeign10}}" + feign_version = "{{#useFeign10}}11.0{{/useFeign10}}{{^useFeign10}}9.7.0{{/useFeign10}}" feign_form_version = "{{#useFeign10}}3.8.0{{/useFeign10}}{{^useFeign10}}2.1.0{{/useFeign10}}" junit_version = "4.13" oltu_version = "1.0.1" diff --git a/modules/openapi-generator/src/main/resources/Java/libraries/feign/build.sbt.mustache b/modules/openapi-generator/src/main/resources/Java/libraries/feign/build.sbt.mustache index 8fa1d345b26f..cd55527b8ec4 100644 --- a/modules/openapi-generator/src/main/resources/Java/libraries/feign/build.sbt.mustache +++ b/modules/openapi-generator/src/main/resources/Java/libraries/feign/build.sbt.mustache @@ -9,10 +9,10 @@ lazy val root = (project in file(".")). publishArtifact in (Compile, packageDoc) := false, resolvers += Resolver.mavenLocal, libraryDependencies ++= Seq( - "io.swagger" % "swagger-annotations" % "1.5.22" % "compile", - "io.github.openfeign" % "feign-core" % "{{#useFeign10}}10.7.4{{/useFeign10}}{{^useFeign10}}9.7.0{{/useFeign10}}" % "compile", - "io.github.openfeign" % "feign-jackson" % "{{#useFeign10}}10.7.4{{/useFeign10}}{{^useFeign10}}9.7.0{{/useFeign10}}" % "compile", - "io.github.openfeign" % "feign-slf4j" % "{{#useFeign10}}10.7.4{{/useFeign10}}{{^useFeign10}}9.7.0{{/useFeign10}}" % "compile", + "io.swagger" % "swagger-annotations" % "1.5.24" % "compile", + "io.github.openfeign" % "feign-core" % "{{#useFeign10}}11.0{{/useFeign10}}{{^useFeign10}}9.7.0{{/useFeign10}}" % "compile", + "io.github.openfeign" % "feign-jackson" % "{{#useFeign10}}11.0{{/useFeign10}}{{^useFeign10}}9.7.0{{/useFeign10}}" % "compile", + "io.github.openfeign" % "feign-slf4j" % "{{#useFeign10}}11.0{{/useFeign10}}{{^useFeign10}}9.7.0{{/useFeign10}}" % "compile", "io.github.openfeign.form" % "feign-form" % "{{#useFeign10}}3.8.0{{/useFeign10}}{{^useFeign10}}2.1.0{{/useFeign10}}" % "compile", "com.fasterxml.jackson.core" % "jackson-core" % "2.10.3" % "compile", "com.fasterxml.jackson.core" % "jackson-annotations" % "2.10.3" % "compile", diff --git a/modules/openapi-generator/src/main/resources/Java/libraries/feign/pom.mustache b/modules/openapi-generator/src/main/resources/Java/libraries/feign/pom.mustache index 86f6f397781d..a40806b32e98 100644 --- a/modules/openapi-generator/src/main/resources/Java/libraries/feign/pom.mustache +++ b/modules/openapi-generator/src/main/resources/Java/libraries/feign/pom.mustache @@ -63,7 +63,7 @@ org.apache.maven.plugins maven-surefire-plugin - 2.12 + 3.0.0-M4 @@ -73,7 +73,7 @@ -Xms512m -Xmx1500m methods - pertest + 10 @@ -139,6 +139,22 @@ + + org.apache.maven.plugins + maven-compiler-plugin + 3.8.1 + + 1.8 + 1.8 + true + 128m + 512m + + -Xlint:all + -J-Xss4m + + + org.apache.maven.plugins maven-javadoc-plugin @@ -314,8 +330,8 @@ {{#supportJava6}}1.6{{/supportJava6}}{{^supportJava6}}{{#java8}}1.8{{/java8}}{{^java8}}1.7{{/java8}}{{/supportJava6}} ${java.version} ${java.version} - 1.5.21 - {{#useFeign10}}10.7.4{{/useFeign10}}{{^useFeign10}}9.7.0{{/useFeign10}} + 1.5.24 + {{#useFeign10}}11.0{{/useFeign10}}{{^useFeign10}}9.7.0{{/useFeign10}} {{#useFeign10}}3.8.0{{/useFeign10}}{{^useFeign10}}2.1.0{{/useFeign10}} 2.10.3 0.2.1 diff --git a/modules/openapi-generator/src/main/resources/Java/libraries/jersey2-experimental/AbstractOpenApiSchema.mustache b/modules/openapi-generator/src/main/resources/Java/libraries/jersey2-experimental/AbstractOpenApiSchema.mustache new file mode 100644 index 000000000000..61fddeca43bb --- /dev/null +++ b/modules/openapi-generator/src/main/resources/Java/libraries/jersey2-experimental/AbstractOpenApiSchema.mustache @@ -0,0 +1,55 @@ +{{>licenseInfo}} + +package {{invokerPackage}}.model; + +import org.openapitools.client.ApiException; +import java.lang.reflect.Type; +import java.util.Map; +import javax.ws.rs.core.GenericType; + +/** + * Abstract class for oneOf,anyOf schemas defined in OpenAPI spec + */ +{{>additionalModelTypeAnnotations}}{{>generatedAnnotation}} +public abstract class AbstractOpenApiSchema { + + // store the actual instance of the schema/object + private Object instance; + + // schema type (e.g. oneOf, anyOf) + private final String schemaType; + + public AbstractOpenApiSchema(String schemaType) { + this.schemaType = schemaType; + } + + /*** + * Get the list of schemas allowed to be stored in this object + * + * @return an instance of the actual schema/object + */ + public abstract Map getSchemas(); + + /*** + * Get the actual instance + * + * @return an instance of the actual schema/object + */ + public Object getActualInstance() {return instance;} + + /*** + * Set the actual instance + * + * @param instance the actual instance of the schema/object + */ + public void setActualInstance(Object instance) {this.instance = instance;} + + /*** + * Get the schema type (e.g. anyOf, oneOf) + * + * @return the schema type + */ + public String getSchemaType() { + return schemaType; + } +} diff --git a/modules/openapi-generator/src/main/resources/Java/libraries/jersey2-experimental/ApiClient.mustache b/modules/openapi-generator/src/main/resources/Java/libraries/jersey2-experimental/ApiClient.mustache new file mode 100644 index 000000000000..10a976f6d760 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/Java/libraries/jersey2-experimental/ApiClient.mustache @@ -0,0 +1,1133 @@ +package {{invokerPackage}}; + +import javax.ws.rs.client.Client; +import javax.ws.rs.client.ClientBuilder; +import javax.ws.rs.client.Entity; +import javax.ws.rs.client.Invocation; +import javax.ws.rs.client.WebTarget; +import javax.ws.rs.core.Form; +import javax.ws.rs.core.GenericType; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; +import javax.ws.rs.core.Response.Status; + +import org.glassfish.jersey.client.ClientConfig; +import org.glassfish.jersey.client.ClientProperties; +import org.glassfish.jersey.client.HttpUrlConnectorProvider; +import org.glassfish.jersey.jackson.JacksonFeature; +import org.glassfish.jersey.media.multipart.FormDataBodyPart; +import org.glassfish.jersey.media.multipart.FormDataContentDisposition; +import org.glassfish.jersey.media.multipart.MultiPart; +import org.glassfish.jersey.media.multipart.MultiPartFeature; + +import java.io.IOException; +import java.io.InputStream; + +import java.net.URI; +{{^supportJava6}} +import java.nio.file.Files; +import java.nio.file.StandardCopyOption; +import org.glassfish.jersey.logging.LoggingFeature; +{{/supportJava6}} +{{#supportJava6}} +import org.apache.commons.io.FileUtils; +import org.glassfish.jersey.filter.LoggingFilter; +{{/supportJava6}} +import java.util.Collection; +import java.util.Collections; +import java.util.Map; +import java.util.Map.Entry; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Arrays; +import java.util.ArrayList; +import java.util.Date; +import java.util.TimeZone; + +import java.net.URLEncoder; + +import java.io.File; +import java.io.UnsupportedEncodingException; + +import java.text.DateFormat; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +import {{invokerPackage}}.auth.Authentication; +import {{invokerPackage}}.auth.HttpBasicAuth; +import {{invokerPackage}}.auth.HttpBearerAuth; +import {{invokerPackage}}.auth.HttpSignatureAuth; +import {{invokerPackage}}.auth.ApiKeyAuth; +import {{invokerPackage}}.model.AbstractOpenApiSchema; + +{{#hasOAuthMethods}} +import {{invokerPackage}}.auth.OAuth; +{{/hasOAuthMethods}} + +{{>generatedAnnotation}} +public class ApiClient { + protected Map defaultHeaderMap = new HashMap(); + protected Map defaultCookieMap = new HashMap(); + protected String basePath = "{{{basePath}}}"; + protected List servers = new ArrayList({{#servers}}{{#-first}}Arrays.asList( +{{/-first}} new ServerConfiguration( + "{{{url}}}", + "{{{description}}}{{^description}}No description provided{{/description}}", + new HashMap(){{#variables}}{{#-first}} {{ +{{/-first}} put("{{{name}}}", new ServerVariable( + "{{{description}}}{{^description}}No description provided{{/description}}", + "{{{defaultValue}}}", + new HashSet( + {{#enumValues}} + {{#-first}} + Arrays.asList( + {{/-first}} + "{{{.}}}"{{^-last}},{{/-last}} + {{#-last}} + ) + {{/-last}} + {{/enumValues}} + ) + )); + {{#-last}} + }}{{/-last}}{{/variables}} + ){{^-last}},{{/-last}} + {{#-last}} + ){{/-last}}{{/servers}}); + protected Integer serverIndex = 0; + protected Map serverVariables = null; + protected Map> operationServers = new HashMap>() {{ + {{#apiInfo}} + {{#apis}} + {{#operations}} + {{#operation}} + {{#servers}} + {{#-first}} + put("{{{classname}}}.{{{operationId}}}", new ArrayList(Arrays.asList( + {{/-first}} + new ServerConfiguration( + "{{{url}}}", + "{{{description}}}{{^description}}No description provided{{/description}}", + new HashMap(){{#variables}}{{#-first}} {{ +{{/-first}} put("{{{name}}}", new ServerVariable( + "{{{description}}}{{^description}}No description provided{{/description}}", + "{{{defaultValue}}}", + new HashSet( + {{#enumValues}} + {{#-first}} + Arrays.asList( + {{/-first}} + "{{{.}}}"{{^-last}},{{/-last}} + {{#-last}} + ) + {{/-last}} + {{/enumValues}} + ) + )); + {{#-last}} + }}{{/-last}}{{/variables}} + ){{^-last}},{{/-last}} + {{#-last}} + )));{{/-last}} + {{/servers}} + {{/operation}} + {{/operations}} + {{/apis}} + {{/apiInfo}} + }}; + protected Map operationServerIndex = new HashMap(); + protected Map> operationServerVariables = new HashMap>(); + protected boolean debugging = false; + protected int connectionTimeout = 0; + private int readTimeout = 0; + + protected Client httpClient; + protected JSON json; + protected String tempFolderPath = null; + + protected Map authentications; + protected Map authenticationLookup; + + protected DateFormat dateFormat; + + public ApiClient() { + json = new JSON(); + httpClient = buildHttpClient(debugging); + + this.dateFormat = new RFC3339DateFormat(); + + // Set default User-Agent. + setUserAgent("{{#httpUserAgent}}{{{.}}}{{/httpUserAgent}}{{^httpUserAgent}}OpenAPI-Generator/{{{artifactVersion}}}/java{{/httpUserAgent}}"); + + // Setup authentications (key: authentication name, value: authentication). + authentications = new HashMap(); + {{#authMethods}} + {{#isBasic}} + {{#isBasicBasic}} + authentications.put("{{name}}", new HttpBasicAuth()); + {{/isBasicBasic}} + {{#isBasicBearer}} + authentications.put("{{name}}", new HttpBearerAuth("{{scheme}}")); + {{/isBasicBearer}} + {{#isHttpSignature}} + authentications.put("{{name}}", new HttpSignatureAuth("{{name}}", null, null)); + {{/isHttpSignature}} + {{/isBasic}} + {{#isApiKey}} + authentications.put("{{name}}", new ApiKeyAuth({{#isKeyInHeader}}"header"{{/isKeyInHeader}}{{^isKeyInHeader}}"query"{{/isKeyInHeader}}, "{{keyParamName}}")); + {{/isApiKey}} + {{#isOAuth}} + authentications.put("{{name}}", new OAuth()); + {{/isOAuth}} + {{/authMethods}} + // Prevent the authentications from being modified. + authentications = Collections.unmodifiableMap(authentications); + + // Setup authentication lookup (key: authentication alias, value: authentication name) + authenticationLookup = new HashMap();{{#authMethods}}{{#vendorExtensions.x-auth-id-alias}} + authenticationLookup.put("{{name}}", "{{.}}");{{/vendorExtensions.x-auth-id-alias}}{{/authMethods}} + } + + /** + * Gets the JSON instance to do JSON serialization and deserialization. + * @return JSON + */ + public JSON getJSON() { + return json; + } + + public Client getHttpClient() { + return httpClient; + } + + public ApiClient setHttpClient(Client httpClient) { + this.httpClient = httpClient; + return this; + } + + public String getBasePath() { + return basePath; + } + + public ApiClient setBasePath(String basePath) { + this.basePath = basePath; + return this; + } + + public List getServers() { + return servers; + } + + public ApiClient setServers(List servers) { + this.servers = servers; + return this; + } + + public Integer getServerIndex() { + return serverIndex; + } + + public ApiClient setServerIndex(Integer serverIndex) { + this.serverIndex = serverIndex; + return this; + } + + public Map getServerVariables() { + return serverVariables; + } + + public ApiClient setServerVariables(Map serverVariables) { + this.serverVariables = serverVariables; + return this; + } + + /** + * Get authentications (key: authentication name, value: authentication). + * @return Map of authentication object + */ + public Map getAuthentications() { + return authentications; + } + + /** + * Get authentication for the given name. + * + * @param authName The authentication name + * @return The authentication, null if not found + */ + public Authentication getAuthentication(String authName) { + return authentications.get(authName); + } + + /** + * Helper method to set username for the first HTTP basic authentication. + * @param username Username + */ + public void setUsername(String username) { + for (Authentication auth : authentications.values()) { + if (auth instanceof HttpBasicAuth) { + ((HttpBasicAuth) auth).setUsername(username); + return; + } + } + throw new RuntimeException("No HTTP basic authentication configured!"); + } + + /** + * Helper method to set password for the first HTTP basic authentication. + * @param password Password + */ + public void setPassword(String password) { + for (Authentication auth : authentications.values()) { + if (auth instanceof HttpBasicAuth) { + ((HttpBasicAuth) auth).setPassword(password); + return; + } + } + throw new RuntimeException("No HTTP basic authentication configured!"); + } + + /** + * Helper method to set API key value for the first API key authentication. + * @param apiKey API key + */ + public void setApiKey(String apiKey) { + for (Authentication auth : authentications.values()) { + if (auth instanceof ApiKeyAuth) { + ((ApiKeyAuth) auth).setApiKey(apiKey); + return; + } + } + throw new RuntimeException("No API key authentication configured!"); + } + + /** + * Helper method to configure authentications which respects aliases of API keys. + * + * @param secrets Hash map from authentication name to its secret. + */ + public void configureApiKeys(HashMap secrets) { + for (Map.Entry authEntry : authentications.entrySet()) { + Authentication auth = authEntry.getValue(); + if (auth instanceof ApiKeyAuth) { + String name = authEntry.getKey(); + // respect x-auth-id-alias property + name = authenticationLookup.getOrDefault(name, name); + if (secrets.containsKey(name)) { + ((ApiKeyAuth) auth).setApiKey(secrets.get(name)); + } + } + } + } + + /** + * Helper method to set API key prefix for the first API key authentication. + * @param apiKeyPrefix API key prefix + */ + public void setApiKeyPrefix(String apiKeyPrefix) { + for (Authentication auth : authentications.values()) { + if (auth instanceof ApiKeyAuth) { + ((ApiKeyAuth) auth).setApiKeyPrefix(apiKeyPrefix); + return; + } + } + throw new RuntimeException("No API key authentication configured!"); + } + + /** + * Helper method to set bearer token for the first Bearer authentication. + * @param bearerToken Bearer token + */ + public void setBearerToken(String bearerToken) { + for (Authentication auth : authentications.values()) { + if (auth instanceof HttpBearerAuth) { + ((HttpBearerAuth) auth).setBearerToken(bearerToken); + return; + } + } + throw new RuntimeException("No Bearer authentication configured!"); + } + + {{#hasOAuthMethods}} + /** + * Helper method to set access token for the first OAuth2 authentication. + * @param accessToken Access token + */ + public void setAccessToken(String accessToken) { + for (Authentication auth : authentications.values()) { + if (auth instanceof OAuth) { + ((OAuth) auth).setAccessToken(accessToken); + return; + } + } + throw new RuntimeException("No OAuth2 authentication configured!"); + } + + {{/hasOAuthMethods}} + /** + * Set the User-Agent header's value (by adding to the default header map). + * @param userAgent Http user agent + * @return API client + */ + public ApiClient setUserAgent(String userAgent) { + addDefaultHeader("User-Agent", userAgent); + return this; + } + + /** + * Add a default header. + * + * @param key The header's key + * @param value The header's value + * @return API client + */ + public ApiClient addDefaultHeader(String key, String value) { + defaultHeaderMap.put(key, value); + return this; + } + + /** + * Add a default cookie. + * + * @param key The cookie's key + * @param value The cookie's value + * @return API client + */ + public ApiClient addDefaultCookie(String key, String value) { + defaultCookieMap.put(key, value); + return this; + } + + /** + * Check that whether debugging is enabled for this API client. + * @return True if debugging is switched on + */ + public boolean isDebugging() { + return debugging; + } + + /** + * Enable/disable debugging for this API client. + * + * @param debugging To enable (true) or disable (false) debugging + * @return API client + */ + public ApiClient setDebugging(boolean debugging) { + this.debugging = debugging; + // Rebuild HTTP Client according to the new "debugging" value. + this.httpClient = buildHttpClient(debugging); + return this; + } + + /** + * The path of temporary folder used to store downloaded files from endpoints + * with file response. The default value is null, i.e. using + * the system's default tempopary folder. + * + * @return Temp folder path + */ + public String getTempFolderPath() { + return tempFolderPath; + } + + /** + * Set temp folder path + * @param tempFolderPath Temp folder path + * @return API client + */ + public ApiClient setTempFolderPath(String tempFolderPath) { + this.tempFolderPath = tempFolderPath; + return this; + } + + /** + * Connect timeout (in milliseconds). + * @return Connection timeout + */ + public int getConnectTimeout() { + return connectionTimeout; + } + + /** + * Set the connect timeout (in milliseconds). + * A value of 0 means no timeout, otherwise values must be between 1 and + * {@link Integer#MAX_VALUE}. + * @param connectionTimeout Connection timeout in milliseconds + * @return API client + */ + public ApiClient setConnectTimeout(int connectionTimeout) { + this.connectionTimeout = connectionTimeout; + httpClient.property(ClientProperties.CONNECT_TIMEOUT, connectionTimeout); + return this; + } + + /** + * read timeout (in milliseconds). + * @return Read timeout + */ + public int getReadTimeout() { + return readTimeout; + } + + /** + * Set the read timeout (in milliseconds). + * A value of 0 means no timeout, otherwise values must be between 1 and + * {@link Integer#MAX_VALUE}. + * @param readTimeout Read timeout in milliseconds + * @return API client + */ + public ApiClient setReadTimeout(int readTimeout) { + this.readTimeout = readTimeout; + httpClient.property(ClientProperties.READ_TIMEOUT, readTimeout); + return this; + } + + /** + * Get the date format used to parse/format date parameters. + * @return Date format + */ + public DateFormat getDateFormat() { + return dateFormat; + } + + /** + * Set the date format used to parse/format date parameters. + * @param dateFormat Date format + * @return API client + */ + public ApiClient setDateFormat(DateFormat dateFormat) { + this.dateFormat = dateFormat; + // also set the date format for model (de)serialization with Date properties + this.json.setDateFormat((DateFormat) dateFormat.clone()); + return this; + } + + /** + * Parse the given string into Date object. + * @param str String + * @return Date + */ + public Date parseDate(String str) { + try { + return dateFormat.parse(str); + } catch (java.text.ParseException e) { + throw new RuntimeException(e); + } + } + + /** + * Format the given Date object into string. + * @param date Date + * @return Date in string format + */ + public String formatDate(Date date) { + return dateFormat.format(date); + } + + /** + * Format the given parameter object into string. + * @param param Object + * @return Object in string format + */ + public String parameterToString(Object param) { + if (param == null) { + return ""; + } else if (param instanceof Date) { + return formatDate((Date) param); + } else if (param instanceof Collection) { + StringBuilder b = new StringBuilder(); + for(Object o : (Collection)param) { + if(b.length() > 0) { + b.append(','); + } + b.append(String.valueOf(o)); + } + return b.toString(); + } else { + return String.valueOf(param); + } + } + + /* + * Format to {@code Pair} objects. + * @param collectionFormat Collection format + * @param name Name + * @param value Value + * @return List of pairs + */ + public List parameterToPairs(String collectionFormat, String name, Object value){ + List params = new ArrayList(); + + // preconditions + if (name == null || name.isEmpty() || value == null) return params; + + Collection valueCollection; + if (value instanceof Collection) { + valueCollection = (Collection) value; + } else { + params.add(new Pair(name, parameterToString(value))); + return params; + } + + if (valueCollection.isEmpty()){ + return params; + } + + // get the collection format (default: csv) + String format = (collectionFormat == null || collectionFormat.isEmpty() ? "csv" : collectionFormat); + + // create the params based on the collection format + if ("multi".equals(format)) { + for (Object item : valueCollection) { + params.add(new Pair(name, parameterToString(item))); + } + + return params; + } + + String delimiter = ","; + + if ("csv".equals(format)) { + delimiter = ","; + } else if ("ssv".equals(format)) { + delimiter = " "; + } else if ("tsv".equals(format)) { + delimiter = "\t"; + } else if ("pipes".equals(format)) { + delimiter = "|"; + } + + StringBuilder sb = new StringBuilder() ; + for (Object item : valueCollection) { + sb.append(delimiter); + sb.append(parameterToString(item)); + } + + params.add(new Pair(name, sb.substring(1))); + + return params; + } + + /** + * Check if the given MIME is a JSON MIME. + * JSON MIME examples: + * application/json + * application/json; charset=UTF8 + * APPLICATION/JSON + * application/vnd.company+json + * "* / *" is also default to JSON + * @param mime MIME + * @return True if the MIME type is JSON + */ + public boolean isJsonMime(String mime) { + String jsonMime = "(?i)^(application/json|[^;/ \t]+/[^;/ \t]+[+]json)[ \t]*(;.*)?$"; + return mime != null && (mime.matches(jsonMime) || mime.equals("*/*")); + } + + /** + * Select the Accept header's value from the given accepts array: + * if JSON exists in the given array, use it; + * otherwise use all of them (joining into a string) + * + * @param accepts The accepts array to select from + * @return The Accept header to use. If the given array is empty, + * null will be returned (not to set the Accept header explicitly). + */ + public String selectHeaderAccept(String[] accepts) { + if (accepts.length == 0) { + return null; + } + for (String accept : accepts) { + if (isJsonMime(accept)) { + return accept; + } + } + return StringUtil.join(accepts, ","); + } + + /** + * Select the Content-Type header's value from the given array: + * if JSON exists in the given array, use it; + * otherwise use the first one of the array. + * + * @param contentTypes The Content-Type array to select from + * @return The Content-Type header to use. If the given array is empty, + * JSON will be used. + */ + public String selectHeaderContentType(String[] contentTypes) { + if (contentTypes.length == 0) { + return "application/json"; + } + for (String contentType : contentTypes) { + if (isJsonMime(contentType)) { + return contentType; + } + } + return contentTypes[0]; + } + + /** + * Escape the given string to be used as URL query value. + * @param str String + * @return Escaped string + */ + public String escapeString(String str) { + try { + return URLEncoder.encode(str, "utf8").replaceAll("\\+", "%20"); + } catch (UnsupportedEncodingException e) { + return str; + } + } + + /** + * Serialize the given Java object into string entity according the given + * Content-Type (only JSON is supported for now). + * @param obj Object + * @param formParams Form parameters + * @param contentType Context type + * @return Entity + * @throws ApiException API exception + */ + public Entity serialize(Object obj, Map formParams, String contentType) throws ApiException { + Entity entity; + if (contentType.startsWith("multipart/form-data")) { + MultiPart multiPart = new MultiPart(); + for (Entry param: formParams.entrySet()) { + if (param.getValue() instanceof File) { + File file = (File) param.getValue(); + FormDataContentDisposition contentDisp = FormDataContentDisposition.name(param.getKey()) + .fileName(file.getName()).size(file.length()).build(); + multiPart.bodyPart(new FormDataBodyPart(contentDisp, file, MediaType.APPLICATION_OCTET_STREAM_TYPE)); + } else { + FormDataContentDisposition contentDisp = FormDataContentDisposition.name(param.getKey()).build(); + multiPart.bodyPart(new FormDataBodyPart(contentDisp, parameterToString(param.getValue()))); + } + } + entity = Entity.entity(multiPart, MediaType.MULTIPART_FORM_DATA_TYPE); + } else if (contentType.startsWith("application/x-www-form-urlencoded")) { + Form form = new Form(); + for (Entry param: formParams.entrySet()) { + form.param(param.getKey(), parameterToString(param.getValue())); + } + entity = Entity.entity(form, MediaType.APPLICATION_FORM_URLENCODED_TYPE); + } else { + // We let jersey handle the serialization + entity = Entity.entity(obj == null ? Entity.text("") : obj, contentType); + } + return entity; + } + + /** + * Serialize the given Java object into string according the given + * Content-Type (only JSON, HTTP form is supported for now). + * @param obj Object + * @param formParams Form parameters + * @param contentType Context type + * @return String + * @throws ApiException API exception + */ + public String serializeToString(Object obj, Map formParams, String contentType) throws ApiException { + try { + if (contentType.startsWith("multipart/form-data")) { + throw new ApiException("multipart/form-data not yet supported for serializeToString (http signature authentication)"); + } else if (contentType.startsWith("application/x-www-form-urlencoded")) { + String formString = ""; + for (Entry param : formParams.entrySet()) { + formString = param.getKey() + "=" + URLEncoder.encode(parameterToString(param.getValue()), "UTF-8") + "&"; + } + + if (formString.length() == 0) { // empty string + return formString; + } else { + return formString.substring(0, formString.length() - 1); + } + } else { + return json.getMapper().writeValueAsString(obj); + } + } catch (Exception ex) { + throw new ApiException("Failed to perform serializeToString: " + ex.toString()); + } + } + + public AbstractOpenApiSchema deserializeSchemas(Response response, AbstractOpenApiSchema schema) throws ApiException{ + + Object result = null; + int matchCounter = 0; + ArrayList matchSchemas = new ArrayList<>(); + + for (Map.Entry entry : schema.getSchemas().entrySet()) { + String schemaName = entry.getKey(); + GenericType schemaType = entry.getValue(); + + if (schemaType instanceof GenericType) { // model + try { + Object deserializedObject = deserialize(response, schemaType); + if (deserializedObject != null) { + result = deserializedObject; + matchCounter++; + + if ("anyOf".equals(schema.getSchemaType())) { + break; + } else if ("oneOf".equals(schema.getSchemaType())) { + matchSchemas.add(schemaName); + } else { + throw new ApiException("Unknowe type found while expecting anyOf/oneOf:" + schema.getSchemaType()); + } + } else { + // failed to deserialize the response in the schema provided, proceed to the next one if any + } + } catch (Exception ex) { + // failed to deserialize, do nothing and try next one (schema) + } + } else {// unknown type + throw new ApiException(schemaType.getClass() + " is not a GenericType and cannot be handled properly in deserialization."); + } + + } + + if (matchCounter > 1 && "oneOf".equals(schema.getSchemaType())) {// more than 1 match for oneOf + throw new ApiException("Response body is invalid as it matches more than one schema (" + String.join(", ", matchSchemas) + ") defined in the oneOf model: " + schema.getClass().getName()); + } else if (matchCounter == 0) { // fail to match any in oneOf/anyOf schemas + throw new ApiException("Response body is invalid as it doens't match any schemas (" + String.join(", ", schema.getSchemas().keySet()) + ") defined in the oneOf/anyOf model: " + schema.getClass().getName()); + } else { // only one matched + schema.setActualInstance(result); + return schema; + } + + } + + + + /** + * Deserialize response body to Java object according to the Content-Type. + * @param Type + * @param response Response + * @param returnType Return type + * @return Deserialize object + * @throws ApiException API exception + */ + @SuppressWarnings("unchecked") + public T deserialize(Response response, GenericType returnType) throws ApiException { + if (response == null || returnType == null) { + return null; + } + + if ("byte[]".equals(returnType.toString())) { + // Handle binary response (byte array). + return (T) response.readEntity(byte[].class); + } else if (returnType.getRawType() == File.class) { + // Handle file downloading. + T file = (T) downloadFileFromResponse(response); + return file; + } + + String contentType = null; + List contentTypes = response.getHeaders().get("Content-Type"); + if (contentTypes != null && !contentTypes.isEmpty()) + contentType = String.valueOf(contentTypes.get(0)); + + // read the entity stream multiple times + response.bufferEntity(); + + return response.readEntity(returnType); + } + + /** + * Download file from the given response. + * @param response Response + * @return File + * @throws ApiException If fail to read file content from response and write to disk + */ + public File downloadFileFromResponse(Response response) throws ApiException { + try { + File file = prepareDownloadFile(response); +{{^supportJava6}} + Files.copy(response.readEntity(InputStream.class), file.toPath(), StandardCopyOption.REPLACE_EXISTING); +{{/supportJava6}} +{{#supportJava6}} + // Java6 falls back to commons.io for file copying + FileUtils.copyToFile(response.readEntity(InputStream.class), file); +{{/supportJava6}} + return file; + } catch (IOException e) { + throw new ApiException(e); + } + } + + public File prepareDownloadFile(Response response) throws IOException { + String filename = null; + String contentDisposition = (String) response.getHeaders().getFirst("Content-Disposition"); + if (contentDisposition != null && !"".equals(contentDisposition)) { + // Get filename from the Content-Disposition header. + Pattern pattern = Pattern.compile("filename=['\"]?([^'\"\\s]+)['\"]?"); + Matcher matcher = pattern.matcher(contentDisposition); + if (matcher.find()) + filename = matcher.group(1); + } + + String prefix; + String suffix = null; + if (filename == null) { + prefix = "download-"; + suffix = ""; + } else { + int pos = filename.lastIndexOf('.'); + if (pos == -1) { + prefix = filename + "-"; + } else { + prefix = filename.substring(0, pos) + "-"; + suffix = filename.substring(pos); + } + // File.createTempFile requires the prefix to be at least three characters long + if (prefix.length() < 3) + prefix = "download-"; + } + + if (tempFolderPath == null) + return File.createTempFile(prefix, suffix); + else + return File.createTempFile(prefix, suffix, new File(tempFolderPath)); + } + + /** + * Invoke API by sending HTTP request with the given options. + * + * @param Type + * @param operation The qualified name of the operation + * @param path The sub-path of the HTTP URL + * @param method The request method, one of "GET", "POST", "PUT", "HEAD" and "DELETE" + * @param queryParams The query parameters + * @param body The request body object + * @param headerParams The header parameters + * @param cookieParams The cookie parameters + * @param formParams The form parameters + * @param accept The request's Accept header + * @param contentType The request's Content-Type header + * @param authNames The authentications to apply + * @param returnType The return type into which to deserialize the response + * @param schema An instance of the response that uses oneOf/anyOf + * @return The response body in type of string + * @throws ApiException API exception + */ + public ApiResponse invokeAPI(String operation, String path, String method, List queryParams, Object body, Map headerParams, Map cookieParams, Map formParams, String accept, String contentType, String[] authNames, GenericType returnType, AbstractOpenApiSchema schema) throws ApiException { + + // Not using `.target(targetURL).path(path)` below, + // to support (constant) query string in `path`, e.g. "/posts?draft=1" + String targetURL; + if (serverIndex != null) { + Integer index; + List serverConfigurations; + Map variables; + + if (operationServers.containsKey(operation)) { + index = operationServerIndex.getOrDefault(operation, serverIndex); + variables = operationServerVariables.getOrDefault(operation, serverVariables); + serverConfigurations = operationServers.get(operation); + } else { + index = serverIndex; + variables = serverVariables; + serverConfigurations = servers; + } + if (index < 0 || index >= serverConfigurations.size()) { + throw new ArrayIndexOutOfBoundsException(String.format( + "Invalid index %d when selecting the host settings. Must be less than %d", index, serverConfigurations.size() + )); + } + targetURL = serverConfigurations.get(index).URL(variables) + path; + } else { + targetURL = this.basePath + path; + } + WebTarget target = httpClient.target(targetURL); + + if (queryParams != null) { + for (Pair queryParam : queryParams) { + if (queryParam.getValue() != null) { + target = target.queryParam(queryParam.getName(), escapeString(queryParam.getValue())); + } + } + } + + Invocation.Builder invocationBuilder = target.request().accept(accept); + + for (Entry entry : headerParams.entrySet()) { + String value = entry.getValue(); + if (value != null) { + invocationBuilder = invocationBuilder.header(entry.getKey(), value); + } + } + + for (Entry entry : cookieParams.entrySet()) { + String value = entry.getValue(); + if (value != null) { + invocationBuilder = invocationBuilder.cookie(entry.getKey(), value); + } + } + + for (Entry entry : defaultCookieMap.entrySet()) { + String value = entry.getValue(); + if (value != null) { + invocationBuilder = invocationBuilder.cookie(entry.getKey(), value); + } + } + + for (Entry entry : defaultHeaderMap.entrySet()) { + String key = entry.getKey(); + if (!headerParams.containsKey(key)) { + String value = entry.getValue(); + if (value != null) { + invocationBuilder = invocationBuilder.header(key, value); + } + } + } + + Entity entity = serialize(body, formParams, contentType); + + // put all headers in one place + Map allHeaderParams = new HashMap<>(); + allHeaderParams.putAll(defaultHeaderMap); + allHeaderParams.putAll(headerParams); + + // update different parameters (e.g. headers) for authentication + updateParamsForAuth(authNames, queryParams, allHeaderParams, cookieParams, serializeToString(body, formParams, contentType), method, target.getUri()); + + Response response = null; + + try { + if ("GET".equals(method)) { + response = invocationBuilder.get(); + } else if ("POST".equals(method)) { + response = invocationBuilder.post(entity); + } else if ("PUT".equals(method)) { + response = invocationBuilder.put(entity); + } else if ("DELETE".equals(method)) { + response = invocationBuilder.method("DELETE", entity); + } else if ("PATCH".equals(method)) { + response = invocationBuilder.method("PATCH", entity); + } else if ("HEAD".equals(method)) { + response = invocationBuilder.head(); + } else if ("OPTIONS".equals(method)) { + response = invocationBuilder.options(); + } else if ("TRACE".equals(method)) { + response = invocationBuilder.trace(); + } else { + throw new ApiException(500, "unknown method type " + method); + } + + int statusCode = response.getStatusInfo().getStatusCode(); + Map> responseHeaders = buildResponseHeaders(response); + + if (response.getStatus() == Status.NO_CONTENT.getStatusCode()) { + return new ApiResponse<{{#supportJava6}}T{{/supportJava6}}>(statusCode, responseHeaders); + } else if (response.getStatusInfo().getFamily() == Status.Family.SUCCESSFUL) { + if (returnType == null) + return new ApiResponse<{{#supportJava6}}T{{/supportJava6}}>(statusCode, responseHeaders); + else + if (schema == null) { + return new ApiResponse<>(statusCode, responseHeaders, deserialize(response, returnType)); + } else { // oneOf/anyOf + return new ApiResponse<>(statusCode, responseHeaders, (T)deserializeSchemas(response, schema)); + } + } else { + String message = "error"; + String respBody = null; + if (response.hasEntity()) { + try { + respBody = String.valueOf(response.readEntity(String.class)); + message = respBody; + } catch (RuntimeException e) { + // e.printStackTrace(); + } + } + throw new ApiException( + response.getStatus(), + message, + buildResponseHeaders(response), + respBody); + } + } finally { + try { + response.close(); + } catch (Exception e) { + // it's not critical, since the response object is local in method invokeAPI; that's fine, just continue + } + } + } + + /** + * @deprecated Add qualified name of the operation as a first parameter. + */ + @Deprecated + public ApiResponse invokeAPI(String path, String method, List queryParams, Object body, Map headerParams, Map cookieParams, Map formParams, String accept, String contentType, String[] authNames, GenericType returnType, AbstractOpenApiSchema schema) throws ApiException { + return invokeAPI(null, path, method, queryParams, body, headerParams, cookieParams, formParams, accept, contentType, authNames, returnType, schema); + } + + /** + * Build the Client used to make HTTP requests. + * @param debugging Debug setting + * @return Client + */ + protected Client buildHttpClient(boolean debugging) { + final ClientConfig clientConfig = new ClientConfig(); + clientConfig.register(MultiPartFeature.class); + clientConfig.register(json); + clientConfig.register(JacksonFeature.class); + clientConfig.property(HttpUrlConnectorProvider.SET_METHOD_WORKAROUND, true); + // turn off compliance validation to be able to send payloads with DELETE calls + clientConfig.property(ClientProperties.SUPPRESS_HTTP_COMPLIANCE_VALIDATION, true); + if (debugging) { +{{^supportJava6}} + clientConfig.register(new LoggingFeature(java.util.logging.Logger.getLogger(LoggingFeature.DEFAULT_LOGGER_NAME), java.util.logging.Level.INFO, LoggingFeature.Verbosity.PAYLOAD_ANY, 1024*50 /* Log payloads up to 50K */)); + clientConfig.property(LoggingFeature.LOGGING_FEATURE_VERBOSITY, LoggingFeature.Verbosity.PAYLOAD_ANY); + // Set logger to ALL + java.util.logging.Logger.getLogger(LoggingFeature.DEFAULT_LOGGER_NAME).setLevel(java.util.logging.Level.ALL); +{{/supportJava6}} +{{#supportJava6}} + clientConfig.register(new LoggingFilter(java.util.logging.Logger.getLogger(LoggingFilter.class.getName()), true)); +{{/supportJava6}} + } else { + // suppress warnings for payloads with DELETE calls: + java.util.logging.Logger.getLogger("org.glassfish.jersey.client").setLevel(java.util.logging.Level.SEVERE); + } + performAdditionalClientConfiguration(clientConfig); + return ClientBuilder.newClient(clientConfig); + } + + protected void performAdditionalClientConfiguration(ClientConfig clientConfig) { + // No-op extension point + } + + protected Map> buildResponseHeaders(Response response) { + Map> responseHeaders = new HashMap>(); + for (Entry> entry: response.getHeaders().entrySet()) { + List values = entry.getValue(); + List headers = new ArrayList(); + for (Object o : values) { + headers.add(String.valueOf(o)); + } + responseHeaders.put(entry.getKey(), headers); + } + return responseHeaders; + } + + /** + * Update query and header parameters based on authentication settings. + * + * @param authNames The authentications to apply + * @param queryParams List of query parameters + * @param headerParams Map of header parameters + * @param cookieParams Map of cookie parameters + * @param method HTTP method (e.g. POST) + * @param uri HTTP URI + */ + protected void updateParamsForAuth(String[] authNames, List queryParams, Map headerParams, + Map cookieParams, String payload, String method, URI uri) throws ApiException { + for (String authName : authNames) { + Authentication auth = authentications.get(authName); + if (auth == null) { + throw new RuntimeException("Authentication undefined: " + authName); + } + auth.applyToParams(queryParams, headerParams, cookieParams, payload, method, uri); + } + } +} diff --git a/modules/openapi-generator/src/main/resources/Java/libraries/jersey2-experimental/ApiResponse.mustache b/modules/openapi-generator/src/main/resources/Java/libraries/jersey2-experimental/ApiResponse.mustache new file mode 100644 index 000000000000..5dae9dc1fdf4 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/Java/libraries/jersey2-experimental/ApiResponse.mustache @@ -0,0 +1,73 @@ +{{>licenseInfo}} + +package {{invokerPackage}}; + +import java.util.List; +import java.util.Map; +{{#caseInsensitiveResponseHeaders}} +import java.util.Map.Entry; +import java.util.TreeMap; +{{/caseInsensitiveResponseHeaders}} + +/** + * API response returned by API call. + * + * @param The type of data that is deserialized from response body + */ +public class ApiResponse { + private final int statusCode; + private final Map> headers; + private final T data; + + /** + * @param statusCode The status code of HTTP response + * @param headers The headers of HTTP response + */ + public ApiResponse(int statusCode, Map> headers) { + this(statusCode, headers, null); + } + + /** + * @param statusCode The status code of HTTP response + * @param headers The headers of HTTP response + * @param data The object deserialized from response bod + */ + public ApiResponse(int statusCode, Map> headers, T data) { + this.statusCode = statusCode; + {{#caseInsensitiveResponseHeaders}} + Map> responseHeaders = new TreeMap>(String.CASE_INSENSITIVE_ORDER); + for(Entry> entry : headers.entrySet()){ + responseHeaders.put(entry.getKey().toLowerCase(), entry.getValue()); + } + {{/caseInsensitiveResponseHeaders}} + this.headers = {{#caseInsensitiveResponseHeaders}}responseHeaders{{/caseInsensitiveResponseHeaders}}{{^caseInsensitiveResponseHeaders}}headers{{/caseInsensitiveResponseHeaders}}; + this.data = data; + } + + /** + * Get the status code + * + * @return status code + */ + public int getStatusCode() { + return statusCode; + } + + /** + * Get the headers + * + * @return map of headers + */ + public Map> getHeaders() { + return headers; + } + + /** + * Get the data + * + * @return data + */ + public T getData() { + return data; + } +} diff --git a/modules/openapi-generator/src/main/resources/Java/libraries/jersey2-experimental/JSON.mustache b/modules/openapi-generator/src/main/resources/Java/libraries/jersey2-experimental/JSON.mustache new file mode 100644 index 000000000000..dc3d9893e6d6 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/Java/libraries/jersey2-experimental/JSON.mustache @@ -0,0 +1,72 @@ +package {{invokerPackage}}; + +{{#threetenbp}} +import org.threeten.bp.*; +{{/threetenbp}} +import com.fasterxml.jackson.annotation.*; +import com.fasterxml.jackson.databind.*; +import org.openapitools.jackson.nullable.JsonNullableModule; +{{#java8}} +import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule; +{{/java8}} +{{#joda}} +import com.fasterxml.jackson.datatype.joda.JodaModule; +{{/joda}} +{{#threetenbp}} +import com.fasterxml.jackson.datatype.threetenbp.ThreeTenModule; +{{/threetenbp}} + +import java.text.DateFormat; + +import javax.ws.rs.ext.ContextResolver; + +{{>generatedAnnotation}} +public class JSON implements ContextResolver { + private ObjectMapper mapper; + + public JSON() { + mapper = new ObjectMapper(); + mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); + mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, true); + mapper.configure(DeserializationFeature.FAIL_ON_INVALID_SUBTYPE, true); + mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS); + mapper.enable(SerializationFeature.WRITE_ENUMS_USING_TO_STRING); + mapper.enable(DeserializationFeature.READ_ENUMS_USING_TO_STRING); + mapper.setDateFormat(new RFC3339DateFormat()); + {{#java8}} + mapper.registerModule(new JavaTimeModule()); + {{/java8}} + {{#joda}} + mapper.registerModule(new JodaModule()); + {{/joda}} + {{#threetenbp}} + ThreeTenModule module = new ThreeTenModule(); + module.addDeserializer(Instant.class, CustomInstantDeserializer.INSTANT); + module.addDeserializer(OffsetDateTime.class, CustomInstantDeserializer.OFFSET_DATE_TIME); + module.addDeserializer(ZonedDateTime.class, CustomInstantDeserializer.ZONED_DATE_TIME); + mapper.registerModule(module); + {{/threetenbp}} + JsonNullableModule jnm = new JsonNullableModule(); + mapper.registerModule(jnm); + } + + /** + * Set the date format for JSON (de)serialization with Date properties. + * @param dateFormat Date format + */ + public void setDateFormat(DateFormat dateFormat) { + mapper.setDateFormat(dateFormat); + } + + @Override + public ObjectMapper getContext(Class type) { + return mapper; + } + + /** + * Get the object mapper + * + * @return object mapper + */ + public ObjectMapper getMapper() { return mapper; } +} diff --git a/modules/openapi-generator/src/main/resources/Java/libraries/jersey2-experimental/anyof_model.mustache b/modules/openapi-generator/src/main/resources/Java/libraries/jersey2-experimental/anyof_model.mustache new file mode 100644 index 000000000000..a3702d221ad2 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/Java/libraries/jersey2-experimental/anyof_model.mustache @@ -0,0 +1,28 @@ +import javax.ws.rs.core.GenericType; +import javax.ws.rs.core.Response; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.Map; + +{{>additionalModelTypeAnnotations}}{{>generatedAnnotation}}{{>xmlAnnotation}} +public class {{classname}} extends AbstractOpenApiSchema{{#vendorExtensions.x-implements}}, {{{.}}}{{/vendorExtensions.x-implements}} { + + // store a list of schema names defined in anyOf + public final static Map schemas = new HashMap(); + + public {{classname}}() { + super("anyOf"); + } + + static { + {{#anyOf}} + schemas.put("{{{.}}}", new GenericType<{{{.}}}>() { + }); + {{/anyOf}} + } + + @Override + public Map getSchemas() { + return {{classname}}.schemas; + } +} diff --git a/modules/openapi-generator/src/main/resources/Java/libraries/jersey2-experimental/api.mustache b/modules/openapi-generator/src/main/resources/Java/libraries/jersey2-experimental/api.mustache new file mode 100644 index 000000000000..509ae48a50ef --- /dev/null +++ b/modules/openapi-generator/src/main/resources/Java/libraries/jersey2-experimental/api.mustache @@ -0,0 +1,262 @@ +package {{package}}; + +import {{invokerPackage}}.ApiException; +import {{invokerPackage}}.ApiClient; +import {{invokerPackage}}.ApiResponse; +import {{invokerPackage}}.Configuration; +import {{invokerPackage}}.Pair; + +import javax.ws.rs.core.GenericType; + +{{#imports}}import {{import}}; +{{/imports}} + +{{^fullJavaUtil}} +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +{{/fullJavaUtil}} +{{>generatedAnnotation}} +{{#operations}} +public class {{classname}} { + private ApiClient apiClient; + + public {{classname}}() { + this(Configuration.getDefaultApiClient()); + } + + public {{classname}}(ApiClient apiClient) { + this.apiClient = apiClient; + } + + /** + * Get the API cilent + * + * @return API client + */ + public ApiClient getApiClient() { + return apiClient; + } + + /** + * Set the API cilent + * + * @param apiClient an instance of API client + */ + public void setApiClient(ApiClient apiClient) { + this.apiClient = apiClient; + } + + {{#operation}} + {{^vendorExtensions.x-group-parameters}} + /** + * {{summary}} + * {{notes}} + {{#allParams}} + * @param {{paramName}} {{description}}{{#required}} (required){{/required}}{{^required}} (optional{{#defaultValue}}, default to {{.}}{{/defaultValue}}){{/required}} + {{/allParams}} + {{#returnType}} + * @return {{returnType}} + {{/returnType}} + * @throws ApiException if fails to make API call + {{#responses.0}} + * @http.response.details + + + {{#responses}} + + {{/responses}} +
      Status Code Description Response Headers
      {{code}} {{message}} {{#headers}} * {{baseName}} - {{description}}
      {{/headers}}{{^headers.0}} - {{/headers.0}}
      + {{/responses.0}} + {{#isDeprecated}} + * @deprecated + {{/isDeprecated}} + {{#externalDocs}} + * {{description}} + * @see {{summary}} Documentation + {{/externalDocs}} + */ + {{#isDeprecated}} + @Deprecated + {{/isDeprecated}} + public {{#returnType}}{{{returnType}}} {{/returnType}}{{^returnType}}void {{/returnType}}{{operationId}}({{#allParams}}{{{dataType}}} {{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) throws ApiException { + {{#returnType}}return {{/returnType}}{{operationId}}WithHttpInfo({{#allParams}}{{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}}){{#returnType}}.getData(){{/returnType}}; + } + {{/vendorExtensions.x-group-parameters}} + + {{^vendorExtensions.x-group-parameters}} + /** + * {{summary}} + * {{notes}} + {{#allParams}} + * @param {{paramName}} {{description}}{{#required}} (required){{/required}}{{^required}} (optional{{#defaultValue}}, default to {{.}}{{/defaultValue}}){{/required}} + {{/allParams}} + * @return ApiResponse<{{#returnType}}{{returnType}}{{/returnType}}{{^returnType}}Void{{/returnType}}> + * @throws ApiException if fails to make API call + {{#responses.0}} + * @http.response.details + + + {{#responses}} + + {{/responses}} +
      Status Code Description Response Headers
      {{code}} {{message}} {{#headers}} * {{baseName}} - {{description}}
      {{/headers}}{{^headers.0}} - {{/headers.0}}
      + {{/responses.0}} + {{#isDeprecated}} + * @deprecated + {{/isDeprecated}} + {{#externalDocs}} + * {{description}} + * @see {{summary}} Documentation + {{/externalDocs}} + */ + {{#isDeprecated}} + @Deprecated + {{/isDeprecated}} + public{{/vendorExtensions.x-group-parameters}}{{#vendorExtensions.x-group-parameters}}private{{/vendorExtensions.x-group-parameters}} ApiResponse<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}Void{{/returnType}}> {{operationId}}WithHttpInfo({{#allParams}}{{{dataType}}} {{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) throws ApiException { + Object localVarPostBody = {{#bodyParam}}{{paramName}}{{/bodyParam}}{{^bodyParam}}null{{/bodyParam}}; + {{#allParams}}{{#required}} + // verify the required parameter '{{paramName}}' is set + if ({{paramName}} == null) { + throw new ApiException(400, "Missing the required parameter '{{paramName}}' when calling {{operationId}}"); + } + {{/required}}{{/allParams}} + // create path and map variables + String localVarPath = "{{{path}}}"{{#pathParams}} + .replaceAll("\\{" + "{{baseName}}" + "\\}", apiClient.escapeString({{{paramName}}}.toString())){{/pathParams}}; + + // query params + {{javaUtilPrefix}}List localVarQueryParams = new {{javaUtilPrefix}}ArrayList(); + {{javaUtilPrefix}}Map localVarHeaderParams = new {{javaUtilPrefix}}HashMap(); + {{javaUtilPrefix}}Map localVarCookieParams = new {{javaUtilPrefix}}HashMap(); + {{javaUtilPrefix}}Map localVarFormParams = new {{javaUtilPrefix}}HashMap(); + + {{#queryParams}} + localVarQueryParams.addAll(apiClient.parameterToPairs("{{#collectionFormat}}{{{collectionFormat}}}{{/collectionFormat}}", "{{baseName}}", {{paramName}})); + {{/queryParams}} + + {{#headerParams}}if ({{paramName}} != null) + localVarHeaderParams.put("{{baseName}}", apiClient.parameterToString({{paramName}})); + {{/headerParams}} + + {{#cookieParams}}if ({{paramName}} != null) + localVarCookieParams.put("{{baseName}}", apiClient.parameterToString({{paramName}})); + {{/cookieParams}} + + {{#formParams}}if ({{paramName}} != null) + localVarFormParams.put("{{baseName}}", {{paramName}}); + {{/formParams}} + + final String[] localVarAccepts = { + {{#produces}}"{{{mediaType}}}"{{#hasMore}}, {{/hasMore}}{{/produces}} + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + + final String[] localVarContentTypes = { + {{#consumes}}"{{{mediaType}}}"{{#hasMore}}, {{/hasMore}}{{/consumes}} + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { {{#authMethods}}"{{name}}"{{#hasMore}}, {{/hasMore}}{{/authMethods}} }; + + {{#returnType}} + GenericType<{{{returnType}}}> localVarReturnType = new GenericType<{{{returnType}}}>() {}; + + {{/returnType}} + return apiClient.invokeAPI("{{classname}}.{{operationId}}", localVarPath, "{{httpMethod}}", localVarQueryParams, localVarPostBody, + localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAccept, localVarContentType, + localVarAuthNames, {{#returnType}}localVarReturnType{{/returnType}}{{^returnType}}null{{/returnType}}, {{#vendorExtensions.x-java-return-type-one-of}}new {{{returnType}}}(){{/vendorExtensions.x-java-return-type-one-of}}{{^vendorExtensions.x-java-return-type-one-of}}{{#vendorExtensions.x-java-return-type-any-of}}new {{{returnType}}}(){{/vendorExtensions.x-java-return-type-any-of}}{{^vendorExtensions.x-java-return-type-any-of}}null{{/vendorExtensions.x-java-return-type-any-of}}{{/vendorExtensions.x-java-return-type-one-of}}); + } + {{#vendorExtensions.x-group-parameters}} + + public class API{{operationId}}Request { + {{#allParams}} + private {{#isRequired}}final {{/isRequired}}{{{dataType}}} {{localVariablePrefix}}{{paramName}}; + {{/allParams}} + + private API{{operationId}}Request({{#pathParams}}{{{dataType}}} {{paramName}}{{#hasMore}}, {{/hasMore}}{{/pathParams}}) { + {{#pathParams}} + this.{{localVariablePrefix}}{{paramName}} = {{paramName}}; + {{/pathParams}} + } + {{#allParams}} + {{^isPathParam}} + + /** + * Set {{paramName}} + * @param {{paramName}} {{description}} ({{^required}}optional{{^isContainer}}{{#defaultValue}}, default to {{.}}{{/defaultValue}}{{/isContainer}}{{/required}}{{#required}}required{{/required}}) + * @return API{{operationId}}Request + */ + public API{{operationId}}Request {{paramName}}({{{dataType}}} {{paramName}}) { + this.{{localVariablePrefix}}{{paramName}} = {{paramName}}; + return this; + } + {{/isPathParam}} + {{/allParams}} + + /** + * Execute {{operationId}} request + {{#returnType}}* @return {{.}}{{/returnType}} + * @throws ApiException if fails to make API call + {{#responses.0}} + * @http.response.details + + + {{#responses}} + + {{/responses}} +
      Status Code Description Response Headers
      {{code}} {{message}} {{#headers}} * {{baseName}} - {{description}}
      {{/headers}}{{^headers.0}} - {{/headers.0}}
      + {{/responses.0}} + {{#isDeprecated}}* @deprecated{{/isDeprecated}} + */ + {{#isDeprecated}}@Deprecated{{/isDeprecated}} + public {{#returnType}}{{{.}}}{{/returnType}}{{^returnType}}void{{/returnType}} execute() throws ApiException { + {{#returnType}}return {{/returnType}}this.executeWithHttpInfo().getData(); + } + + /** + * Execute {{operationId}} request with HTTP info returned + * @return ApiResponse<{{#returnType}}{{.}}{{/returnType}}{{^returnType}}Void{{/returnType}}> + * @throws ApiException if fails to make API call + {{#responses.0}} + * @http.response.details + + + {{#responses}} + + {{/responses}} +
      Status Code Description Response Headers
      {{code}} {{message}} {{#headers}} * {{baseName}} - {{description}}
      {{/headers}}{{^headers.0}} - {{/headers.0}}
      + {{/responses.0}} + {{#isDeprecated}} + * @deprecated{{/isDeprecated}} + */ + {{#isDeprecated}} + @Deprecated + {{/isDeprecated}} + public ApiResponse<{{#returnType}}{{{.}}}{{/returnType}}{{^returnType}}Void{{/returnType}}> executeWithHttpInfo() throws ApiException { + return {{operationId}}WithHttpInfo({{#allParams}}{{localVariablePrefix}}{{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}}); + } + } + + /** + * {{summary}} + * {{notes}}{{#pathParams}} + * @param {{paramName}} {{description}} (required){{/pathParams}} + * @return {{operationId}}Request + * @throws ApiException if fails to make API call + {{#isDeprecated}}* @deprecated{{/isDeprecated}} + {{#externalDocs}}* {{description}} + * @see {{summary}} Documentation{{/externalDocs}} + */ + {{#isDeprecated}} + @Deprecated + {{/isDeprecated}} + public API{{operationId}}Request {{operationId}}({{#pathParams}}{{{dataType}}} {{paramName}}{{#hasMore}}, {{/hasMore}}{{/pathParams}}) throws ApiException { + return new API{{operationId}}Request({{#pathParams}}{{paramName}}{{#hasMore}}, {{/hasMore}}{{/pathParams}}); + } + {{/vendorExtensions.x-group-parameters}} + {{/operation}} +} +{{/operations}} diff --git a/modules/openapi-generator/src/main/resources/Java/libraries/jersey2-experimental/apiException.mustache b/modules/openapi-generator/src/main/resources/Java/libraries/jersey2-experimental/apiException.mustache new file mode 100644 index 000000000000..f0079c7bbece --- /dev/null +++ b/modules/openapi-generator/src/main/resources/Java/libraries/jersey2-experimental/apiException.mustache @@ -0,0 +1,99 @@ +{{>licenseInfo}} + +package {{invokerPackage}}; + +import java.util.Map; +import java.util.List; +{{#caseInsensitiveResponseHeaders}} +import java.util.Map.Entry; +import java.util.TreeMap; +{{/caseInsensitiveResponseHeaders}} + +/** + * API Exception + */ +{{>generatedAnnotation}} +public class ApiException extends{{#useRuntimeException}} RuntimeException {{/useRuntimeException}}{{^useRuntimeException}} Exception {{/useRuntimeException}}{ + private int code = 0; + private Map> responseHeaders = null; + private String responseBody = null; + + public ApiException() {} + + public ApiException(Throwable throwable) { + super(throwable); + } + + public ApiException(String message) { + super(message); + } + + public ApiException(String message, Throwable throwable, int code, Map> responseHeaders, String responseBody) { + super(message, throwable); + this.code = code; + {{#caseInsensitiveResponseHeaders}} + Map> headers = new TreeMap>(String.CASE_INSENSITIVE_ORDER); + for(Entry> entry : responseHeaders.entrySet()){ + headers.put(entry.getKey().toLowerCase(), entry.getValue()); + } + {{/caseInsensitiveResponseHeaders}} + this.responseHeaders = {{#caseInsensitiveResponseHeaders}}headers{{/caseInsensitiveResponseHeaders}}{{^caseInsensitiveResponseHeaders}}responseHeaders{{/caseInsensitiveResponseHeaders}}; + this.responseBody = responseBody; + } + + public ApiException(String message, int code, Map> responseHeaders, String responseBody) { + this(message, (Throwable) null, code, responseHeaders, responseBody); + } + + public ApiException(String message, Throwable throwable, int code, Map> responseHeaders) { + this(message, throwable, code, responseHeaders, null); + } + + public ApiException(int code, Map> responseHeaders, String responseBody) { + this((String) null, (Throwable) null, code, responseHeaders, responseBody); + } + + public ApiException(int code, String message) { + super(message); + this.code = code; + } + + public ApiException(int code, String message, Map> responseHeaders, String responseBody) { + this(code, message); + {{#caseInsensitiveResponseHeaders}} + Map> headers = new TreeMap>(String.CASE_INSENSITIVE_ORDER); + for(Entry> entry : responseHeaders.entrySet()){ + headers.put(entry.getKey().toLowerCase(), entry.getValue()); + } + {{/caseInsensitiveResponseHeaders}} + this.responseHeaders = {{#caseInsensitiveResponseHeaders}}headers{{/caseInsensitiveResponseHeaders}}{{^caseInsensitiveResponseHeaders}}responseHeaders{{/caseInsensitiveResponseHeaders}}; + this.responseBody = responseBody; + } + + /** + * Get the HTTP status code. + * + * @return HTTP status code + */ + public int getCode() { + return code; + } + + /** + * Get the HTTP response headers. + * + * @return A map of list of string + */ + public Map> getResponseHeaders() { + return responseHeaders; + } + + /** + * Get the HTTP response body. + * + * @return Response body in the form of string + */ + public String getResponseBody() { + return responseBody; + } +} diff --git a/modules/openapi-generator/src/main/resources/Java/libraries/jersey2-experimental/api_doc.mustache b/modules/openapi-generator/src/main/resources/Java/libraries/jersey2-experimental/api_doc.mustache new file mode 100644 index 000000000000..f162d1cc9748 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/Java/libraries/jersey2-experimental/api_doc.mustache @@ -0,0 +1,121 @@ +# {{classname}}{{#description}} + +{{description}}{{/description}} + +All URIs are relative to *{{basePath}}* + +Method | HTTP request | Description +------------- | ------------- | ------------- +{{#operations}}{{#operation}}[**{{operationId}}**]({{classname}}.md#{{operationId}}) | **{{httpMethod}}** {{path}} | {{#summary}}{{summary}}{{/summary}} +{{/operation}}{{/operations}} + +{{#operations}} +{{#operation}} + +## {{operationId}} + +{{^vendorExtensions.x-group-parameters}} +> {{#returnType}}{{returnType}} {{/returnType}}{{operationId}}({{#allParams}}{{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) +{{/vendorExtensions.x-group-parameters}} +{{#vendorExtensions.x-group-parameters}} +> {{#returnType}}{{returnType}} {{/returnType}}{{operationId}}({{#pathParams}}{{paramName}}{{#hasMore}}, {{/hasMore}}{{/pathParams}}){{#allParams}}{{^isPathParam}}.{{paramName}}({{paramName}}){{/isPathParam}}{{/allParams}}.execute(); +{{/vendorExtensions.x-group-parameters}} + +{{summary}}{{#notes}} + +{{{unescapedNotes}}}{{/notes}} + +### Example + +```java +// Import classes: +import {{{invokerPackage}}}.ApiClient; +import {{{invokerPackage}}}.ApiException; +import {{{invokerPackage}}}.Configuration;{{#hasAuthMethods}} +import {{{invokerPackage}}}.auth.*;{{/hasAuthMethods}} +import {{{invokerPackage}}}.models.*; +import {{{package}}}.{{{classname}}}; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("{{{basePath}}}"); + {{#hasAuthMethods}} + {{#authMethods}}{{#isBasic}}{{#isBasicBasic}} + // Configure HTTP basic authorization: {{{name}}} + HttpBasicAuth {{{name}}} = (HttpBasicAuth) defaultClient.getAuthentication("{{{name}}}"); + {{{name}}}.setUsername("YOUR USERNAME"); + {{{name}}}.setPassword("YOUR PASSWORD");{{/isBasicBasic}}{{#isBasicBearer}} + // Configure HTTP bearer authorization: {{{name}}} + HttpBearerAuth {{{name}}} = (HttpBearerAuth) defaultClient.getAuthentication("{{{name}}}"); + {{{name}}}.setBearerToken("BEARER TOKEN");{{/isBasicBearer}}{{/isBasic}}{{#isApiKey}} + // Configure API key authorization: {{{name}}} + ApiKeyAuth {{{name}}} = (ApiKeyAuth) defaultClient.getAuthentication("{{{name}}}"); + {{{name}}}.setApiKey("YOUR API KEY"); + // Uncomment the following line to set a prefix for the API key, e.g. "Token" (defaults to null) + //{{{name}}}.setApiKeyPrefix("Token");{{/isApiKey}}{{#isOAuth}} + // Configure OAuth2 access token for authorization: {{{name}}} + OAuth {{{name}}} = (OAuth) defaultClient.getAuthentication("{{{name}}}"); + {{{name}}}.setAccessToken("YOUR ACCESS TOKEN");{{/isOAuth}} + {{/authMethods}} + {{/hasAuthMethods}} + + {{{classname}}} apiInstance = new {{{classname}}}(defaultClient); + {{#allParams}} + {{{dataType}}} {{{paramName}}} = {{{example}}}; // {{{dataType}}} | {{{description}}} + {{/allParams}} + try { + {{^vendorExtensions.x-group-parameters}} + {{#returnType}}{{{returnType}}} result = {{/returnType}}apiInstance.{{{operationId}}}({{#allParams}}{{{paramName}}}{{#hasMore}}, {{/hasMore}}{{/allParams}}); + {{/vendorExtensions.x-group-parameters}} + {{#vendorExtensions.x-group-parameters}} + {{#returnType}}{{{returnType}}} result = {{/returnType}}api.{{operationId}}({{#pathParams}}{{paramName}}{{#hasMore}}, {{/hasMore}}{{/pathParams}}){{#allParams}}{{^isPathParam}} + .{{paramName}}({{paramName}}){{/isPathParam}}{{/allParams}} + .execute(); + {{/vendorExtensions.x-group-parameters}} + {{#returnType}} + System.out.println(result); + {{/returnType}} + } catch (ApiException e) { + System.err.println("Exception when calling {{{classname}}}#{{{operationId}}}"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } +} +``` + +### Parameters + +{{^allParams}}This endpoint does not need any parameter.{{/allParams}}{{#allParams}}{{#-last}} +Name | Type | Description | Notes +------------- | ------------- | ------------- | -------------{{/-last}}{{/allParams}} +{{#allParams}} **{{paramName}}** | {{#isPrimitiveType}}**{{dataType}}**{{/isPrimitiveType}}{{^isPrimitiveType}}{{#isFile}}**{{dataType}}**{{/isFile}}{{^isFile}}[**{{dataType}}**]({{baseType}}.md){{/isFile}}{{/isPrimitiveType}}| {{description}} |{{^required}} [optional]{{/required}}{{^isContainer}}{{#defaultValue}} [default to {{defaultValue}}]{{/defaultValue}}{{/isContainer}}{{#allowableValues}} [enum: {{#values}}{{{.}}}{{^-last}}, {{/-last}}{{/values}}]{{/allowableValues}} +{{/allParams}} + +### Return type + +{{#returnType}}{{#returnTypeIsPrimitive}}**{{returnType}}**{{/returnTypeIsPrimitive}}{{^returnTypeIsPrimitive}}[**{{returnType}}**]({{returnBaseType}}.md){{/returnTypeIsPrimitive}}{{/returnType}}{{^returnType}}null (empty response body){{/returnType}} + +### Authorization + +{{^authMethods}}No authorization required{{/authMethods}}{{#authMethods}}[{{name}}](../README.md#{{name}}){{^-last}}, {{/-last}}{{/authMethods}} + +### HTTP request headers + +- **Content-Type**: {{#consumes}}{{{mediaType}}}{{#hasMore}}, {{/hasMore}}{{/consumes}}{{^consumes}}Not defined{{/consumes}} +- **Accept**: {{#produces}}{{{mediaType}}}{{#hasMore}}, {{/hasMore}}{{/produces}}{{^produces}}Not defined{{/produces}} + +{{#responses.0}} +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +{{#responses}} +| **{{code}}** | {{message}} | {{#headers}} * {{baseName}} - {{description}}
      {{/headers}}{{^headers.0}} - {{/headers.0}} | +{{/responses}} +{{/responses.0}} + +{{/operation}} +{{/operations}} diff --git a/modules/openapi-generator/src/main/resources/Java/libraries/jersey2-experimental/api_test.mustache b/modules/openapi-generator/src/main/resources/Java/libraries/jersey2-experimental/api_test.mustache new file mode 100644 index 000000000000..5ee6e494084e --- /dev/null +++ b/modules/openapi-generator/src/main/resources/Java/libraries/jersey2-experimental/api_test.mustache @@ -0,0 +1,51 @@ +{{>licenseInfo}} + +package {{package}}; + +import {{invokerPackage}}.ApiException; +{{#imports}}import {{import}}; +{{/imports}} +import org.junit.Test; +import org.junit.Ignore; +import org.junit.Assert; + +{{^fullJavaUtil}} +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +{{/fullJavaUtil}} + +/** + * API tests for {{classname}} + */ +public class {{classname}}Test { + + private final {{classname}} api = new {{classname}}(); + + {{#operations}}{{#operation}} + /** + * {{summary}} + * + * {{notes}} + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void {{operationId}}Test() throws ApiException { + {{#allParams}} + //{{{dataType}}} {{paramName}} = null; + {{/allParams}} + {{^vendorExtensions.x-group-parameters}} + //{{#returnType}}{{{returnType}}} response = {{/returnType}}api.{{operationId}}({{#allParams}}{{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}}); + {{/vendorExtensions.x-group-parameters}} + {{#vendorExtensions.x-group-parameters}} + //{{#returnType}}{{{returnType}}} response = {{/returnType}}api.{{operationId}}({{#pathParams}}{{paramName}}{{#hasMore}}, {{/hasMore}}{{/pathParams}}){{#allParams}}{{^isPathParam}} + // .{{paramName}}({{paramName}}){{/isPathParam}}{{/allParams}} + // .execute(); + {{/vendorExtensions.x-group-parameters}} + // TODO: test validations + } + {{/operation}}{{/operations}} +} diff --git a/modules/openapi-generator/src/main/resources/Java/libraries/jersey2-experimental/auth/ApiKeyAuth.mustache b/modules/openapi-generator/src/main/resources/Java/libraries/jersey2-experimental/auth/ApiKeyAuth.mustache new file mode 100644 index 000000000000..1731f936fb87 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/Java/libraries/jersey2-experimental/auth/ApiKeyAuth.mustache @@ -0,0 +1,68 @@ +{{>licenseInfo}} + +package {{invokerPackage}}.auth; + +import {{invokerPackage}}.Pair; +import {{invokerPackage}}.ApiException; + +import java.net.URI; +import java.util.Map; +import java.util.List; + +{{>generatedAnnotation}} +public class ApiKeyAuth implements Authentication { + private final String location; + private final String paramName; + + private String apiKey; + private String apiKeyPrefix; + + public ApiKeyAuth(String location, String paramName) { + this.location = location; + this.paramName = paramName; + } + + public String getLocation() { + return location; + } + + public String getParamName() { + return paramName; + } + + public String getApiKey() { + return apiKey; + } + + public void setApiKey(String apiKey) { + this.apiKey = apiKey; + } + + public String getApiKeyPrefix() { + return apiKeyPrefix; + } + + public void setApiKeyPrefix(String apiKeyPrefix) { + this.apiKeyPrefix = apiKeyPrefix; + } + + @Override + public void applyToParams(List queryParams, Map headerParams, Map cookieParams, String payload, String method, URI uri) throws ApiException { + if (apiKey == null) { + return; + } + String value; + if (apiKeyPrefix != null) { + value = apiKeyPrefix + " " + apiKey; + } else { + value = apiKey; + } + if ("query".equals(location)) { + queryParams.add(new Pair(paramName, value)); + } else if ("header".equals(location)) { + headerParams.put(paramName, value); + } else if ("cookie".equals(location)) { + cookieParams.put(paramName, value); + } + } +} diff --git a/modules/openapi-generator/src/main/resources/Java/libraries/jersey2-experimental/auth/Authentication.mustache b/modules/openapi-generator/src/main/resources/Java/libraries/jersey2-experimental/auth/Authentication.mustache new file mode 100644 index 000000000000..46d9c1ab6ace --- /dev/null +++ b/modules/openapi-generator/src/main/resources/Java/libraries/jersey2-experimental/auth/Authentication.mustache @@ -0,0 +1,22 @@ +{{>licenseInfo}} + +package {{invokerPackage}}.auth; + +import {{invokerPackage}}.Pair; +import {{invokerPackage}}.ApiException; + +import java.net.URI; +import java.util.Map; +import java.util.List; + +public interface Authentication { + /** + * Apply authentication settings to header and query params. + * + * @param queryParams List of query parameters + * @param headerParams Map of header parameters + * @param cookieParams Map of cookie parameters + */ + void applyToParams(List queryParams, Map headerParams, Map cookieParams, String payload, String method, URI uri) throws ApiException; + +} diff --git a/modules/openapi-generator/src/main/resources/Java/libraries/jersey2-experimental/auth/HttpBasicAuth.mustache b/modules/openapi-generator/src/main/resources/Java/libraries/jersey2-experimental/auth/HttpBasicAuth.mustache new file mode 100644 index 000000000000..898bb97ee782 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/Java/libraries/jersey2-experimental/auth/HttpBasicAuth.mustache @@ -0,0 +1,62 @@ +{{>licenseInfo}} + +package {{invokerPackage}}.auth; + +import {{invokerPackage}}.Pair; +import {{invokerPackage}}.ApiException; + +{{^java8}} +import com.migcomponents.migbase64.Base64; +{{/java8}} +{{#java8}} +import java.util.Base64; +import java.nio.charset.StandardCharsets; +{{/java8}} + +import java.net.URI; +import java.util.Map; +import java.util.List; + +{{^java8}} +import java.io.UnsupportedEncodingException; +{{/java8}} + +{{>generatedAnnotation}} +public class HttpBasicAuth implements Authentication { + private String username; + private String password; + + public String getUsername() { + return username; + } + + public void setUsername(String username) { + this.username = username; + } + + public String getPassword() { + return password; + } + + public void setPassword(String password) { + this.password = password; + } + + @Override + public void applyToParams(List queryParams, Map headerParams, Map cookieParams, String payload, String method, URI uri) throws ApiException { + if (username == null && password == null) { + return; + } + String str = (username == null ? "" : username) + ":" + (password == null ? "" : password); +{{^java8}} + try { + headerParams.put("Authorization", "Basic " + Base64.encodeToString(str.getBytes("UTF-8"), false)); + } catch (UnsupportedEncodingException e) { + throw new RuntimeException(e); + } +{{/java8}} +{{#java8}} + headerParams.put("Authorization", "Basic " + Base64.getEncoder().encodeToString(str.getBytes(StandardCharsets.UTF_8))); +{{/java8}} + } +} diff --git a/modules/openapi-generator/src/main/resources/Java/libraries/jersey2-experimental/auth/HttpBearerAuth.mustache b/modules/openapi-generator/src/main/resources/Java/libraries/jersey2-experimental/auth/HttpBearerAuth.mustache new file mode 100644 index 000000000000..110a11ea7798 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/Java/libraries/jersey2-experimental/auth/HttpBearerAuth.mustache @@ -0,0 +1,51 @@ +{{>licenseInfo}} + +package {{invokerPackage}}.auth; + +import {{invokerPackage}}.Pair; +import {{invokerPackage}}.ApiException; + +import java.net.URI; +import java.util.Map; +import java.util.List; + +{{>generatedAnnotation}} +public class HttpBearerAuth implements Authentication { + private final String scheme; + private String bearerToken; + + public HttpBearerAuth(String scheme) { + this.scheme = scheme; + } + + /** + * Gets the token, which together with the scheme, will be sent as the value of the Authorization header. + * + * @return The bearer token + */ + public String getBearerToken() { + return bearerToken; + } + + /** + * Sets the token, which together with the scheme, will be sent as the value of the Authorization header. + * + * @param bearerToken The bearer token to send in the Authorization header + */ + public void setBearerToken(String bearerToken) { + this.bearerToken = bearerToken; + } + + @Override + public void applyToParams(List queryParams, Map headerParams, Map cookieParams, String payload, String method, URI uri) throws ApiException { + if(bearerToken == null) { + return; + } + + headerParams.put("Authorization", (scheme != null ? upperCaseBearer(scheme) + " " : "") + bearerToken); + } + + private static String upperCaseBearer(String scheme) { + return ("bearer".equalsIgnoreCase(scheme)) ? "Bearer" : scheme; + } +} diff --git a/modules/openapi-generator/src/main/resources/Java/libraries/jersey2-experimental/auth/HttpSignatureAuth.mustache b/modules/openapi-generator/src/main/resources/Java/libraries/jersey2-experimental/auth/HttpSignatureAuth.mustache new file mode 100644 index 000000000000..3a856e3bc3c5 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/Java/libraries/jersey2-experimental/auth/HttpSignatureAuth.mustache @@ -0,0 +1,115 @@ +{{>licenseInfo}} + +package {{invokerPackage}}.auth; + +import {{invokerPackage}}.Pair; +import {{invokerPackage}}.ApiException; + +import java.net.URI; +import java.net.URLEncoder; +import java.security.MessageDigest; +import java.security.Key; +import java.text.SimpleDateFormat; +import java.util.ArrayList; +import java.util.Base64; +import java.util.Date; +import java.util.Locale; +import java.util.Map; +import java.util.List; + +import org.tomitribe.auth.signatures.*; + +public class HttpSignatureAuth implements Authentication { + + private Signer signer; + + private String name; + + private Algorithm algorithm; + + private List headers; + + public HttpSignatureAuth(String name, Algorithm algorithm, List headers) { + this.name = name; + this.algorithm = algorithm; + this.headers = headers; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public Algorithm getAlgorithm() { + return algorithm; + } + + public void setAlgorithm(Algorithm algorithm) { + this.algorithm = algorithm; + } + + public List getHeaders() { + return headers; + } + + public void setHeaders(List headers) { + this.headers = headers; + } + + public Signer getSigner() { + return signer; + } + + public void setSigner(Signer signer) { + this.signer = signer; + } + + public void setup(Key key) throws ApiException { + if (key == null) { + throw new ApiException("key (java.security.Key) cannot be null"); + } + + signer = new Signer(key, new Signature(name, algorithm, null, headers)); + } + + @Override + public void applyToParams(List queryParams, Map headerParams, Map cookieParams, + String payload, String method, URI uri) throws ApiException { + try { + if (headers.contains("host")) { + headerParams.put("host", uri.getHost()); + } + + if (headers.contains("date")) { + headerParams.put("date", new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss zzz", Locale.US).format(new Date())); + } + + if (headers.contains("digest")) { + headerParams.put("digest", "SHA-256=" + new String(Base64.getEncoder().encode(MessageDigest.getInstance("SHA-256").digest(payload.getBytes())))); + } + + if (signer == null) { + throw new ApiException("Signer cannot be null. Please run the method `setup` to set it up correctly"); + } + + // construct the path with the URL query string + String path = uri.getPath(); + + List urlQueries = new ArrayList(); + for (Pair queryParam : queryParams) { + urlQueries.add(queryParam.getName() + "=" + URLEncoder.encode(queryParam.getValue(), "utf8").replaceAll("\\+", "%20")); + } + + if (!urlQueries.isEmpty()) { + path = path + "?" + String.join("&", urlQueries); + } + + headerParams.put("Authorization", signer.sign(method, path, headerParams).toString()); + } catch (Exception ex) { + throw new ApiException("Failed to create signature in the HTTP request header: " + ex.toString()); + } + } +} diff --git a/modules/openapi-generator/src/main/resources/Java/libraries/jersey2-experimental/auth/OAuth.mustache b/modules/openapi-generator/src/main/resources/Java/libraries/jersey2-experimental/auth/OAuth.mustache new file mode 100644 index 000000000000..8622798ad378 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/Java/libraries/jersey2-experimental/auth/OAuth.mustache @@ -0,0 +1,30 @@ +{{>licenseInfo}} + +package {{invokerPackage}}.auth; + +import {{invokerPackage}}.Pair; +import {{invokerPackage}}.ApiException; + +import java.net.URI; +import java.util.Map; +import java.util.List; + +{{>generatedAnnotation}} +public class OAuth implements Authentication { + private String accessToken; + + public String getAccessToken() { + return accessToken; + } + + public void setAccessToken(String accessToken) { + this.accessToken = accessToken; + } + + @Override + public void applyToParams(List queryParams, Map headerParams, Map cookieParams, String payload, String method, URI uri) throws ApiException { + if (accessToken != null) { + headerParams.put("Authorization", "Bearer " + accessToken); + } + } +} diff --git a/modules/openapi-generator/src/main/resources/Java/libraries/jersey2-experimental/auth/OAuthFlow.mustache b/modules/openapi-generator/src/main/resources/Java/libraries/jersey2-experimental/auth/OAuthFlow.mustache new file mode 100644 index 000000000000..002e9572f33f --- /dev/null +++ b/modules/openapi-generator/src/main/resources/Java/libraries/jersey2-experimental/auth/OAuthFlow.mustache @@ -0,0 +1,7 @@ +{{>licenseInfo}} + +package {{invokerPackage}}.auth; + +public enum OAuthFlow { + accessCode, implicit, password, application +} diff --git a/modules/openapi-generator/src/main/resources/Java/libraries/jersey2-experimental/build.gradle.mustache b/modules/openapi-generator/src/main/resources/Java/libraries/jersey2-experimental/build.gradle.mustache new file mode 100644 index 000000000000..cdb451adb345 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/Java/libraries/jersey2-experimental/build.gradle.mustache @@ -0,0 +1,170 @@ +apply plugin: 'idea' +apply plugin: 'eclipse' + +group = '{{groupId}}' +version = '{{artifactVersion}}' + +buildscript { + repositories { + maven { url "https://repo1.maven.org/maven2" } + jcenter() + } + dependencies { + classpath 'com.android.tools.build:gradle:2.3.+' + classpath 'com.github.dcendents:android-maven-gradle-plugin:1.5' + } +} + +repositories { + jcenter() +} + + +if(hasProperty('target') && target == 'android') { + + apply plugin: 'com.android.library' + apply plugin: 'com.github.dcendents.android-maven' + + android { + compileSdkVersion 25 + buildToolsVersion '25.0.2' + defaultConfig { + minSdkVersion 14 + targetSdkVersion 25 + } + compileOptions { + {{#supportJava6}} + sourceCompatibility JavaVersion.VERSION_1_6 + targetCompatibility JavaVersion.VERSION_1_6 + {{/supportJava6}} + {{^supportJava6}} + {{#java8}} + sourceCompatibility JavaVersion.VERSION_1_8 + targetCompatibility JavaVersion.VERSION_1_8 + {{/java8}} + {{^java8}} + sourceCompatibility JavaVersion.VERSION_1_7 + targetCompatibility JavaVersion.VERSION_1_7 + {{/java8}} + {{/supportJava6}} + } + + // Rename the aar correctly + libraryVariants.all { variant -> + variant.outputs.each { output -> + def outputFile = output.outputFile + if (outputFile != null && outputFile.name.endsWith('.aar')) { + def fileName = "${project.name}-${variant.baseName}-${version}.aar" + output.outputFile = new File(outputFile.parent, fileName) + } + } + } + + dependencies { + provided 'javax.annotation:jsr250-api:1.0' + } + } + + afterEvaluate { + android.libraryVariants.all { variant -> + def task = project.tasks.create "jar${variant.name.capitalize()}", Jar + task.description = "Create jar artifact for ${variant.name}" + task.dependsOn variant.javaCompile + task.from variant.javaCompile.destinationDir + task.destinationDir = project.file("${project.buildDir}/outputs/jar") + task.archiveName = "${project.name}-${variant.baseName}-${version}.jar" + artifacts.add('archives', task); + } + } + + task sourcesJar(type: Jar) { + from android.sourceSets.main.java.srcDirs + classifier = 'sources' + } + + artifacts { + archives sourcesJar + } + +} else { + + apply plugin: 'java' + apply plugin: 'maven' + {{#supportJava6}} + sourceCompatibility = JavaVersion.VERSION_1_6 + targetCompatibility = JavaVersion.VERSION_1_6 + {{/supportJava6}} + {{^supportJava6}} + {{#java8}} + sourceCompatibility = JavaVersion.VERSION_1_8 + targetCompatibility = JavaVersion.VERSION_1_8 + {{/java8}} + {{^java8}} + sourceCompatibility = JavaVersion.VERSION_1_7 + targetCompatibility = JavaVersion.VERSION_1_7 + {{/java8}} + {{/supportJava6}} + + install { + repositories.mavenInstaller { + pom.artifactId = '{{artifactId}}' + } + } + + task execute(type:JavaExec) { + main = System.getProperty('mainClass') + classpath = sourceSets.main.runtimeClasspath + } +} + +ext { + swagger_annotations_version = "1.5.22" + jackson_version = "2.10.3" + jackson_databind_version = "2.10.3" + jackson_databind_nullable_version = "0.2.1" + {{#supportJava6}} + jersey_version = "2.6" + commons_io_version=2.5 + commons_lang3_version=3.6 + {{/supportJava6}} + {{^supportJava6}} + jersey_version = "2.27" + {{/supportJava6}} + junit_version = "4.13" + {{#threetenbp}} + threetenbp_version = "2.9.10" + {{/threetenbp}} +} + +dependencies { + compile "io.swagger:swagger-annotations:$swagger_annotations_version" + compile "com.google.code.findbugs:jsr305:3.0.2" + compile "org.glassfish.jersey.core:jersey-client:$jersey_version" + compile "org.glassfish.jersey.media:jersey-media-multipart:$jersey_version" + compile "org.glassfish.jersey.media:jersey-media-json-jackson:$jersey_version" + compile "com.fasterxml.jackson.core:jackson-core:$jackson_version" + compile "com.fasterxml.jackson.core:jackson-annotations:$jackson_version" + compile "com.fasterxml.jackson.core:jackson-databind:$jackson_databind_version" + compile "org.openapitools:jackson-databind-nullable:$jackson_databind_nullable_version" + {{#joda}} + compile "com.fasterxml.jackson.datatype:jackson-datatype-joda:$jackson_version" + {{/joda}} + {{#java8}} + compile "com.fasterxml.jackson.datatype:jackson-datatype-jsr310:$jackson_version" + {{/java8}} + {{#supportJava6}} + compile "commons-io:commons-io:$commons_io_version" + compile "org.apache.commons:commons-lang3:$commons_lang3_version" + {{/supportJava6}} + {{#threetenbp}} + compile "com.github.joschi.jackson:jackson-datatype-threetenbp:$threetenbp_version" + {{/threetenbp}} + {{^java8}} + compile "com.brsanthu:migbase64:2.2" + {{/java8}} + testCompile "junit:junit:$junit_version" +} + +javadoc { + options.tags = [ "http.response.details:a:Http Response Details" ] +} diff --git a/modules/openapi-generator/src/main/resources/Java/libraries/jersey2-experimental/build.sbt.mustache b/modules/openapi-generator/src/main/resources/Java/libraries/jersey2-experimental/build.sbt.mustache new file mode 100644 index 000000000000..abb91ecdc990 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/Java/libraries/jersey2-experimental/build.sbt.mustache @@ -0,0 +1,38 @@ +lazy val root = (project in file(".")). + settings( + organization := "{{groupId}}", + name := "{{artifactId}}", + version := "{{artifactVersion}}", + scalaVersion := "2.11.4", + scalacOptions ++= Seq("-feature"), + javacOptions in compile ++= Seq("-Xlint:deprecation"), + publishArtifact in (Compile, packageDoc) := false, + resolvers += Resolver.mavenLocal, + libraryDependencies ++= Seq( + "io.swagger" % "swagger-annotations" % "1.5.22", + "org.glassfish.jersey.core" % "jersey-client" % {{#supportJava6}}"2.6"{{/supportJava6}}{{^supportJava6}}"2.25.1"{{/supportJava6}}, + "org.glassfish.jersey.media" % "jersey-media-multipart" % {{#supportJava6}}"2.6"{{/supportJava6}}{{^supportJava6}}"2.25.1"{{/supportJava6}}, + "org.glassfish.jersey.media" % "jersey-media-json-jackson" % {{#supportJava6}}"2.6"{{/supportJava6}}{{^supportJava6}}"2.25.1"{{/supportJava6}}, + "com.fasterxml.jackson.core" % "jackson-core" % "2.10.3" % "compile", + "com.fasterxml.jackson.core" % "jackson-annotations" % "2.10.3" % "compile", + "com.fasterxml.jackson.core" % "jackson-databind" % "2.10.3" % "compile", + {{#joda}} + "com.fasterxml.jackson.datatype" % "jackson-datatype-joda" % "2.9.10" % "compile", + {{/joda}} + {{#java8}} + "com.fasterxml.jackson.datatype" % "jackson-datatype-jsr310" % "2.9.10" % "compile", + {{/java8}} + {{#threetenbp}} + "com.github.joschi.jackson" % "jackson-datatype-threetenbp" % "2.9.10" % "compile", + {{/threetenbp}} + {{^java8}} + "com.brsanthu" % "migbase64" % "2.2", + {{/java8}} + {{#supportJava6}} + "org.apache.commons" % "commons-lang3" % "3.6", + "commons-io" % "commons-io" % "2.5", + {{/supportJava6}} + "junit" % "junit" % "4.13" % "test", + "com.novocode" % "junit-interface" % "0.10" % "test" + ) + ) diff --git a/modules/openapi-generator/src/main/resources/Java/libraries/jersey2-experimental/model.mustache b/modules/openapi-generator/src/main/resources/Java/libraries/jersey2-experimental/model.mustache new file mode 100644 index 000000000000..02787f8bb7ff --- /dev/null +++ b/modules/openapi-generator/src/main/resources/Java/libraries/jersey2-experimental/model.mustache @@ -0,0 +1,47 @@ +{{>licenseInfo}} + +package {{package}}; + +{{#useReflectionEqualsHashCode}} +import org.apache.commons.lang3.builder.EqualsBuilder; +import org.apache.commons.lang3.builder.HashCodeBuilder; +{{/useReflectionEqualsHashCode}} +{{^supportJava6}} +import java.util.Objects; +import java.util.Arrays; +{{/supportJava6}} +{{#supportJava6}} +import org.apache.commons.lang3.ObjectUtils; +{{/supportJava6}} +{{#imports}} +import {{import}}; +{{/imports}} +{{#serializableModel}} +import java.io.Serializable; +{{/serializableModel}} +{{#jackson}} +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +{{#withXml}} +import com.fasterxml.jackson.dataformat.xml.annotation.*; +{{/withXml}} +{{/jackson}} +{{#withXml}} +import javax.xml.bind.annotation.*; +{{/withXml}} +{{#parcelableModel}} +import android.os.Parcelable; +import android.os.Parcel; +{{/parcelableModel}} +{{#useBeanValidation}} +import javax.validation.constraints.*; +import javax.validation.Valid; +{{/useBeanValidation}} +{{#performBeanValidation}} +import org.hibernate.validator.constraints.*; +{{/performBeanValidation}} + +{{#models}} +{{#model}} +{{#isEnum}}{{>modelEnum}}{{/isEnum}}{{^isEnum}}{{#oneOf}}{{#-first}}{{>oneof_model}}{{/-first}}{{/oneOf}}{{^oneOf}}{{#anyOf}}{{#-first}}{{>anyof_model}}{{/-first}}{{/anyOf}}{{^anyOf}}{{>pojo}}{{/anyOf}}{{/oneOf}}{{/isEnum}} +{{/model}} +{{/models}} diff --git a/modules/openapi-generator/src/main/resources/Java/libraries/jersey2-experimental/oneof_model.mustache b/modules/openapi-generator/src/main/resources/Java/libraries/jersey2-experimental/oneof_model.mustache new file mode 100644 index 000000000000..b5d4442e6081 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/Java/libraries/jersey2-experimental/oneof_model.mustache @@ -0,0 +1,41 @@ +import javax.ws.rs.core.GenericType; +import javax.ws.rs.core.Response; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.Map; + +{{>additionalModelTypeAnnotations}}{{>generatedAnnotation}}{{>xmlAnnotation}} +public class {{classname}} extends AbstractOpenApiSchema{{#vendorExtensions.x-implements}}, {{{.}}}{{/vendorExtensions.x-implements}} { + + // store a list of schema names defined in oneOf + public final static Map schemas = new HashMap(); + + public {{classname}}() { + super("oneOf"); + } + + static { + {{#oneOf}} + schemas.put("{{{.}}}", new GenericType<{{{.}}}>() { + }); + {{/oneOf}} + } + + @Override + public Map getSchemas() { + return {{classname}}.schemas; + } + + @Override + public void setActualInstance(Object instance) { + {{#oneOf}} + if (instance instanceof {{{.}}}) { + super.setActualInstance(instance); + return; + } + + {{/oneOf}} + throw new RuntimeException("Invalid instance type. Must be {{#oneOf}}{{{.}}}{{^-last}}, {{/-last}}{{/oneOf}}"); + } + +} diff --git a/modules/openapi-generator/src/main/resources/Java/libraries/jersey2-experimental/pojo.mustache b/modules/openapi-generator/src/main/resources/Java/libraries/jersey2-experimental/pojo.mustache new file mode 100644 index 000000000000..c438cd43eb72 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/Java/libraries/jersey2-experimental/pojo.mustache @@ -0,0 +1,369 @@ +/** + * {{#description}}{{.}}{{/description}}{{^description}}{{classname}}{{/description}} + */{{#description}} +@ApiModel(description = "{{{description}}}"){{/description}} +{{#jackson}} +@JsonPropertyOrder({ +{{#vars}} + {{classname}}.JSON_PROPERTY_{{nameInSnakeCase}}{{^-last}},{{/-last}} +{{/vars}} +}) +{{/jackson}} +{{>additionalModelTypeAnnotations}}{{>generatedAnnotation}}{{#discriminator}}{{>typeInfoAnnotation}}{{/discriminator}}{{>xmlAnnotation}} +public class {{classname}} {{#parent}}extends {{{parent}}} {{/parent}}{{#vendorExtensions.x-implements}}{{#-first}}implements {{{.}}}{{/-first}}{{^-first}}, {{{.}}}{{/-first}}{{#-last}} {{/-last}}{{/vendorExtensions.x-implements}}{ +{{#serializableModel}} + private static final long serialVersionUID = 1L; + +{{/serializableModel}} + {{#vars}} + {{#isEnum}} + {{^isContainer}} +{{>modelInnerEnum}} + {{/isContainer}} + {{#isContainer}} + {{#mostInnerItems}} +{{>modelInnerEnum}} + {{/mostInnerItems}} + {{/isContainer}} + {{/isEnum}} + {{#gson}} + public static final String SERIALIZED_NAME_{{nameInSnakeCase}} = "{{baseName}}"; + {{/gson}} + {{#jackson}} + public static final String JSON_PROPERTY_{{nameInSnakeCase}} = "{{baseName}}"; + {{/jackson}} + {{#withXml}} + {{#isXmlAttribute}} + @XmlAttribute(name = "{{#xmlName}}{{xmlName}}{{/xmlName}}{{^xmlName}}{{baseName}}{{/xmlName}}") + {{/isXmlAttribute}} + {{^isXmlAttribute}} + {{^isContainer}} + @XmlElement({{#xmlNamespace}}namespace="{{xmlNamespace}}", {{/xmlNamespace}}name = "{{#xmlName}}{{xmlName}}{{/xmlName}}{{^xmlName}}{{baseName}}{{/xmlName}}") + {{/isContainer}} + {{#isContainer}} + // Is a container wrapped={{isXmlWrapped}} + {{#items}} + // items.name={{name}} items.baseName={{baseName}} items.xmlName={{xmlName}} items.xmlNamespace={{xmlNamespace}} + // items.example={{example}} items.type={{dataType}} + @XmlElement({{#xmlNamespace}}namespace="{{xmlNamespace}}", {{/xmlNamespace}}name = "{{#xmlName}}{{xmlName}}{{/xmlName}}{{^xmlName}}{{baseName}}{{/xmlName}}") + {{/items}} + {{#isXmlWrapped}} + @XmlElementWrapper({{#xmlNamespace}}namespace="{{xmlNamespace}}", {{/xmlNamespace}}name = "{{#xmlName}}{{xmlName}}{{/xmlName}}{{^xmlName}}{{baseName}}{{/xmlName}}") + {{/isXmlWrapped}} + {{/isContainer}} + {{/isXmlAttribute}} + {{/withXml}} + {{#gson}} + @SerializedName(SERIALIZED_NAME_{{nameInSnakeCase}}) + {{/gson}} + {{#vendorExtensions.x-is-jackson-optional-nullable}} + {{#isContainer}} + private JsonNullable<{{{datatypeWithEnum}}}> {{name}} = JsonNullable.<{{{datatypeWithEnum}}}>undefined(); + {{/isContainer}} + {{^isContainer}} + private JsonNullable<{{{datatypeWithEnum}}}> {{name}} = JsonNullable.<{{{datatypeWithEnum}}}>{{#defaultValue}}of({{{.}}}){{/defaultValue}}{{^defaultValue}}undefined(){{/defaultValue}}; + {{/isContainer}} + {{/vendorExtensions.x-is-jackson-optional-nullable}} + {{^vendorExtensions.x-is-jackson-optional-nullable}} + {{#isContainer}} + private {{{datatypeWithEnum}}} {{name}}{{#required}}{{#defaultValue}} = {{{.}}}{{/defaultValue}}{{/required}}{{^required}} = null{{/required}}; + {{/isContainer}} + {{^isContainer}} + private {{{datatypeWithEnum}}} {{name}}{{#defaultValue}} = {{{.}}}{{/defaultValue}}; + {{/isContainer}} + {{/vendorExtensions.x-is-jackson-optional-nullable}} + + {{/vars}} + {{#parcelableModel}} + public {{classname}}() { + {{#parent}} + super(); + {{/parent}} + {{#gson}} + {{#discriminator}} + this.{{{discriminatorName}}} = this.getClass().getSimpleName(); + {{/discriminator}} + {{/gson}} + } + {{/parcelableModel}} + {{^parcelableModel}} + {{#gson}} + {{#discriminator}} + public {{classname}}() { + this.{{{discriminatorName}}} = this.getClass().getSimpleName(); + } + {{/discriminator}} + {{/gson}} + {{/parcelableModel}} + {{#vars}} + + {{^isReadOnly}} + public {{classname}} {{name}}({{{datatypeWithEnum}}} {{name}}) { + {{#vendorExtensions.x-is-jackson-optional-nullable}}this.{{name}} = JsonNullable.<{{{datatypeWithEnum}}}>of({{name}});{{/vendorExtensions.x-is-jackson-optional-nullable}} + {{^vendorExtensions.x-is-jackson-optional-nullable}}this.{{name}} = {{name}};{{/vendorExtensions.x-is-jackson-optional-nullable}} + return this; + } + {{#isListContainer}} + + public {{classname}} add{{nameInCamelCase}}Item({{{items.datatypeWithEnum}}} {{name}}Item) { + {{#vendorExtensions.x-is-jackson-optional-nullable}} + if (this.{{name}} == null || !this.{{name}}.isPresent()) { + this.{{name}} = JsonNullable.<{{{datatypeWithEnum}}}>of({{{defaultValue}}}); + } + try { + this.{{name}}.get().add({{name}}Item); + } catch (java.util.NoSuchElementException e) { + // this can never happen, as we make sure above that the value is present + } + return this; + {{/vendorExtensions.x-is-jackson-optional-nullable}} + {{^vendorExtensions.x-is-jackson-optional-nullable}} + {{^required}} + if (this.{{name}} == null) { + this.{{name}} = {{{defaultValue}}}; + } + {{/required}} + this.{{name}}.add({{name}}Item); + return this; + {{/vendorExtensions.x-is-jackson-optional-nullable}} + } + {{/isListContainer}} + {{#isMapContainer}} + + public {{classname}} put{{nameInCamelCase}}Item(String key, {{{items.datatypeWithEnum}}} {{name}}Item) { + {{#vendorExtensions.x-is-jackson-optional-nullable}} + if (this.{{name}} == null || !this.{{name}}.isPresent()) { + this.{{name}} = JsonNullable.<{{{datatypeWithEnum}}}>of({{{defaultValue}}}); + } + try { + this.{{name}}.get().put(key, {{name}}Item); + } catch (java.util.NoSuchElementException e) { + // this can never happen, as we make sure above that the value is present + } + return this; + {{/vendorExtensions.x-is-jackson-optional-nullable}} + {{^vendorExtensions.x-is-jackson-optional-nullable}} + {{^required}} + if (this.{{name}} == null) { + this.{{name}} = {{{defaultValue}}}; + } + {{/required}} + this.{{name}}.put(key, {{name}}Item); + return this; + {{/vendorExtensions.x-is-jackson-optional-nullable}} + } + {{/isMapContainer}} + + {{/isReadOnly}} + /** + {{#description}} + * {{description}} + {{/description}} + {{^description}} + * Get {{name}} + {{/description}} + {{#minimum}} + * minimum: {{minimum}} + {{/minimum}} + {{#maximum}} + * maximum: {{maximum}} + {{/maximum}} + * @return {{name}} + **/ +{{#required}} +{{#isNullable}} + @javax.annotation.Nullable +{{/isNullable}} +{{/required}} +{{^required}} + @javax.annotation.Nullable +{{/required}} +{{#useBeanValidation}}{{>beanValidation}}{{/useBeanValidation}} @ApiModelProperty({{#example}}example = "{{{example}}}", {{/example}}{{#required}}required = {{required}}, {{/required}}value = "{{{description}}}") +{{#vendorExtensions.x-extra-annotation}} + {{{vendorExtensions.x-extra-annotation}}} +{{/vendorExtensions.x-extra-annotation}} +{{#vendorExtensions.x-is-jackson-optional-nullable}} + {{!unannotated, Jackson would pick this up automatically and add it *in addition* to the _JsonNullable getter field}} + @JsonIgnore +{{/vendorExtensions.x-is-jackson-optional-nullable}} +{{^vendorExtensions.x-is-jackson-optional-nullable}}{{#jackson}}{{> jackson_annotations}}{{/jackson}}{{/vendorExtensions.x-is-jackson-optional-nullable}} + public {{{datatypeWithEnum}}} {{getter}}() { + {{#vendorExtensions.x-is-jackson-optional-nullable}} + {{#isReadOnly}}{{! A readonly attribute doesn't have setter => jackson will set null directly if explicitly returned by API, so make sure we have an empty JsonNullable}} + if ({{name}} == null) { + {{name}} = JsonNullable.<{{{datatypeWithEnum}}}>{{#defaultValue}}of({{{.}}}){{/defaultValue}}{{^defaultValue}}undefined(){{/defaultValue}}; + } + {{/isReadOnly}} + return {{name}}.orElse(null); + {{/vendorExtensions.x-is-jackson-optional-nullable}} + {{^vendorExtensions.x-is-jackson-optional-nullable}} + return {{name}}; + {{/vendorExtensions.x-is-jackson-optional-nullable}} + } + + {{#vendorExtensions.x-is-jackson-optional-nullable}} +{{> jackson_annotations}} + public JsonNullable<{{{datatypeWithEnum}}}> {{getter}}_JsonNullable() { + return {{name}}; + } + {{/vendorExtensions.x-is-jackson-optional-nullable}}{{#vendorExtensions.x-is-jackson-optional-nullable}} + @JsonProperty(JSON_PROPERTY_{{nameInSnakeCase}}) + {{#isReadOnly}}private{{/isReadOnly}}{{^isReadOnly}}public{{/isReadOnly}} void {{setter}}_JsonNullable(JsonNullable<{{{datatypeWithEnum}}}> {{name}}) { + {{! For getters/setters that have name differing from attribute name, we must include setter (albeit private) for jackson to be able to set the attribute}} + this.{{name}} = {{name}}; + } + {{/vendorExtensions.x-is-jackson-optional-nullable}} + + {{^isReadOnly}} + public void {{setter}}({{{datatypeWithEnum}}} {{name}}) { + {{#vendorExtensions.x-is-jackson-optional-nullable}} + this.{{name}} = JsonNullable.<{{{datatypeWithEnum}}}>of({{name}}); + {{/vendorExtensions.x-is-jackson-optional-nullable}} + {{^vendorExtensions.x-is-jackson-optional-nullable}} + this.{{name}} = {{name}}; + {{/vendorExtensions.x-is-jackson-optional-nullable}} + } + {{/isReadOnly}} + + {{/vars}} + +{{^supportJava6}} + @Override + public boolean equals(java.lang.Object o) { + {{#useReflectionEqualsHashCode}} + return EqualsBuilder.reflectionEquals(this, o, false, null, true); + {{/useReflectionEqualsHashCode}} + {{^useReflectionEqualsHashCode}} + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + }{{#hasVars}} + {{classname}} {{classVarName}} = ({{classname}}) o; + return {{#vars}}{{#isByteArray}}Arrays{{/isByteArray}}{{^isByteArray}}Objects{{/isByteArray}}.equals(this.{{name}}, {{classVarName}}.{{name}}){{#hasMore}} && + {{/hasMore}}{{/vars}}{{#parent}} && + super.equals(o){{/parent}};{{/hasVars}}{{^hasVars}} + return {{#parent}}super.equals(o){{/parent}}{{^parent}}true{{/parent}};{{/hasVars}} + {{/useReflectionEqualsHashCode}} + } + + @Override + public int hashCode() { + {{#useReflectionEqualsHashCode}} + return HashCodeBuilder.reflectionHashCode(this); + {{/useReflectionEqualsHashCode}} + {{^useReflectionEqualsHashCode}} + return Objects.hash({{#vars}}{{^isByteArray}}{{name}}{{/isByteArray}}{{#isByteArray}}Arrays.hashCode({{name}}){{/isByteArray}}{{#hasMore}}, {{/hasMore}}{{/vars}}{{#parent}}{{#hasVars}}, {{/hasVars}}super.hashCode(){{/parent}}); + {{/useReflectionEqualsHashCode}} + } + +{{/supportJava6}} +{{#supportJava6}} + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + }{{#hasVars}} + {{classname}} {{classVarName}} = ({{classname}}) o; + return {{#vars}}ObjectUtils.equals(this.{{name}}, {{classVarName}}.{{name}}){{#hasMore}} && + {{/hasMore}}{{/vars}}{{#parent}} && + super.equals(o){{/parent}};{{/hasVars}}{{^hasVars}} + return true;{{/hasVars}} + } + + @Override + public int hashCode() { + return ObjectUtils.hashCodeMulti({{#vars}}{{name}}{{#hasMore}}, {{/hasMore}}{{/vars}}{{#parent}}{{#hasVars}}, {{/hasVars}}super.hashCode(){{/parent}}); + } + +{{/supportJava6}} + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class {{classname}} {\n"); + {{#parent}} + sb.append(" ").append(toIndentedString(super.toString())).append("\n"); + {{/parent}} + {{#vars}} + sb.append(" {{name}}: ").append(toIndentedString({{name}})).append("\n"); + {{/vars}} + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } + +{{#parcelableModel}} + + public void writeToParcel(Parcel out, int flags) { +{{#model}} +{{#isArrayModel}} + out.writeList(this); +{{/isArrayModel}} +{{^isArrayModel}} +{{#parent}} + super.writeToParcel(out, flags); +{{/parent}} +{{#vars}} + out.writeValue({{name}}); +{{/vars}} +{{/isArrayModel}} +{{/model}} + } + + {{classname}}(Parcel in) { +{{#isArrayModel}} + in.readTypedList(this, {{arrayModelType}}.CREATOR); +{{/isArrayModel}} +{{^isArrayModel}} +{{#parent}} + super(in); +{{/parent}} +{{#vars}} +{{#isPrimitiveType}} + {{name}} = ({{{datatypeWithEnum}}})in.readValue(null); +{{/isPrimitiveType}} +{{^isPrimitiveType}} + {{name}} = ({{{datatypeWithEnum}}})in.readValue({{complexType}}.class.getClassLoader()); +{{/isPrimitiveType}} +{{/vars}} +{{/isArrayModel}} + } + + public int describeContents() { + return 0; + } + + public static final Parcelable.Creator<{{classname}}> CREATOR = new Parcelable.Creator<{{classname}}>() { + public {{classname}} createFromParcel(Parcel in) { +{{#model}} +{{#isArrayModel}} + {{classname}} result = new {{classname}}(); + result.addAll(in.readArrayList({{arrayModelType}}.class.getClassLoader())); + return result; +{{/isArrayModel}} +{{^isArrayModel}} + return new {{classname}}(in); +{{/isArrayModel}} +{{/model}} + } + public {{classname}}[] newArray(int size) { + return new {{classname}}[size]; + } + }; +{{/parcelableModel}} +} diff --git a/modules/openapi-generator/src/main/resources/Java/libraries/jersey2-experimental/pom.mustache b/modules/openapi-generator/src/main/resources/Java/libraries/jersey2-experimental/pom.mustache new file mode 100644 index 000000000000..a71ab2638633 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/Java/libraries/jersey2-experimental/pom.mustache @@ -0,0 +1,383 @@ + + 4.0.0 + {{groupId}} + {{artifactId}} + jar + {{artifactId}} + {{artifactVersion}} + {{artifactUrl}} + {{artifactDescription}} + + {{scmConnection}} + {{scmDeveloperConnection}} + {{scmUrl}} + +{{#parentOverridden}} + + {{{parentGroupId}}} + {{{parentArtifactId}}} + {{{parentVersion}}} + +{{/parentOverridden}} + + + + {{licenseName}} + {{licenseUrl}} + repo + + + + + + {{developerName}} + {{developerEmail}} + {{developerOrganization}} + {{developerOrganizationUrl}} + + + + + + + org.apache.maven.plugins + maven-enforcer-plugin + 3.0.0-M1 + + + enforce-maven + + enforce + + + + + 2.2.0 + + + + + + + + org.apache.maven.plugins + maven-surefire-plugin + 3.0.0-M4 + + + + loggerPath + conf/log4j.properties + + + -Xms512m -Xmx1500m + methods + 10 + + + + maven-dependency-plugin + + + package + + copy-dependencies + + + ${project.build.directory}/lib + + + + + + + + org.apache.maven.plugins + maven-jar-plugin + 2.6 + + + + jar + test-jar + + + + + + + + + org.codehaus.mojo + build-helper-maven-plugin + 1.10 + + + add_sources + generate-sources + + add-source + + + + src/main/java + + + + + add_test_sources + generate-test-sources + + add-test-source + + + + src/test/java + + + + + + + org.apache.maven.plugins + maven-compiler-plugin + 3.8.1 + + {{#supportJava6}} + 1.6 + 1.6 + {{/supportJava6}} + {{^supportJava6}} + {{#java8}} + 1.8 + 1.8 + {{/java8}} + {{^java8}} + 1.7 + 1.7 + {{/java8}} + {{/supportJava6}} + true + 128m + 512m + + -Xlint:all + -J-Xss4m + + + + + org.apache.maven.plugins + maven-javadoc-plugin + 3.1.1 + + + attach-javadocs + + jar + + + + + none + + + http.response.details + a + Http Response Details: + + + + + + org.apache.maven.plugins + maven-source-plugin + 2.2.1 + + + attach-sources + + jar-no-fork + + + + + + + + + + sign-artifacts + + + + org.apache.maven.plugins + maven-gpg-plugin + 1.5 + + + sign-artifacts + verify + + sign + + + + + + + + + + + + io.swagger + swagger-annotations + ${swagger-annotations-version} + + + + + com.google.code.findbugs + jsr305 + 3.0.2 + + + + + org.glassfish.jersey.core + jersey-client + ${jersey-version} + + {{^supportJava6}} + + org.glassfish.jersey.inject + jersey-hk2 + ${jersey-version} + + {{/supportJava6}} + + org.glassfish.jersey.media + jersey-media-multipart + ${jersey-version} + + + org.glassfish.jersey.media + jersey-media-json-jackson + ${jersey-version} + + + + + com.fasterxml.jackson.core + jackson-core + ${jackson-version} + + + com.fasterxml.jackson.core + jackson-annotations + ${jackson-version} + + + com.fasterxml.jackson.core + jackson-databind + ${jackson-databind-version} + + + org.openapitools + jackson-databind-nullable + ${jackson-databind-nullable-version} + + {{#withXml}} + + + org.glassfish.jersey.media + jersey-media-jaxb + ${jersey-version} + + {{/withXml}} + {{#joda}} + + com.fasterxml.jackson.datatype + jackson-datatype-joda + ${jackson-version} + + {{/joda}} + {{#java8}} + + com.fasterxml.jackson.datatype + jackson-datatype-jsr310 + ${jackson-version} + + {{/java8}} + {{#threetenbp}} + + com.github.joschi.jackson + jackson-datatype-threetenbp + ${threetenbp-version} + + {{/threetenbp}} + {{^java8}} + + + com.brsanthu + migbase64 + 2.2 + + {{/java8}} + {{#supportJava6}} + + org.apache.commons + commons-lang3 + ${commons-lang3-version} + + + commons-io + commons-io + ${commons-io-version} + + {{/supportJava6}} + + org.tomitribe + tomitribe-http-signatures + ${http-signature-version} + + {{#useBeanValidation}} + + + javax.validation + validation-api + 1.1.0.Final + provided + + {{/useBeanValidation}} + + + junit + junit + ${junit-version} + test + + + + UTF-8 + 1.6.1 + {{^supportJava6}} + 2.30.1 + {{/supportJava6}} + {{#supportJava6}} + 2.6 + 2.5 + 3.6 + {{/supportJava6}} + 2.10.3 + 2.10.3 + 0.2.1 + {{#threetenbp}} + 2.9.10 + {{/threetenbp}} + 4.13 + 1.3 + + diff --git a/modules/openapi-generator/src/main/resources/Java/libraries/jersey2/pom.mustache b/modules/openapi-generator/src/main/resources/Java/libraries/jersey2/pom.mustache index 9bd8925f001b..d999ffaf0faf 100644 --- a/modules/openapi-generator/src/main/resources/Java/libraries/jersey2/pom.mustache +++ b/modules/openapi-generator/src/main/resources/Java/libraries/jersey2/pom.mustache @@ -352,7 +352,7 @@ UTF-8 - 1.5.22 + 1.6.1 {{^supportJava6}} 2.27 {{/supportJava6}} diff --git a/modules/openapi-generator/src/main/resources/Java/libraries/okhttp-gson/build.gradle.mustache b/modules/openapi-generator/src/main/resources/Java/libraries/okhttp-gson/build.gradle.mustache index 304b00a445a7..919132767757 100644 --- a/modules/openapi-generator/src/main/resources/Java/libraries/okhttp-gson/build.gradle.mustache +++ b/modules/openapi-generator/src/main/resources/Java/libraries/okhttp-gson/build.gradle.mustache @@ -68,7 +68,7 @@ if(hasProperty('target') && target == 'android') { } dependencies { - provided 'javax.annotation:jsr250-api:1.0' + provided 'javax.annotation:javax.annotation-api:1.3.2' } } @@ -126,21 +126,21 @@ if(hasProperty('target') && target == 'android') { } dependencies { - compile 'io.swagger:swagger-annotations:1.5.22' + compile 'io.swagger:swagger-annotations:1.5.24' compile "com.google.code.findbugs:jsr305:3.0.2" - compile 'com.squareup.okhttp3:okhttp:3.14.2' - compile 'com.squareup.okhttp3:logging-interceptor:3.14.2' - compile 'com.google.code.gson:gson:2.8.5' - compile 'io.gsonfire:gson-fire:1.8.3' + compile 'com.squareup.okhttp3:okhttp:3.14.7' + compile 'com.squareup.okhttp3:logging-interceptor:3.14.7' + compile 'com.google.code.gson:gson:2.8.6' + compile 'io.gsonfire:gson-fire:1.8.4' {{#hasOAuthMethods}} compile group: 'org.apache.oltu.oauth2', name: 'org.apache.oltu.oauth2.client', version: '1.0.1' {{/hasOAuthMethods}} - compile group: 'org.apache.commons', name: 'commons-lang3', version: '3.9' + compile group: 'org.apache.commons', name: 'commons-lang3', version: '3.10' {{#joda}} compile 'joda-time:joda-time:2.9.9' {{/joda}} {{#threetenbp}} - compile 'org.threeten:threetenbp:1.4.0' + compile 'org.threeten:threetenbp:1.4.3' {{/threetenbp}} testCompile 'junit:junit:4.13' } diff --git a/modules/openapi-generator/src/main/resources/Java/libraries/okhttp-gson/build.sbt.mustache b/modules/openapi-generator/src/main/resources/Java/libraries/okhttp-gson/build.sbt.mustache index 439074622027..7c137589e37f 100644 --- a/modules/openapi-generator/src/main/resources/Java/libraries/okhttp-gson/build.sbt.mustache +++ b/modules/openapi-generator/src/main/resources/Java/libraries/okhttp-gson/build.sbt.mustache @@ -9,11 +9,11 @@ lazy val root = (project in file(".")). publishArtifact in (Compile, packageDoc) := false, resolvers += Resolver.mavenLocal, libraryDependencies ++= Seq( - "io.swagger" % "swagger-annotations" % "1.5.22", - "com.squareup.okhttp3" % "okhttp" % "3.14.2", - "com.squareup.okhttp3" % "logging-interceptor" % "3.14.2", - "com.google.code.gson" % "gson" % "2.8.5", - "org.apache.commons" % "commons-lang3" % "3.9", + "io.swagger" % "swagger-annotations" % "1.5.24", + "com.squareup.okhttp3" % "okhttp" % "3.14.7", + "com.squareup.okhttp3" % "logging-interceptor" % "3.14.7", + "com.google.code.gson" % "gson" % "2.8.6", + "org.apache.commons" % "commons-lang3" % "3.10", {{#hasOAuthMethods}} "org.apache.oltu.oauth2" % "org.apache.oltu.oauth2.client" % "1.0.1", {{/hasOAuthMethods}} @@ -21,10 +21,11 @@ lazy val root = (project in file(".")). "joda-time" % "joda-time" % "2.9.9" % "compile", {{/joda}} {{#threetenbp}} - "org.threeten" % "threetenbp" % "1.4.0" % "compile", + "org.threeten" % "threetenbp" % "1.4.3" % "compile", {{/threetenbp}} "io.gsonfire" % "gson-fire" % "1.8.3" % "compile", - "javax.annotation" % "jsr250-api" % "1.0" % "compile", + "javax.annotation" % "javax.annotation-api" % "1.3.2" % "compile", + "com.google.code.findbugs" % "jsr305" % "3.0.2" % "compile", "junit" % "junit" % "4.13" % "test", "com.novocode" % "junit-interface" % "0.10" % "test" ) diff --git a/modules/openapi-generator/src/main/resources/Java/libraries/okhttp-gson/pom.mustache b/modules/openapi-generator/src/main/resources/Java/libraries/okhttp-gson/pom.mustache index c11b4ab127d7..b6d67f283507 100644 --- a/modules/openapi-generator/src/main/resources/Java/libraries/okhttp-gson/pom.mustache +++ b/modules/openapi-generator/src/main/resources/Java/libraries/okhttp-gson/pom.mustache @@ -40,6 +40,20 @@ + + org.apache.maven.plugins + maven-compiler-plugin + 3.8.1 + + true + 128m + 512m + + -Xlint:all + -J-Xss4m + + + org.apache.maven.plugins maven-enforcer-plugin @@ -293,7 +307,7 @@ {{/parcelableModel}} javax.annotation - jsr250-api + javax.annotation-api ${javax-annotation-version} @@ -308,19 +322,18 @@ {{#supportJava6}}1.6{{/supportJava6}}{{^supportJava6}}{{#java8}}1.8{{/java8}}{{^java8}}1.7{{/java8}}{{/supportJava6}} ${java.version} ${java.version} - 1.8.3 - 1.5.22 - 3.14.2 - 2.8.5 - 3.9 + 1.8.4 + 1.5.24 + 3.14.7 + 2.8.6 + 3.10 {{#joda}} 2.9.9 {{/joda}} {{#threetenbp}} - 1.4.0 + 1.4.3 {{/threetenbp}} - 1.0.0 - 1.0 + 1.3.2 4.13 UTF-8 diff --git a/modules/openapi-generator/src/main/resources/Java/libraries/rest-assured/build.gradle.mustache b/modules/openapi-generator/src/main/resources/Java/libraries/rest-assured/build.gradle.mustache index b04e53f1e966..0868a2aa7c0e 100644 --- a/modules/openapi-generator/src/main/resources/Java/libraries/rest-assured/build.gradle.mustache +++ b/modules/openapi-generator/src/main/resources/Java/libraries/rest-assured/build.gradle.mustache @@ -96,36 +96,51 @@ if(hasProperty('target') && target == 'android') { ext { swagger_annotations_version = "1.5.21" - rest_assured_version = "4.0.0" + rest_assured_version = "4.3.0" junit_version = "4.13" {{#jackson}} - jackson_version = "2.10.1" - jackson_databind_version = "2.9.10" - jackson_databind_nullable_version = 0.2.1 + jackson_version = "2.10.3" + jackson_databind_version = "2.10.3" + jackson_databind_nullable_version = "0.2.1" + {{#threetenbp}} + jackson_threetenbp_version = "2.10.0" + {{/threetenbp}} {{/jackson}} {{#gson}} - gson_version = "2.8.5" - gson_fire_version = "1.8.3" + gson_version = "2.8.6" + gson_fire_version = "1.8.4" {{/gson}} {{#joda}} - jodatime_version = "2.9.9" + jodatime_version = "2.10.5" {{/joda}} {{#threetenbp}} - threetenbp_version = "1.4.0" + threetenbp_version = "1.4.3" {{/threetenbp}} - okio_version = "1.13.0" + okio_version = "1.17.5" } dependencies { compile "io.swagger:swagger-annotations:$swagger_annotations_version" compile "com.google.code.findbugs:jsr305:3.0.2" - compile "io.rest-assured:scala-support:$rest_assured_version" + compile "io.rest-assured:rest-assured:$rest_assured_version" {{#jackson}} compile "com.fasterxml.jackson.core:jackson-core:$jackson_version" compile "com.fasterxml.jackson.core:jackson-annotations:$jackson_version" compile "com.fasterxml.jackson.core:jackson-databind:$jackson_databind_version" compile "com.fasterxml.jackson.jaxrs:jackson-jaxrs-json-provider:$jackson_version" compile "org.openapitools:jackson-databind-nullable:$jackson_databind_nullable_version" + {{#withXml}} + compile "com.fasterxml.jackson.dataformat:jackson-dataformat-xml:$jackson_version" + {{/withXml}} + {{#joda}} + compile "com.fasterxml.jackson.datatype:jackson-datatype-joda:$jackson_version" + {{/joda}} + {{#java8}} + compile "com.fasterxml.jackson.datatype:jackson-datatype-jsr310:$jackson_version" + {{/java8}} + {{#threetenbp}} + compile "com.github.joschi.jackson:jackson-datatype-threetenbp:$jackson_threetenbp_version" + {{/threetenbp}} {{/jackson}} {{#gson}} compile "io.gsonfire:gson-fire:$gson_fire_version" @@ -138,5 +153,11 @@ dependencies { compile "org.threeten:threetenbp:$threetenbp_version" {{/threetenbp}} compile "com.squareup.okio:okio:$okio_version" +{{#useBeanValidation}} + compile "javax.validation:validation-api:2.0.1.Final" +{{/useBeanValidation}} +{{#performBeanValidation}} + compile "org.hibernate:hibernate-validator:6.0.19.Final" +{{/performBeanValidation}} testCompile "junit:junit:$junit_version" } diff --git a/modules/openapi-generator/src/main/resources/Java/libraries/rest-assured/build.sbt.mustache b/modules/openapi-generator/src/main/resources/Java/libraries/rest-assured/build.sbt.mustache index 71f2eaeeba24..955f515fc70f 100644 --- a/modules/openapi-generator/src/main/resources/Java/libraries/rest-assured/build.sbt.mustache +++ b/modules/openapi-generator/src/main/resources/Java/libraries/rest-assured/build.sbt.mustache @@ -10,23 +10,44 @@ lazy val root = (project in file(".")). resolvers += Resolver.mavenLocal, libraryDependencies ++= Seq( "io.swagger" % "swagger-annotations" % "1.5.21", - "io.rest-assured" % "scala-support" % "4.0.0", + "io.rest-assured" % "rest-assured" % "4.3.0", + "io.rest-assured" % "scala-support" % "4.3.0", + "com.google.code.findbugs" % "jsr305" % "3.0.2", {{#jackson}} - "com.fasterxml.jackson.core" % "jackson-core" % "2.9.9" % "compile", - "com.fasterxml.jackson.core" % "jackson-annotations" % "2.9.9" % "compile", - "com.fasterxml.jackson.core" % "jackson-databind" % "2.9.9" % "compile", + "com.fasterxml.jackson.core" % "jackson-core" % "2.10.3", + "com.fasterxml.jackson.core" % "jackson-annotations" % "2.10.3", + "com.fasterxml.jackson.core" % "jackson-databind" % "2.10.3", + "org.openapitools" % "jackson-databind-nullable" % "0.2.1", + {{#withXml}} + "com.fasterxml.jackson.dataformat" % "jackson-dataformat-xml" % "2.10.3", + {{/withXml}} + {{#joda}} + "com.fasterxml.jackson.datatype" % "jackson-datatype-joda" % "2.10.3", + {{/joda}} + {{#java8}} + "com.fasterxml.jackson.datatype" % "jackson-datatype-jsr310" % "2.10.3", + {{/java8}} + {{#threetenbp}} + "com.github.joschi.jackson" % "jackson-datatype-threetenbp" % "2.10.0", + {{/threetenbp}} {{/jackson}} {{#gson}} - "com.google.code.gson" % "gson" % "2.8.5", - "io.gsonfire" % "gson-fire" % "1.8.3" % "compile", + "com.google.code.gson" % "gson" % "2.8.6", + "io.gsonfire" % "gson-fire" % "1.8.4" % "compile", {{/gson}} {{#joda}} - "joda-time" % "joda-time" % "2.9.9" % "compile", + "joda-time" % "joda-time" % "2.10.5" % "compile", {{/joda}} {{#threetenbp}} - "org.threeten" % "threetenbp" % "1.4.0" % "compile", + "org.threeten" % "threetenbp" % "1.4.3" % "compile", {{/threetenbp}} - "com.squareup.okio" % "okio" % "1.13.0" % "compile", + "com.squareup.okio" % "okio" % "1.17.5" % "compile", +{{#useBeanValidation}} + "javax.validation" % "validation-api" % "2.0.1.Final" % "compile", +{{/useBeanValidation}} +{{#performBeanValidation}} + "org.hibernate" % "hibernate-validator" % "6.0.19.Final" % "compile", +{{/performBeanValidation}} "junit" % "junit" % "4.13" % "test", "com.novocode" % "junit-interface" % "0.10" % "test" ) diff --git a/modules/openapi-generator/src/main/resources/Java/libraries/rest-assured/pom.mustache b/modules/openapi-generator/src/main/resources/Java/libraries/rest-assured/pom.mustache index da538caa9b06..2e68695d431a 100644 --- a/modules/openapi-generator/src/main/resources/Java/libraries/rest-assured/pom.mustache +++ b/modules/openapi-generator/src/main/resources/Java/libraries/rest-assured/pom.mustache @@ -43,7 +43,7 @@ org.apache.maven.plugins maven-enforcer-plugin - 3.0.0-M1 + 3.0.0-M3 enforce-maven @@ -53,7 +53,7 @@ - 2.2.0 + 3.0.5 @@ -63,7 +63,7 @@ org.apache.maven.plugins maven-surefire-plugin - 2.12 + 2.22.2 @@ -71,9 +71,8 @@ conf/log4j.properties - -Xms512m -Xmx1500m - methods - pertest + false + 1C @@ -111,6 +110,7 @@ org.codehaus.mojo build-helper-maven-plugin + 3.1.0 add_sources @@ -141,7 +141,7 @@ org.apache.maven.plugins maven-compiler-plugin - 3.6.1 + 3.8.1 1.8 1.8 @@ -150,7 +150,7 @@ org.apache.maven.plugins maven-javadoc-plugin - 3.1.1 + 3.2.0 none @@ -166,7 +166,7 @@ org.apache.maven.plugins maven-source-plugin - 2.2.1 + 3.2.0 attach-sources @@ -187,7 +187,7 @@ org.apache.maven.plugins maven-gpg-plugin - 1.5 + 1.6 sign-artifacts @@ -203,6 +203,20 @@ + {{#jackson}} + + + + com.fasterxml.jackson + jackson-bom + ${jackson-version} + pom + import + + + + {{/jackson}} + io.swagger @@ -215,6 +229,14 @@ jsr305 3.0.2 + {{^hideGenerationTimestamp}} + + javax.annotation + javax.annotation-api + 1.3.2 + provided + + {{/hideGenerationTimestamp}} io.rest-assured rest-assured @@ -253,17 +275,14 @@ com.fasterxml.jackson.core jackson-core - ${jackson-version} com.fasterxml.jackson.core jackson-annotations - ${jackson-version} com.fasterxml.jackson.core jackson-databind - ${jackson-databind-version} org.openapitools @@ -274,21 +293,18 @@ com.fasterxml.jackson.dataformat jackson-dataformat-xml - ${jackson-version} {{/withXml}} {{#joda}} com.fasterxml.jackson.datatype jackson-datatype-joda - ${jackson-version} {{/joda}} {{#java8}} com.fasterxml.jackson.datatype jackson-datatype-jsr310 - ${jackson-version} {{/java8}} {{#threetenbp}} @@ -304,6 +320,23 @@ okio ${okio-version} + {{#useBeanValidation}} + + + javax.validation + validation-api + 2.0.1.Final + provided + + {{/useBeanValidation}} + {{#performBeanValidation}} + + + org.hibernate + hibernate-validator + 6.0.19.Final + + {{/performBeanValidation}} junit @@ -315,25 +348,23 @@ UTF-8 1.5.21 - 4.0.0 - 2.8.5 - 1.8.3 - 1.0.0 + 4.3.0 + 2.8.6 + 1.8.4 {{#joda}} - 2.9.9 + 2.10.5 {{/joda}} {{#threetenbp}} - 1.4.0 + 1.4.3 {{/threetenbp}} {{#jackson}} - 2.10.1 - 2.9.10 + 2.10.3 0.2.1 {{#threetenbp}} - 2.9.10 + 2.10.0 {{/threetenbp}} {{/jackson}} - 1.13.0 + 1.17.5 4.13 diff --git a/modules/openapi-generator/src/main/resources/Java/libraries/resttemplate/ApiClient.mustache b/modules/openapi-generator/src/main/resources/Java/libraries/resttemplate/ApiClient.mustache index b160b7cca231..a2e66a62b616 100644 --- a/modules/openapi-generator/src/main/resources/Java/libraries/resttemplate/ApiClient.mustache +++ b/modules/openapi-generator/src/main/resources/Java/libraries/resttemplate/ApiClient.mustache @@ -716,7 +716,7 @@ public class ApiClient { * @param queryParams The query parameters * @param headerParams The header parameters */ - private void updateParamsForAuth(String[] authNames, MultiValueMap queryParams, HttpHeaders headerParams, MultiValueMap cookieParams) { + protected void updateParamsForAuth(String[] authNames, MultiValueMap queryParams, HttpHeaders headerParams, MultiValueMap cookieParams) { for (String authName : authNames) { Authentication auth = authentications.get(authName); if (auth == null) { diff --git a/modules/openapi-generator/src/main/resources/Java/openapi.mustache b/modules/openapi-generator/src/main/resources/Java/openapi.mustache new file mode 100644 index 000000000000..34fbb53f3317 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/Java/openapi.mustache @@ -0,0 +1 @@ +{{{openapi-yaml}}} diff --git a/modules/openapi-generator/src/main/resources/Java/pojo.mustache b/modules/openapi-generator/src/main/resources/Java/pojo.mustache index c438cd43eb72..653f44062d14 100644 --- a/modules/openapi-generator/src/main/resources/Java/pojo.mustache +++ b/modules/openapi-generator/src/main/resources/Java/pojo.mustache @@ -69,7 +69,7 @@ public class {{classname}} {{#parent}}extends {{{parent}}} {{/parent}}{{#vendorE private {{{datatypeWithEnum}}} {{name}}{{#required}}{{#defaultValue}} = {{{.}}}{{/defaultValue}}{{/required}}{{^required}} = null{{/required}}; {{/isContainer}} {{^isContainer}} - private {{{datatypeWithEnum}}} {{name}}{{#defaultValue}} = {{{.}}}{{/defaultValue}}; + {{#isDiscriminator}}protected{{/isDiscriminator}}{{^isDiscriminator}}private{{/isDiscriminator}} {{{datatypeWithEnum}}} {{name}}{{#defaultValue}} = {{{.}}}{{/defaultValue}}; {{/isContainer}} {{/vendorExtensions.x-is-jackson-optional-nullable}} diff --git a/modules/openapi-generator/src/main/resources/Java/pom.mustache b/modules/openapi-generator/src/main/resources/Java/pom.mustache index dd95ac7554ee..e9cbf546b6d7 100644 --- a/modules/openapi-generator/src/main/resources/Java/pom.mustache +++ b/modules/openapi-generator/src/main/resources/Java/pom.mustache @@ -40,6 +40,21 @@ + + org.apache.maven.plugins + maven-compiler-plugin + 3.8.1 + + true + 128m + 512m + + -Xlint:all + -J-Xss4m + + + + org.apache.maven.plugins maven-enforcer-plugin diff --git a/modules/openapi-generator/src/main/resources/JavaJaxRS/beanValidationCore.mustache b/modules/openapi-generator/src/main/resources/JavaJaxRS/beanValidationCore.mustache index d107c037b9a7..ae26b2739f1e 100644 --- a/modules/openapi-generator/src/main/resources/JavaJaxRS/beanValidationCore.mustache +++ b/modules/openapi-generator/src/main/resources/JavaJaxRS/beanValidationCore.mustache @@ -17,4 +17,4 @@ isInteger set isLong set }}{{#isLong}}{{#minimum}} @Min({{minimum}}L){{/minimum}}{{#maximum}} @Max({{maximum}}L){{/maximum}}{{/isLong}}{{! Not Integer, not Long => we have a decimal value! -}}{{^isInteger}}{{^isLong}}{{#minimum}} @DecimalMin({{#exclusiveMinimum}}value={{/exclusiveMinimum}}"{{minimum}}"{{#exclusiveMinimum}},inclusive=false{{/exclusiveMinimum}}){{/minimum}}{{#maximum}} @DecimalMax({{#exclusiveMinimum}}value={{/exclusiveMinimum}}"{{maximum}}"{{#exclusiveMinimum}},inclusive=false{{/exclusiveMinimum}}){{/maximum}}{{/isLong}}{{/isInteger}} \ No newline at end of file +}}{{^isInteger}}{{^isLong}}{{#minimum}} @DecimalMin({{#exclusiveMinimum}}value={{/exclusiveMinimum}}"{{minimum}}"{{#exclusiveMinimum}},inclusive=false{{/exclusiveMinimum}}){{/minimum}}{{#maximum}} @DecimalMax({{#exclusiveMaximum}}value={{/exclusiveMaximum}}"{{maximum}}"{{#exclusiveMaximum}},inclusive=false{{/exclusiveMaximum}}){{/maximum}}{{/isLong}}{{/isInteger}} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/JavaJaxRS/cxf-cdi/beanValidationCore.mustache b/modules/openapi-generator/src/main/resources/JavaJaxRS/cxf-cdi/beanValidationCore.mustache index d107c037b9a7..ae26b2739f1e 100644 --- a/modules/openapi-generator/src/main/resources/JavaJaxRS/cxf-cdi/beanValidationCore.mustache +++ b/modules/openapi-generator/src/main/resources/JavaJaxRS/cxf-cdi/beanValidationCore.mustache @@ -17,4 +17,4 @@ isInteger set isLong set }}{{#isLong}}{{#minimum}} @Min({{minimum}}L){{/minimum}}{{#maximum}} @Max({{maximum}}L){{/maximum}}{{/isLong}}{{! Not Integer, not Long => we have a decimal value! -}}{{^isInteger}}{{^isLong}}{{#minimum}} @DecimalMin({{#exclusiveMinimum}}value={{/exclusiveMinimum}}"{{minimum}}"{{#exclusiveMinimum}},inclusive=false{{/exclusiveMinimum}}){{/minimum}}{{#maximum}} @DecimalMax({{#exclusiveMinimum}}value={{/exclusiveMinimum}}"{{maximum}}"{{#exclusiveMinimum}},inclusive=false{{/exclusiveMinimum}}){{/maximum}}{{/isLong}}{{/isInteger}} \ No newline at end of file +}}{{^isInteger}}{{^isLong}}{{#minimum}} @DecimalMin({{#exclusiveMinimum}}value={{/exclusiveMinimum}}"{{minimum}}"{{#exclusiveMinimum}},inclusive=false{{/exclusiveMinimum}}){{/minimum}}{{#maximum}} @DecimalMax({{#exclusiveMaximum}}value={{/exclusiveMaximum}}"{{maximum}}"{{#exclusiveMaximum}},inclusive=false{{/exclusiveMaximum}}){{/maximum}}{{/isLong}}{{/isInteger}} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/JavaJaxRS/cxf-cdi/pojo.mustache b/modules/openapi-generator/src/main/resources/JavaJaxRS/cxf-cdi/pojo.mustache index 15a4bffef0e0..5e6eff4dafa0 100644 --- a/modules/openapi-generator/src/main/resources/JavaJaxRS/cxf-cdi/pojo.mustache +++ b/modules/openapi-generator/src/main/resources/JavaJaxRS/cxf-cdi/pojo.mustache @@ -81,13 +81,14 @@ public class {{classname}} {{#parent}}extends {{{parent}}}{{/parent}} {{#seriali } {{classname}} {{classVarName}} = ({{classname}}) o;{{#hasVars}} return {{#vars}}Objects.equals({{name}}, {{classVarName}}.{{name}}){{#hasMore}} && - {{/hasMore}}{{^hasMore}};{{/hasMore}}{{/vars}}{{/hasVars}}{{^hasVars}} + {{/hasMore}}{{/vars}}{{#parent}} && + super.equals(o){{/parent}};{{/hasVars}}{{^hasVars}} return true;{{/hasVars}} } @Override public int hashCode() { - return Objects.hash({{#vars}}{{name}}{{#hasMore}}, {{/hasMore}}{{/vars}}); + return Objects.hash({{#vars}}{{name}}{{#hasMore}}, {{/hasMore}}{{/vars}}{{#parent}}{{#hasVars}}, {{/hasVars}}super.hashCode(){{/parent}}); } @Override diff --git a/modules/openapi-generator/src/main/resources/JavaJaxRS/cxf-cdi/pom.mustache b/modules/openapi-generator/src/main/resources/JavaJaxRS/cxf-cdi/pom.mustache index 2e4a1649272b..d553a7b1278e 100644 --- a/modules/openapi-generator/src/main/resources/JavaJaxRS/cxf-cdi/pom.mustache +++ b/modules/openapi-generator/src/main/resources/JavaJaxRS/cxf-cdi/pom.mustache @@ -58,8 +58,8 @@ org.apache.cxf cxf-rt-frontend-jaxrs - - 3.0.2 + + 3.1.2 provided diff --git a/modules/openapi-generator/src/main/resources/JavaJaxRS/cxf/beanValidationCore.mustache b/modules/openapi-generator/src/main/resources/JavaJaxRS/cxf/beanValidationCore.mustache index d107c037b9a7..ae26b2739f1e 100644 --- a/modules/openapi-generator/src/main/resources/JavaJaxRS/cxf/beanValidationCore.mustache +++ b/modules/openapi-generator/src/main/resources/JavaJaxRS/cxf/beanValidationCore.mustache @@ -17,4 +17,4 @@ isInteger set isLong set }}{{#isLong}}{{#minimum}} @Min({{minimum}}L){{/minimum}}{{#maximum}} @Max({{maximum}}L){{/maximum}}{{/isLong}}{{! Not Integer, not Long => we have a decimal value! -}}{{^isInteger}}{{^isLong}}{{#minimum}} @DecimalMin({{#exclusiveMinimum}}value={{/exclusiveMinimum}}"{{minimum}}"{{#exclusiveMinimum}},inclusive=false{{/exclusiveMinimum}}){{/minimum}}{{#maximum}} @DecimalMax({{#exclusiveMinimum}}value={{/exclusiveMinimum}}"{{maximum}}"{{#exclusiveMinimum}},inclusive=false{{/exclusiveMinimum}}){{/maximum}}{{/isLong}}{{/isInteger}} \ No newline at end of file +}}{{^isInteger}}{{^isLong}}{{#minimum}} @DecimalMin({{#exclusiveMinimum}}value={{/exclusiveMinimum}}"{{minimum}}"{{#exclusiveMinimum}},inclusive=false{{/exclusiveMinimum}}){{/minimum}}{{#maximum}} @DecimalMax({{#exclusiveMaximum}}value={{/exclusiveMaximum}}"{{maximum}}"{{#exclusiveMaximum}},inclusive=false{{/exclusiveMaximum}}){{/maximum}}{{/isLong}}{{/isInteger}} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/JavaJaxRS/resteasy/beanValidationCore.mustache b/modules/openapi-generator/src/main/resources/JavaJaxRS/resteasy/beanValidationCore.mustache index d107c037b9a7..ae26b2739f1e 100644 --- a/modules/openapi-generator/src/main/resources/JavaJaxRS/resteasy/beanValidationCore.mustache +++ b/modules/openapi-generator/src/main/resources/JavaJaxRS/resteasy/beanValidationCore.mustache @@ -17,4 +17,4 @@ isInteger set isLong set }}{{#isLong}}{{#minimum}} @Min({{minimum}}L){{/minimum}}{{#maximum}} @Max({{maximum}}L){{/maximum}}{{/isLong}}{{! Not Integer, not Long => we have a decimal value! -}}{{^isInteger}}{{^isLong}}{{#minimum}} @DecimalMin({{#exclusiveMinimum}}value={{/exclusiveMinimum}}"{{minimum}}"{{#exclusiveMinimum}},inclusive=false{{/exclusiveMinimum}}){{/minimum}}{{#maximum}} @DecimalMax({{#exclusiveMinimum}}value={{/exclusiveMinimum}}"{{maximum}}"{{#exclusiveMinimum}},inclusive=false{{/exclusiveMinimum}}){{/maximum}}{{/isLong}}{{/isInteger}} \ No newline at end of file +}}{{^isInteger}}{{^isLong}}{{#minimum}} @DecimalMin({{#exclusiveMinimum}}value={{/exclusiveMinimum}}"{{minimum}}"{{#exclusiveMinimum}},inclusive=false{{/exclusiveMinimum}}){{/minimum}}{{#maximum}} @DecimalMax({{#exclusiveMaximum}}value={{/exclusiveMaximum}}"{{maximum}}"{{#exclusiveMaximum}},inclusive=false{{/exclusiveMaximum}}){{/maximum}}{{/isLong}}{{/isInteger}} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/JavaJaxRS/resteasy/eap/beanValidationCore.mustache b/modules/openapi-generator/src/main/resources/JavaJaxRS/resteasy/eap/beanValidationCore.mustache index d107c037b9a7..ae26b2739f1e 100644 --- a/modules/openapi-generator/src/main/resources/JavaJaxRS/resteasy/eap/beanValidationCore.mustache +++ b/modules/openapi-generator/src/main/resources/JavaJaxRS/resteasy/eap/beanValidationCore.mustache @@ -17,4 +17,4 @@ isInteger set isLong set }}{{#isLong}}{{#minimum}} @Min({{minimum}}L){{/minimum}}{{#maximum}} @Max({{maximum}}L){{/maximum}}{{/isLong}}{{! Not Integer, not Long => we have a decimal value! -}}{{^isInteger}}{{^isLong}}{{#minimum}} @DecimalMin({{#exclusiveMinimum}}value={{/exclusiveMinimum}}"{{minimum}}"{{#exclusiveMinimum}},inclusive=false{{/exclusiveMinimum}}){{/minimum}}{{#maximum}} @DecimalMax({{#exclusiveMinimum}}value={{/exclusiveMinimum}}"{{maximum}}"{{#exclusiveMinimum}},inclusive=false{{/exclusiveMinimum}}){{/maximum}}{{/isLong}}{{/isInteger}} \ No newline at end of file +}}{{^isInteger}}{{^isLong}}{{#minimum}} @DecimalMin({{#exclusiveMinimum}}value={{/exclusiveMinimum}}"{{minimum}}"{{#exclusiveMinimum}},inclusive=false{{/exclusiveMinimum}}){{/minimum}}{{#maximum}} @DecimalMax({{#exclusiveMaximum}}value={{/exclusiveMaximum}}"{{maximum}}"{{#exclusiveMaximum}},inclusive=false{{/exclusiveMaximum}}){{/maximum}}{{/isLong}}{{/isInteger}} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/JavaJaxRS/spec/beanValidationCore.mustache b/modules/openapi-generator/src/main/resources/JavaJaxRS/spec/beanValidationCore.mustache index d107c037b9a7..ae26b2739f1e 100644 --- a/modules/openapi-generator/src/main/resources/JavaJaxRS/spec/beanValidationCore.mustache +++ b/modules/openapi-generator/src/main/resources/JavaJaxRS/spec/beanValidationCore.mustache @@ -17,4 +17,4 @@ isInteger set isLong set }}{{#isLong}}{{#minimum}} @Min({{minimum}}L){{/minimum}}{{#maximum}} @Max({{maximum}}L){{/maximum}}{{/isLong}}{{! Not Integer, not Long => we have a decimal value! -}}{{^isInteger}}{{^isLong}}{{#minimum}} @DecimalMin({{#exclusiveMinimum}}value={{/exclusiveMinimum}}"{{minimum}}"{{#exclusiveMinimum}},inclusive=false{{/exclusiveMinimum}}){{/minimum}}{{#maximum}} @DecimalMax({{#exclusiveMinimum}}value={{/exclusiveMinimum}}"{{maximum}}"{{#exclusiveMinimum}},inclusive=false{{/exclusiveMinimum}}){{/maximum}}{{/isLong}}{{/isInteger}} \ No newline at end of file +}}{{^isInteger}}{{^isLong}}{{#minimum}} @DecimalMin({{#exclusiveMinimum}}value={{/exclusiveMinimum}}"{{minimum}}"{{#exclusiveMinimum}},inclusive=false{{/exclusiveMinimum}}){{/minimum}}{{#maximum}} @DecimalMax({{#exclusiveMaximum}}value={{/exclusiveMaximum}}"{{maximum}}"{{#exclusiveMaximum}},inclusive=false{{/exclusiveMaximum}}){{/maximum}}{{/isLong}}{{/isInteger}} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/JavaJaxRS/spec/pojo.mustache b/modules/openapi-generator/src/main/resources/JavaJaxRS/spec/pojo.mustache index 487a6fbb0ba4..1c48e051d7d2 100644 --- a/modules/openapi-generator/src/main/resources/JavaJaxRS/spec/pojo.mustache +++ b/modules/openapi-generator/src/main/resources/JavaJaxRS/spec/pojo.mustache @@ -6,21 +6,19 @@ import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonValue; -{{#discriminator}}{{>typeInfoAnnotation}}{{/discriminator}}{{#description}} -/** +{{#discriminator}}{{>typeInfoAnnotation}}{{/discriminator}}{{#description}}/** * {{description}} - **/{{/description}}{{#useSwaggerAnnotations}} -{{#description}}{{>additionalModelTypeAnnotations}}@ApiModel(description = "{{{description}}}"){{/description}}{{/useSwaggerAnnotations}} + **/{{/description}} +{{#useSwaggerAnnotations}}{{#description}}{{>additionalModelTypeAnnotations}}@ApiModel(description = "{{{description}}}"){{/description}}{{/useSwaggerAnnotations}} {{>generatedAnnotation}}public class {{classname}} {{#parent}}extends {{{parent}}}{{/parent}} {{#serializableModel}}implements Serializable{{/serializableModel}} { {{#vars}}{{#isEnum}}{{^isContainer}} {{>enumClass}}{{/isContainer}}{{#isContainer}}{{#mostInnerItems}} {{>enumClass}}{{/mostInnerItems}}{{/isContainer}}{{/isEnum}} - private {{#useBeanValidation}}@Valid{{/useBeanValidation}} {{{datatypeWithEnum}}} {{name}}{{#defaultValue}} = {{{.}}}{{/defaultValue}};{{/vars}} + private {{#useBeanValidation}}@Valid {{/useBeanValidation}}{{{datatypeWithEnum}}} {{name}}{{#defaultValue}} = {{{.}}}{{/defaultValue}};{{/vars}} - {{#vars}} - /** + {{#vars}}/** {{#description}} * {{description}} {{/description}} @@ -36,17 +34,22 @@ import com.fasterxml.jackson.annotation.JsonValue; return this; } + {{#generateBuilders}}public {{classname}}({{#vars}}{{{datatypeWithEnum}}} {{name}}{{#hasMore}}, {{/hasMore}}{{/vars}}) { + {{#vars}} + this.{{name}} = {{name}}; + {{/vars}} + }{{/generateBuilders}} + {{#vendorExtensions.x-extra-annotation}}{{{vendorExtensions.x-extra-annotation}}}{{/vendorExtensions.x-extra-annotation}}{{#useSwaggerAnnotations}} @ApiModelProperty({{#example}}example = "{{{example}}}", {{/example}}{{#required}}required = {{required}}, {{/required}}value = "{{{description}}}"){{/useSwaggerAnnotations}} @JsonProperty("{{baseName}}") {{#useBeanValidation}}{{>beanValidation}}{{/useBeanValidation}} public {{{datatypeWithEnum}}} {{getter}}() { return {{name}}; } + public void {{setter}}({{{datatypeWithEnum}}} {{name}}) { this.{{name}} = {{name}}; - } - - {{/vars}} + }{{/vars}} @Override public boolean equals(java.lang.Object o) { @@ -88,4 +91,37 @@ import com.fasterxml.jackson.annotation.JsonValue; } return o.toString().replace("\n", "\n "); } + + {{#generateBuilders}} + public static Builder builder() { + return new Builder(); + } + + public static class Builder { + {{#vars}} + private {{{datatypeWithEnum}}} {{name}}{{#defaultValue}} = {{{.}}}{{/defaultValue}}; + {{/vars}} + + {{#vars}} + /** + {{#description}} + * {{description}} + {{/description}} + {{#minimum}} + * minimum: {{minimum}} + {{/minimum}} + {{#maximum}} + * maximum: {{maximum}} + {{/maximum}} + **/ + public Builder {{name}}({{{datatypeWithEnum}}} {{name}}) { + this.{{name}} = {{name}}; + return this; + } + {{/vars}} + + public {{classname}} build() { + return new {{classname}}({{#vars}}{{name}}{{#hasMore}}, {{/hasMore}}{{/vars}}); + } + }{{/generateBuilders}} } diff --git a/modules/openapi-generator/src/main/resources/JavaSpring/beanValidationCore.mustache b/modules/openapi-generator/src/main/resources/JavaSpring/beanValidationCore.mustache index 4694c0980f27..55b4494bf83f 100644 --- a/modules/openapi-generator/src/main/resources/JavaSpring/beanValidationCore.mustache +++ b/modules/openapi-generator/src/main/resources/JavaSpring/beanValidationCore.mustache @@ -21,4 +21,4 @@ isInteger set isLong set }}{{#isLong}}{{#minimum}}@Min({{minimum}}L){{/minimum}}{{#maximum}} @Max({{maximum}}L) {{/maximum}}{{/isLong}}{{! Not Integer, not Long => we have a decimal value! -}}{{^isInteger}}{{^isLong}}{{#minimum}}@DecimalMin({{#exclusiveMinimum}}value={{/exclusiveMinimum}}"{{minimum}}"{{#exclusiveMinimum}},inclusive=false{{/exclusiveMinimum}}){{/minimum}}{{#maximum}} @DecimalMax({{#exclusiveMinimum}}value={{/exclusiveMinimum}}"{{maximum}}"{{#exclusiveMinimum}},inclusive=false{{/exclusiveMinimum}}) {{/maximum}}{{/isLong}}{{/isInteger}} \ No newline at end of file +}}{{^isInteger}}{{^isLong}}{{#minimum}}@DecimalMin({{#exclusiveMinimum}}value={{/exclusiveMinimum}}"{{minimum}}"{{#exclusiveMinimum}},inclusive=false{{/exclusiveMinimum}}){{/minimum}}{{#maximum}} @DecimalMax({{#exclusiveMaximum}}value={{/exclusiveMaximum}}"{{maximum}}"{{#exclusiveMaximum}},inclusive=false{{/exclusiveMaximum}}) {{/maximum}}{{/isLong}}{{/isInteger}} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/JavaSpring/pojo.mustache b/modules/openapi-generator/src/main/resources/JavaSpring/pojo.mustache index 695e865a71ae..0601e70f6902 100644 --- a/modules/openapi-generator/src/main/resources/JavaSpring/pojo.mustache +++ b/modules/openapi-generator/src/main/resources/JavaSpring/pojo.mustache @@ -31,6 +31,12 @@ public class {{classname}} {{#parent}}extends {{{parent}}}{{/parent}}{{^parent}} private {{>nullableDataType}} {{name}} = {{#isNullable}}JsonNullable.undefined(){{/isNullable}}{{^isNullable}}{{#required}}{{{defaultValue}}}{{/required}}{{^required}}null{{/required}}{{/isNullable}}; {{/isContainer}} {{^isContainer}} + {{#isDate}} + @org.springframework.format.annotation.DateTimeFormat(iso = org.springframework.format.annotation.DateTimeFormat.ISO.DATE) + {{/isDate}} + {{#isDateTime}} + @org.springframework.format.annotation.DateTimeFormat(iso = org.springframework.format.annotation.DateTimeFormat.ISO.DATE_TIME) + {{/isDateTime}} private {{>nullableDataType}} {{name}}{{#isNullable}} = JsonNullable.undefined(){{/isNullable}}{{^isNullable}}{{#defaultValue}} = {{{.}}}{{/defaultValue}}{{/isNullable}}; {{/isContainer}} diff --git a/modules/openapi-generator/src/main/resources/META-INF/services/org.openapitools.codegen.CodegenConfig b/modules/openapi-generator/src/main/resources/META-INF/services/org.openapitools.codegen.CodegenConfig index a940b17f5635..c0b1391cf505 100644 --- a/modules/openapi-generator/src/main/resources/META-INF/services/org.openapitools.codegen.CodegenConfig +++ b/modules/openapi-generator/src/main/resources/META-INF/services/org.openapitools.codegen.CodegenConfig @@ -130,4 +130,6 @@ org.openapitools.codegen.languages.FsharpFunctionsServerCodegen org.openapitools.codegen.languages.MarkdownDocumentationCodegen org.openapitools.codegen.languages.ScalaSttpClientCodegen +org.openapitools.codegen.languages.ScalaAkkaHttpServerCodegen + org.openapitools.codegen.languages.StubiBackendApiClientClientCodegen diff --git a/modules/openapi-generator/src/main/resources/cpp-qt5-client/HttpRequest.cpp.mustache b/modules/openapi-generator/src/main/resources/cpp-qt5-client/HttpRequest.cpp.mustache index 64e8ab094ff8..6ec3d67bcae3 100644 --- a/modules/openapi-generator/src/main/resources/cpp-qt5-client/HttpRequest.cpp.mustache +++ b/modules/openapi-generator/src/main/resources/cpp-qt5-client/HttpRequest.cpp.mustache @@ -45,7 +45,7 @@ void {{prefix}}HttpRequestInput::add_file(QString variable_name, QString local_f } {{prefix}}HttpRequestWorker::{{prefix}}HttpRequestWorker(QObject *parent) - : QObject(parent), manager(nullptr), timeOutTimer(this) { + : QObject(parent), manager(nullptr), timeOutTimer(this), isResponseCompressionEnabled(false), isRequestCompressionEnabled(false), httpResponseCode(-1) { qsrand(QDateTime::currentDateTime().toTime_t()); manager = new QNetworkAccessManager(this); workingDirectory = QDir::currentPath(); @@ -110,6 +110,10 @@ void {{prefix}}HttpRequestWorker::setRequestCompressionEnabled(bool enable) { isRequestCompressionEnabled = enable; } +int {{prefix}}HttpRequestWorker::getHttpResponseCode() const{ + return httpResponseCode; +} + QString {{prefix}}HttpRequestWorker::http_attribute_encode(QString attribute_name, QString input) { // result structure follows RFC 5987 bool need_utf_encoding = false; @@ -360,6 +364,7 @@ void {{prefix}}HttpRequestWorker::execute({{prefix}}HttpRequestInput *input) { } void {{prefix}}HttpRequestWorker::on_manager_finished(QNetworkReply *reply) { + bool codeSts = false; if(timeOutTimer.isActive()) { QObject::disconnect(&timeOutTimer, &QTimer::timeout, nullptr, nullptr); timeOutTimer.stop(); @@ -371,6 +376,12 @@ void {{prefix}}HttpRequestWorker::on_manager_finished(QNetworkReply *reply) { headers.insert(item.first, item.second); } } + auto rescode = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt(&codeSts); + if(codeSts){ + httpResponseCode = rescode; + } else{ + httpResponseCode = -1; + } process_response(reply); reply->deleteLater(); emit on_execution_finished(this); diff --git a/modules/openapi-generator/src/main/resources/cpp-qt5-client/HttpRequest.h.mustache b/modules/openapi-generator/src/main/resources/cpp-qt5-client/HttpRequest.h.mustache index 247f5906841a..efd352568855 100644 --- a/modules/openapi-generator/src/main/resources/cpp-qt5-client/HttpRequest.h.mustache +++ b/modules/openapi-generator/src/main/resources/cpp-qt5-client/HttpRequest.h.mustache @@ -50,11 +50,12 @@ class {{prefix}}HttpRequestWorker : public QObject { Q_OBJECT public: + explicit {{prefix}}HttpRequestWorker(QObject *parent = nullptr); + virtual ~{{prefix}}HttpRequestWorker(); + QByteArray response; QNetworkReply::NetworkError error_type; QString error_str; - explicit {{prefix}}HttpRequestWorker(QObject *parent = nullptr); - virtual ~{{prefix}}HttpRequestWorker(); QMap getResponseHeaders() const; QString http_attribute_encode(QString attribute_name, QString input); @@ -66,6 +67,8 @@ public: QByteArray *getMultiPartField(const QString &fieldname = QString()); void setResponseCompressionEnabled(bool enable); void setRequestCompressionEnabled(bool enable); + int getHttpResponseCode() const; + signals: void on_execution_finished({{prefix}}HttpRequestWorker *worker); @@ -82,10 +85,13 @@ private: QTimer timeOutTimer; bool isResponseCompressionEnabled; bool isRequestCompressionEnabled; + int httpResponseCode; + void on_manager_timeout(QNetworkReply *reply); void process_response(QNetworkReply *reply); QByteArray decompress(const QByteArray& data); - QByteArray compress(const QByteArray& input, int level, {{prefix}}CompressionType compressType); + QByteArray compress(const QByteArray& input, int level, {{prefix}}CompressionType compressType); + private slots: void on_manager_finished(QNetworkReply *reply); }; diff --git a/modules/openapi-generator/src/main/resources/cpp-qt5-client/helpers-body.mustache b/modules/openapi-generator/src/main/resources/cpp-qt5-client/helpers-body.mustache index 4dd03102bad6..a4c04a8951c0 100644 --- a/modules/openapi-generator/src/main/resources/cpp-qt5-client/helpers-body.mustache +++ b/modules/openapi-generator/src/main/resources/cpp-qt5-client/helpers-body.mustache @@ -7,13 +7,49 @@ namespace {{this}} { {{/cppNamespaceDeclarations}} +class {{prefix}}SerializerSettings { +public: + static void setDateTimeFormat(const QString & dtFormat){ + getInstance()->dateTimeFormat = dtFormat; + } + static QString getDateTimeFormat() { + return getInstance()->dateTimeFormat; + } + static {{prefix}}SerializerSettings *getInstance(){ + if(instance == nullptr){ + instance = new {{prefix}}SerializerSettings(); + } + return instance; + } +private: + explicit {{prefix}}SerializerSettings(){ + instance = this; + dateTimeFormat.clear(); + } + static {{prefix}}SerializerSettings *instance; + QString dateTimeFormat; +}; + +{{prefix}}SerializerSettings * {{prefix}}SerializerSettings::instance = nullptr; + +bool setDateTimeFormat(const QString& dateTimeFormat){ + bool success = false; + auto dt = QDateTime::fromString(QDateTime::currentDateTime().toString(dateTimeFormat), dateTimeFormat); + if(dt.isValid()){ + success = true; + {{prefix}}SerializerSettings::setDateTimeFormat(dateTimeFormat); + } + return success; +} + + QString toStringValue(const QString &value) { return value; } QString toStringValue(const QDateTime &value) { // ISO 8601 - return value.toString("yyyy-MM-ddTHH:mm:ss[Z|[+|-]HH:mm]"); + return {{prefix}}SerializerSettings::getInstance()->getDateTimeFormat().isEmpty()? value.toString(Qt::ISODate):value.toString({{prefix}}SerializerSettings::getInstance()->getDateTimeFormat()); } QString toStringValue(const QByteArray &value) { @@ -62,7 +98,7 @@ QJsonValue toJsonValue(const QString &value) { } QJsonValue toJsonValue(const QDateTime &value) { - return QJsonValue(value.toString(Qt::ISODate)); + return QJsonValue(value.toString({{prefix}}SerializerSettings::getInstance()->getDateTimeFormat().isEmpty()?value.toString(Qt::ISODate):value.toString({{prefix}}SerializerSettings::getInstance()->getDateTimeFormat()))); } QJsonValue toJsonValue(const QByteArray &value) { @@ -115,7 +151,7 @@ bool fromStringValue(const QString &inStr, QDateTime &value) { if (inStr.isEmpty()) { return false; } else { - auto dateTime = QDateTime::fromString(inStr, "yyyy-MM-ddTHH:mm:ss[Z|[+|-]HH:mm]"); + auto dateTime = {{prefix}}SerializerSettings::getInstance()->getDateTimeFormat().isEmpty()?QDateTime::fromString(inStr, Qt::ISODate) :QDateTime::fromString(inStr, {{prefix}}SerializerSettings::getInstance()->getDateTimeFormat()); if (dateTime.isValid()) { value.setDate(dateTime.date()); value.setTime(dateTime.time()); @@ -220,7 +256,7 @@ bool fromJsonValue(QString &value, const QJsonValue &jval) { bool fromJsonValue(QDateTime &value, const QJsonValue &jval) { bool ok = true; if (!jval.isUndefined() && !jval.isNull() && jval.isString()) { - value = QDateTime::fromString(jval.toString(), Qt::ISODate); + value = {{prefix}}SerializerSettings::getInstance()->getDateTimeFormat().isEmpty()?QDateTime::fromString(jval.toString(), Qt::ISODate): QDateTime::fromString(jval.toString(), {{prefix}}SerializerSettings::getInstance()->getDateTimeFormat()); ok = value.isValid(); } else { ok = false; diff --git a/modules/openapi-generator/src/main/resources/cpp-qt5-client/helpers-header.mustache b/modules/openapi-generator/src/main/resources/cpp-qt5-client/helpers-header.mustache index a53e0a30edd9..0a8e6b8b2145 100644 --- a/modules/openapi-generator/src/main/resources/cpp-qt5-client/helpers-header.mustache +++ b/modules/openapi-generator/src/main/resources/cpp-qt5-client/helpers-header.mustache @@ -20,6 +20,8 @@ namespace {{this}} { {{/cppNamespaceDeclarations}} +bool setDateTimeFormat(const QString&); + template QString toStringValue(const QList &val); diff --git a/modules/openapi-generator/src/main/resources/cpp-qt5-client/model-body.mustache b/modules/openapi-generator/src/main/resources/cpp-qt5-client/model-body.mustache index 05f22ceb8fb9..e48e1597db1f 100644 --- a/modules/openapi-generator/src/main/resources/cpp-qt5-client/model-body.mustache +++ b/modules/openapi-generator/src/main/resources/cpp-qt5-client/model-body.mustache @@ -120,6 +120,14 @@ void {{classname}}::{{setter}}(const {{{dataType}}} &{{name}}) { this->m_{{name}}_isSet = true; } +bool {{classname}}::is_{{name}}_Set() const{ + return m_{{name}}_isSet; +} + +bool {{classname}}::is_{{name}}_Valid() const{ + return m_{{name}}_isValid; +} + {{/vars}}{{/isEnum}}{{#isEnum}} {{classname}}::e{{classname}} {{classname}}::getValue() const { return m_value; diff --git a/modules/openapi-generator/src/main/resources/cpp-qt5-client/model-header.mustache b/modules/openapi-generator/src/main/resources/cpp-qt5-client/model-header.mustache index 8f194ac12f9c..5bbe8c8c20e1 100644 --- a/modules/openapi-generator/src/main/resources/cpp-qt5-client/model-header.mustache +++ b/modules/openapi-generator/src/main/resources/cpp-qt5-client/model-header.mustache @@ -35,6 +35,8 @@ public: {{^isEnum}}{{#vars}} {{{dataType}}} {{getter}}() const; void {{setter}}(const {{{dataType}}} &{{name}}); + bool is_{{name}}_Set() const; + bool is_{{name}}_Valid() const; {{/vars}}{{/isEnum}}{{#isEnum}} {{#allowableValues}} enum class e{{classname}} {{#enumVars}}{{#-first}}{{^isString}}: int {{/isString}}{{/-first}}{{/enumVars}}{ diff --git a/modules/openapi-generator/src/main/resources/cpp-qt5-qhttpengine-server/helpers-body.mustache b/modules/openapi-generator/src/main/resources/cpp-qt5-qhttpengine-server/helpers-body.mustache index 4dd03102bad6..a4c04a8951c0 100644 --- a/modules/openapi-generator/src/main/resources/cpp-qt5-qhttpengine-server/helpers-body.mustache +++ b/modules/openapi-generator/src/main/resources/cpp-qt5-qhttpengine-server/helpers-body.mustache @@ -7,13 +7,49 @@ namespace {{this}} { {{/cppNamespaceDeclarations}} +class {{prefix}}SerializerSettings { +public: + static void setDateTimeFormat(const QString & dtFormat){ + getInstance()->dateTimeFormat = dtFormat; + } + static QString getDateTimeFormat() { + return getInstance()->dateTimeFormat; + } + static {{prefix}}SerializerSettings *getInstance(){ + if(instance == nullptr){ + instance = new {{prefix}}SerializerSettings(); + } + return instance; + } +private: + explicit {{prefix}}SerializerSettings(){ + instance = this; + dateTimeFormat.clear(); + } + static {{prefix}}SerializerSettings *instance; + QString dateTimeFormat; +}; + +{{prefix}}SerializerSettings * {{prefix}}SerializerSettings::instance = nullptr; + +bool setDateTimeFormat(const QString& dateTimeFormat){ + bool success = false; + auto dt = QDateTime::fromString(QDateTime::currentDateTime().toString(dateTimeFormat), dateTimeFormat); + if(dt.isValid()){ + success = true; + {{prefix}}SerializerSettings::setDateTimeFormat(dateTimeFormat); + } + return success; +} + + QString toStringValue(const QString &value) { return value; } QString toStringValue(const QDateTime &value) { // ISO 8601 - return value.toString("yyyy-MM-ddTHH:mm:ss[Z|[+|-]HH:mm]"); + return {{prefix}}SerializerSettings::getInstance()->getDateTimeFormat().isEmpty()? value.toString(Qt::ISODate):value.toString({{prefix}}SerializerSettings::getInstance()->getDateTimeFormat()); } QString toStringValue(const QByteArray &value) { @@ -62,7 +98,7 @@ QJsonValue toJsonValue(const QString &value) { } QJsonValue toJsonValue(const QDateTime &value) { - return QJsonValue(value.toString(Qt::ISODate)); + return QJsonValue(value.toString({{prefix}}SerializerSettings::getInstance()->getDateTimeFormat().isEmpty()?value.toString(Qt::ISODate):value.toString({{prefix}}SerializerSettings::getInstance()->getDateTimeFormat()))); } QJsonValue toJsonValue(const QByteArray &value) { @@ -115,7 +151,7 @@ bool fromStringValue(const QString &inStr, QDateTime &value) { if (inStr.isEmpty()) { return false; } else { - auto dateTime = QDateTime::fromString(inStr, "yyyy-MM-ddTHH:mm:ss[Z|[+|-]HH:mm]"); + auto dateTime = {{prefix}}SerializerSettings::getInstance()->getDateTimeFormat().isEmpty()?QDateTime::fromString(inStr, Qt::ISODate) :QDateTime::fromString(inStr, {{prefix}}SerializerSettings::getInstance()->getDateTimeFormat()); if (dateTime.isValid()) { value.setDate(dateTime.date()); value.setTime(dateTime.time()); @@ -220,7 +256,7 @@ bool fromJsonValue(QString &value, const QJsonValue &jval) { bool fromJsonValue(QDateTime &value, const QJsonValue &jval) { bool ok = true; if (!jval.isUndefined() && !jval.isNull() && jval.isString()) { - value = QDateTime::fromString(jval.toString(), Qt::ISODate); + value = {{prefix}}SerializerSettings::getInstance()->getDateTimeFormat().isEmpty()?QDateTime::fromString(jval.toString(), Qt::ISODate): QDateTime::fromString(jval.toString(), {{prefix}}SerializerSettings::getInstance()->getDateTimeFormat()); ok = value.isValid(); } else { ok = false; diff --git a/modules/openapi-generator/src/main/resources/cpp-qt5-qhttpengine-server/helpers-header.mustache b/modules/openapi-generator/src/main/resources/cpp-qt5-qhttpengine-server/helpers-header.mustache index a53e0a30edd9..0a8e6b8b2145 100644 --- a/modules/openapi-generator/src/main/resources/cpp-qt5-qhttpengine-server/helpers-header.mustache +++ b/modules/openapi-generator/src/main/resources/cpp-qt5-qhttpengine-server/helpers-header.mustache @@ -20,6 +20,8 @@ namespace {{this}} { {{/cppNamespaceDeclarations}} +bool setDateTimeFormat(const QString&); + template QString toStringValue(const QList &val); diff --git a/modules/openapi-generator/src/main/resources/cpp-qt5-qhttpengine-server/model-body.mustache b/modules/openapi-generator/src/main/resources/cpp-qt5-qhttpengine-server/model-body.mustache index 05f22ceb8fb9..e48e1597db1f 100644 --- a/modules/openapi-generator/src/main/resources/cpp-qt5-qhttpengine-server/model-body.mustache +++ b/modules/openapi-generator/src/main/resources/cpp-qt5-qhttpengine-server/model-body.mustache @@ -120,6 +120,14 @@ void {{classname}}::{{setter}}(const {{{dataType}}} &{{name}}) { this->m_{{name}}_isSet = true; } +bool {{classname}}::is_{{name}}_Set() const{ + return m_{{name}}_isSet; +} + +bool {{classname}}::is_{{name}}_Valid() const{ + return m_{{name}}_isValid; +} + {{/vars}}{{/isEnum}}{{#isEnum}} {{classname}}::e{{classname}} {{classname}}::getValue() const { return m_value; diff --git a/modules/openapi-generator/src/main/resources/cpp-qt5-qhttpengine-server/model-header.mustache b/modules/openapi-generator/src/main/resources/cpp-qt5-qhttpengine-server/model-header.mustache index 8f194ac12f9c..5bbe8c8c20e1 100644 --- a/modules/openapi-generator/src/main/resources/cpp-qt5-qhttpengine-server/model-header.mustache +++ b/modules/openapi-generator/src/main/resources/cpp-qt5-qhttpengine-server/model-header.mustache @@ -35,6 +35,8 @@ public: {{^isEnum}}{{#vars}} {{{dataType}}} {{getter}}() const; void {{setter}}(const {{{dataType}}} &{{name}}); + bool is_{{name}}_Set() const; + bool is_{{name}}_Valid() const; {{/vars}}{{/isEnum}}{{#isEnum}} {{#allowableValues}} enum class e{{classname}} {{#enumVars}}{{#-first}}{{^isString}}: int {{/isString}}{{/-first}}{{/enumVars}}{ diff --git a/modules/openapi-generator/src/main/resources/csharp-dotnet2/ApiClient.mustache b/modules/openapi-generator/src/main/resources/csharp-dotnet2/ApiClient.mustache index c382839d8984..1938e277989a 100644 --- a/modules/openapi-generator/src/main/resources/csharp-dotnet2/ApiClient.mustache +++ b/modules/openapi-generator/src/main/resources/csharp-dotnet2/ApiClient.mustache @@ -261,8 +261,25 @@ namespace {{clientPackage}} { {{#authMethods}} case "{{name}}": - {{#isApiKey}}{{#isKeyInHeader}}headerParams["{{keyParamName}}"] = GetApiKeyWithPrefix("{{keyParamName}}");{{/isKeyInHeader}}{{#isKeyInQuery}}queryParams["{{keyParamName}}"] = GetApiKeyWithPrefix("{{keyParamName}}");{{/isKeyInQuery}}{{/isApiKey}}{{#isBasic}}headerParams["Authorization"] = "Basic " + Base64Encode(Configuration.Username + ":" + Configuration.Password);{{/isBasic}} - {{#isOAuth}}//TODO support oauth{{/isOAuth}} + {{#isApiKey}} + {{#isKeyInHeader}} + headerParams["{{keyParamName}}"] = GetApiKeyWithPrefix("{{keyParamName}}"); + {{/isKeyInHeader}} + {{#isKeyInQuery}} + queryParams["{{keyParamName}}"] = GetApiKeyWithPrefix("{{keyParamName}}"); + {{/isKeyInQuery}} + {{/isApiKey}} + {{#isBasic}} + {{#isBasicBasic}} + headerParams["Authorization"] = "Basic " + Base64Encode(Configuration.Username + ":" + Configuration.Password); + {{/isBasicBasic}} + {{#isBasicBearer}} + headerParams["Authorization"] = "Bearer " + Configuration.AccessToken; + {{/isBasicBearer}} + {{/isBasic}} + {{#isOAuth}} + headerParams["Authorization"] = "Bearer " + Configuration.AccessToken; + {{/isOAuth}} break; {{/authMethods}} default: diff --git a/modules/openapi-generator/src/main/resources/csharp-dotnet2/Configuration.mustache b/modules/openapi-generator/src/main/resources/csharp-dotnet2/Configuration.mustache index e09f39fc601e..77f755d61144 100644 --- a/modules/openapi-generator/src/main/resources/csharp-dotnet2/Configuration.mustache +++ b/modules/openapi-generator/src/main/resources/csharp-dotnet2/Configuration.mustache @@ -37,6 +37,12 @@ namespace {{clientPackage}} /// The password. public static String Password { get; set; } + /// + /// Gets or sets the access token (Bearer/OAuth authentication). + /// + /// The access token. + public static String AccessToken { get; set; } + /// /// Gets or sets the API key based on the authentication name. /// diff --git a/modules/openapi-generator/src/main/resources/csharp-dotnet2/README.mustache b/modules/openapi-generator/src/main/resources/csharp-dotnet2/README.mustache index 041dec963b05..0d8dfd814d44 100644 --- a/modules/openapi-generator/src/main/resources/csharp-dotnet2/README.mustache +++ b/modules/openapi-generator/src/main/resources/csharp-dotnet2/README.mustache @@ -56,16 +56,31 @@ namespace Example { public void main() { - {{#apiInfo}}{{#apis}}{{#-first}}{{#operations}}{{#operation}}{{#-first}}{{#hasAuthMethods}}{{#authMethods}}{{#isBasic}} + {{#apiInfo}}{{#apis}}{{#-first}}{{#operations}}{{#operation}}{{#-first}} + {{#hasAuthMethods}} + {{#authMethods}} + {{#isBasic}} + {{#isBasicBasic}} // Configure HTTP basic authorization: {{{name}}} Configuration.Default.Username = "YOUR_USERNAME"; - Configuration.Default.Password = "YOUR_PASSWORD";{{/isBasic}}{{#isApiKey}} + Configuration.Default.Password = "YOUR_PASSWORD"; + {{/isBasicBasic}} + {{#isBasicBearer}} + // Configure Bearer access token for authorization: {{{name}}} + Configuration.Default.AccessToken = "YOUR_ACCESS_TOKEN"; + {{/isBasicBearer}} + {{/isBasic}} + {{#isApiKey}} // Configure API key authorization: {{{name}}} Configuration.Default.ApiKey.Add("{{{keyParamName}}}", "YOUR_API_KEY"); // Uncomment below to setup prefix (e.g. Bearer) for API key, if needed - // Configuration.Default.ApiKeyPrefix.Add("{{{keyParamName}}}", "Bearer");{{/isApiKey}}{{#isOAuth}} + // Configuration.Default.ApiKeyPrefix.Add("{{{keyParamName}}}", "Bearer"); + {{/isApiKey}} + {{#isOAuth}} // Configure OAuth2 access token for authorization: {{{name}}} - Configuration.Default.AccessToken = "YOUR_ACCESS_TOKEN";{{/isOAuth}}{{/authMethods}} + Configuration.Default.AccessToken = "YOUR_ACCESS_TOKEN"; + {{/isOAuth}} + {{/authMethods}} {{/hasAuthMethods}} var apiInstance = new {{classname}}(); @@ -123,21 +138,29 @@ No model defined in this package All endpoints do not require authorization. {{/authMethods}} {{#authMethods}} -{{#last}} +{{#-last}} Authentication schemes defined for the API: -{{/last}} +{{/-last}} {{/authMethods}} {{#authMethods}} ### {{name}} -{{#isApiKey}}- **Type**: API key +{{#isApiKey}} +- **Type**: API key - **API key parameter name**: {{keyParamName}} - **Location**: {{#isKeyInQuery}}URL query string{{/isKeyInQuery}}{{#isKeyInHeader}}HTTP header{{/isKeyInHeader}} {{/isApiKey}} -{{#isBasic}}- **Type**: HTTP basic authentication +{{#isBasic}} +{{#isBasicBasic}} +- **Type**: HTTP basic authentication +{{/isBasicBasic}} +{{#isBasicBearer}} +- **Type**: HTTP bearer authentication +{{/isBasicBearer}} {{/isBasic}} -{{#isOAuth}}- **Type**: OAuth +{{#isOAuth}} +- **Type**: OAuth - **Flow**: {{flow}} - **Authorization URL**: {{authorizationUrl}} - **Scopes**: {{^scopes}}N/A{{/scopes}} diff --git a/modules/openapi-generator/src/main/resources/csharp-dotnet2/api_doc.mustache b/modules/openapi-generator/src/main/resources/csharp-dotnet2/api_doc.mustache index 1a7727618947..325e1426014a 100644 --- a/modules/openapi-generator/src/main/resources/csharp-dotnet2/api_doc.mustache +++ b/modules/openapi-generator/src/main/resources/csharp-dotnet2/api_doc.mustache @@ -32,18 +32,32 @@ namespace Example { public void main() { - {{#hasAuthMethods}}{{#authMethods}}{{#isBasic}} + {{#hasAuthMethods}} + {{#authMethods}} + {{#isBasic}} + {{#isBasicBasic}} // Configure HTTP basic authorization: {{{name}}} Configuration.Default.Username = "YOUR_USERNAME"; - Configuration.Default.Password = "YOUR_PASSWORD";{{/isBasic}}{{#isApiKey}} + Configuration.Default.Password = "YOUR_PASSWORD"; + {{/isBasicBasic}} + {{#isBasicBearer}} + // Configure Bearer access token: {{{name}}} + Configuration.Default.AccessToken = "YOUR_ACCESS_TOKEN"; + {{/isBasicBearer}} + {{/isBasic}} + {{#isApiKey}} // Configure API key authorization: {{{name}}} Configuration.Default.ApiKey.Add("{{{keyParamName}}}", "YOUR_API_KEY"); // Uncomment below to setup prefix (e.g. Bearer) for API key, if needed - // Configuration.Default.ApiKeyPrefix.Add("{{{keyParamName}}}", "Bearer");{{/isApiKey}}{{#isOAuth}} + // Configuration.Default.ApiKeyPrefix.Add("{{{keyParamName}}}", "Bearer"); + {{/isApiKey}} + {{#isOAuth}} // Configure OAuth2 access token for authorization: {{{name}}} - Configuration.Default.AccessToken = "YOUR_ACCESS_TOKEN";{{/isOAuth}}{{/authMethods}} - {{/hasAuthMethods}} + Configuration.Default.AccessToken = "YOUR_ACCESS_TOKEN"; + {{/isOAuth}} + {{/authMethods}} + {{/hasAuthMethods}} var apiInstance = new {{classname}}(); {{#allParams}} {{#isPrimitiveType}} diff --git a/modules/openapi-generator/src/main/resources/csharp-netcore/ClientUtils.mustache b/modules/openapi-generator/src/main/resources/csharp-netcore/ClientUtils.mustache index b407a4edd08d..f756a2c86aeb 100755 --- a/modules/openapi-generator/src/main/resources/csharp-netcore/ClientUtils.mustache +++ b/modules/openapi-generator/src/main/resources/csharp-netcore/ClientUtils.mustache @@ -169,7 +169,7 @@ namespace {{packageName}}.Client public static String SelectHeaderContentType(String[] contentTypes) { if (contentTypes.Length == 0) - return "application/json"; + return null; foreach (var contentType in contentTypes) { diff --git a/modules/openapi-generator/src/main/resources/csharp-netcore/README.mustache b/modules/openapi-generator/src/main/resources/csharp-netcore/README.mustache index 666e7933c0a9..b0f7b5cc2247 100644 --- a/modules/openapi-generator/src/main/resources/csharp-netcore/README.mustache +++ b/modules/openapi-generator/src/main/resources/csharp-netcore/README.mustache @@ -105,11 +105,15 @@ namespace Example config.BasePath = "{{{basePath}}}"; {{#hasAuthMethods}} {{#authMethods}} - {{#isBasic}} + {{#isBasicBasic}} // Configure HTTP basic authorization: {{{name}}} config.Username = "YOUR_USERNAME"; config.Password = "YOUR_PASSWORD"; - {{/isBasic}} + {{/isBasicBasic}} + {{#isBasicBearer}} + // Configure Bearer token for authorization: {{{name}}} + config.AccessToken = "YOUR_BEARER_TOKEN"; + {{/isBasicBearer}} {{#isApiKey}} // Configure API key authorization: {{{name}}} config.ApiKey.Add("{{{keyParamName}}}", "YOUR_API_KEY"); @@ -193,8 +197,10 @@ Authentication schemes defined for the API: - **API key parameter name**: {{keyParamName}} - **Location**: {{#isKeyInQuery}}URL query string{{/isKeyInQuery}}{{#isKeyInHeader}}HTTP header{{/isKeyInHeader}} {{/isApiKey}} -{{#isBasic}}- **Type**: HTTP basic authentication -{{/isBasic}} +{{#isBasicBasic}}- **Type**: HTTP basic authentication +{{/isBasicBasic}} +{{#isBasicBearer}}- **Type**: Bearer Authentication +{{/isBasicBearer}} {{#isOAuth}}- **Type**: OAuth - **Flow**: {{flow}} - **Authorization URL**: {{authorizationUrl}} diff --git a/modules/openapi-generator/src/main/resources/csharp-netcore/api.mustache b/modules/openapi-generator/src/main/resources/csharp-netcore/api.mustache index f149f196b390..af912e73577f 100644 --- a/modules/openapi-generator/src/main/resources/csharp-netcore/api.mustache +++ b/modules/openapi-generator/src/main/resources/csharp-netcore/api.mustache @@ -325,13 +325,20 @@ namespace {{packageName}}.{{apiPackage}} } {{/isKeyInQuery}} {{/isApiKey}} - {{#isBasic}} + {{#isBasicBasic}} // http basic authentication required if (!String.IsNullOrEmpty(this.Configuration.Username) || !String.IsNullOrEmpty(this.Configuration.Password)) { localVarRequestOptions.HeaderParameters.Add("Authorization", "Basic " + {{packageName}}.Client.ClientUtils.Base64Encode(this.Configuration.Username + ":" + this.Configuration.Password)); } - {{/isBasic}} + {{/isBasicBasic}} + {{#isBasicBearer}} + // bearer authentication required + if (!String.IsNullOrEmpty(this.Configuration.AccessToken)) + { + localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); + } + {{/isBasicBearer}} {{#isOAuth}} // oauth required if (!String.IsNullOrEmpty(this.Configuration.AccessToken)) diff --git a/modules/openapi-generator/src/main/resources/csharp-netcore/api_doc.mustache b/modules/openapi-generator/src/main/resources/csharp-netcore/api_doc.mustache index 544411db910f..7447e20594b5 100644 --- a/modules/openapi-generator/src/main/resources/csharp-netcore/api_doc.mustache +++ b/modules/openapi-generator/src/main/resources/csharp-netcore/api_doc.mustache @@ -36,11 +36,15 @@ namespace Example config.BasePath = "{{{basePath}}}"; {{#hasAuthMethods}} {{#authMethods}} - {{#isBasic}} + {{#isBasicBasic}} // Configure HTTP basic authorization: {{{name}}} config.Username = "YOUR_USERNAME"; config.Password = "YOUR_PASSWORD"; - {{/isBasic}} + {{/isBasicBasic}} + {{#isBasicBearer}} + // Configure Bearer token for authorization: {{{name}}} + config.AccessToken = "YOUR_BEARER_TOKEN"; + {{/isBasicBearer}} {{#isApiKey}} // Configure API key authorization: {{{name}}} config.AddApiKey("{{{keyParamName}}}", "YOUR_API_KEY"); diff --git a/modules/openapi-generator/src/main/resources/csharp-netcore/modelGeneric.mustache b/modules/openapi-generator/src/main/resources/csharp-netcore/modelGeneric.mustache index b2b13cfa3c81..eb69cfc3eb13 100644 --- a/modules/openapi-generator/src/main/resources/csharp-netcore/modelGeneric.mustache +++ b/modules/openapi-generator/src/main/resources/csharp-netcore/modelGeneric.mustache @@ -63,7 +63,7 @@ {{#required}} {{^vendorExtensions.x-csharp-value-type}} // to ensure "{{#lambda.camelcase_param}}{{name}}{{/lambda.camelcase_param}}" is required (not null) - this.{{name}} = {{#lambda.camelcase_param}}{{name}}{{/lambda.camelcase_param}} ?? throw new ArgumentNullException("{{#lambda.camelcase_param}}{{name}}{{/lambda.camelcase_param}} is a required property for {{classname}} and cannot be null");; + this.{{name}} = {{#lambda.camelcase_param}}{{name}}{{/lambda.camelcase_param}} ?? throw new ArgumentNullException("{{#lambda.camelcase_param}}{{name}}{{/lambda.camelcase_param}} is a required property for {{classname}} and cannot be null"); {{/vendorExtensions.x-csharp-value-type}} {{#vendorExtensions.x-csharp-value-type}} this.{{name}} = {{#lambda.camelcase_param}}{{name}}{{/lambda.camelcase_param}}; diff --git a/modules/openapi-generator/src/main/resources/csharp/ApiClient.mustache b/modules/openapi-generator/src/main/resources/csharp/ApiClient.mustache index 1b6ee4fa8ade..6e70b0d4a9c7 100644 --- a/modules/openapi-generator/src/main/resources/csharp/ApiClient.mustache +++ b/modules/openapi-generator/src/main/resources/csharp/ApiClient.mustache @@ -153,7 +153,7 @@ namespace {{packageName}}.Client {{/netStandard}} {{^netStandard}} {{^supportsUWP}} - request.AddFile(param.Value.Name, param.Value.Writer, param.Value.FileName, param.Value.ContentType); + request.AddFile(param.Value.Name, param.Value.Writer, param.Value.FileName{{#isRestSharp_106_10_1_above}}, param.Value.ContentLength{{/isRestSharp_106_10_1_above}}, param.Value.ContentType); {{/supportsUWP}} {{#supportsUWP}} byte[] paramWriter = null; @@ -565,6 +565,7 @@ namespace {{packageName}}.Client /// Convert params to key/value pairs. /// Use collectionFormat to properly format lists and collections. /// + /// Collection format. /// Key name. /// Value object. /// A list of KeyValuePairs diff --git a/modules/openapi-generator/src/main/resources/csharp/Project.mustache b/modules/openapi-generator/src/main/resources/csharp/Project.mustache index c5b763016f9f..c1862f7cb8c2 100644 --- a/modules/openapi-generator/src/main/resources/csharp/Project.mustache +++ b/modules/openapi-generator/src/main/resources/csharp/Project.mustache @@ -69,26 +69,26 @@ - $(SolutionDir)\packages\Newtonsoft.Json.12.0.1\lib\{{targetFrameworkNuget}}\Newtonsoft.Json.dll - ..\packages\Newtonsoft.Json.12.0.1\lib\{{targetFrameworkNuget}}\Newtonsoft.Json.dll - ..\..\packages\Newtonsoft.Json.12.0.1\lib\{{targetFrameworkNuget}}\Newtonsoft.Json.dll - {{binRelativePath}}\Newtonsoft.Json.12.0.1\lib\{{targetFrameworkNuget}}\Newtonsoft.Json.dll + $(SolutionDir)\packages\Newtonsoft.Json.{{newtonsoft-json.version}}\lib\{{newtonsoft-json.targetFramework}}\Newtonsoft.Json.dll + ..\packages\Newtonsoft.Json.{{newtonsoft-json.version}}\lib\{{newtonsoft-json.targetFramework}}\Newtonsoft.Json.dll + ..\..\packages\Newtonsoft.Json.{{newtonsoft-json.version}}\lib\{{newtonsoft-json.targetFramework}}\Newtonsoft.Json.dll + {{binRelativePath}}\Newtonsoft.Json.{{newtonsoft-json.version}}\lib\{{newtonsoft-json.targetFramework}}\Newtonsoft.Json.dll - $(SolutionDir)\packages\JsonSubTypes.1.5.2\lib\{{targetFrameworkNuget}}\JsonSubTypes.dll - ..\packages\JsonSubTypes.1.5.2\lib\{{targetFrameworkNuget}}\JsonSubTypes.dll - ..\..\packages\JsonSubTypes.1.5.2\lib\{{targetFrameworkNuget}}\JsonSubTypes.dll - {{binRelativePath}}\JsonSubTypes.1.5.2\lib\{{targetFrameworkNuget}}\JsonSubTypes.dll + $(SolutionDir)\packages\JsonSubTypes.{{json-subtypes.version}}\lib\{{json-subtypes.targetFramework}}\JsonSubTypes.dll + ..\packages\JsonSubTypes.{{json-subtypes.version}}\lib\{{json-subtypes.targetFramework}}\JsonSubTypes.dll + ..\..\packages\JsonSubTypes.{{json-subtypes.version}}\lib\{{json-subtypes.targetFramework}}\JsonSubTypes.dll + {{binRelativePath}}\JsonSubTypes.{{json-subtypes.version}}\lib\{{json-subtypes.targetFramework}}\JsonSubTypes.dll - $(SolutionDir)\packages\RestSharp.105.1.0\lib\{{#isNet40}}net4{{/isNet40}}{{^isNet40}}{{targetFrameworkNuget}}{{/isNet40}}\RestSharp.dll - ..\packages\RestSharp.105.1.0\lib\{{#isNet40}}net4{{/isNet40}}{{^isNet40}}{{targetFrameworkNuget}}{{/isNet40}}\RestSharp.dll - ..\..\packages\RestSharp.105.1.0\lib\{{#isNet40}}net4{{/isNet40}}{{^isNet40}}{{targetFrameworkNuget}}{{/isNet40}}\RestSharp.dll - {{binRelativePath}}\RestSharp.105.1.0\lib\{{#isNet40}}net4{{/isNet40}}{{^isNet40}}{{targetFrameworkNuget}}{{/isNet40}}\RestSharp.dll + $(SolutionDir)\packages\RestSharp.{{restsharp.version}}\lib\{{restsharp.targetFramework}}\RestSharp.dll + ..\packages\RestSharp.{{restsharp.version}}\lib\{{restsharp.targetFramework}}\RestSharp.dll + ..\..\packages\RestSharp.{{restsharp.version}}\lib\{{restsharp.targetFramework}}\RestSharp.dll + {{binRelativePath}}\RestSharp.{{restsharp.version}}\lib\{{restsharp.targetFramework}}\RestSharp.dll {{#generatePropertyChanged}} - ..\..\packages\PropertyChanged.Fody.1.51.3\Lib\portable-net4+sl4+wp8+win8+wpa81+MonoAndroid16+MonoTouch40\PropertyChanged.dll + ..\..\packages\PropertyChanged.Fody.{{propertychanged-fody.version}}\Lib\portable-net4+sl4+wp8+win8+wpa81+MonoAndroid16+MonoTouch40\PropertyChanged.dll {{/generatePropertyChanged}} {{/netStandard}} @@ -110,7 +110,7 @@ {{#generatePropertyChanged}} - + {{/generatePropertyChanged}} {{/netStandard}} {{#netStandard}} diff --git a/modules/openapi-generator/src/main/resources/csharp/README.mustache b/modules/openapi-generator/src/main/resources/csharp/README.mustache index 474bfe829b40..da6053f4aa26 100644 --- a/modules/openapi-generator/src/main/resources/csharp/README.mustache +++ b/modules/openapi-generator/src/main/resources/csharp/README.mustache @@ -119,9 +119,15 @@ namespace Example {{#hasAuthMethods}} {{#authMethods}} {{#isBasic}} + {{#isBasicBasic}} // Configure HTTP basic authorization: {{{name}}} Configuration.Default.Username = "YOUR_USERNAME"; Configuration.Default.Password = "YOUR_PASSWORD"; + {{/isBasicBasic}} + {{#isBasicBearer}} + // Configure HTTP bearer authorization: {{{name}}} + Configuration.Default.AccessToken = "YOUR_ACCESS_TOKEN"; + {{/isBasicBearer}} {{/isBasic}} {{#isApiKey}} // Configure API key authorization: {{{name}}} @@ -205,8 +211,14 @@ Authentication schemes defined for the API: - **Location**: {{#isKeyInQuery}}URL query string{{/isKeyInQuery}}{{#isKeyInHeader}}HTTP header{{/isKeyInHeader}} {{/isApiKey}} {{#isBasic}} +{{#isBasicBasic}} - **Type**: HTTP basic authentication +{{/isBasicBasic}} +{{#isBasicBearer}} + +- **Type**: HTTP bearer authentication +{{/isBasicBearer}} {{/isBasic}} {{#isOAuth}} diff --git a/modules/openapi-generator/src/main/resources/csharp/TestProject.mustache b/modules/openapi-generator/src/main/resources/csharp/TestProject.mustache index 0b1f35a53db2..3e850f2f3ac6 100644 --- a/modules/openapi-generator/src/main/resources/csharp/TestProject.mustache +++ b/modules/openapi-generator/src/main/resources/csharp/TestProject.mustache @@ -59,28 +59,28 @@ - $(SolutionDir)\packages\Newtonsoft.Json.12.0.1\lib\{{targetFrameworkNuget}}\Newtonsoft.Json.dll - ..\packages\Newtonsoft.Json.12.0.1\lib\{{targetFrameworkNuget}}\Newtonsoft.Json.dll - ..\..\packages\Newtonsoft.Json.12.0.1\lib\{{targetFrameworkNuget}}\Newtonsoft.Json.dll - {{binRelativePath}}\Newtonsoft.Json.12.0.1\lib\{{targetFrameworkNuget}}\Newtonsoft.Json.dll + $(SolutionDir)\packages\Newtonsoft.Json.{{newtonsoft-json.version}}\lib\{{newtonsoft-json.targetFramework}}\Newtonsoft.Json.dll + ..\packages\Newtonsoft.Json.{{newtonsoft-json.version}}\lib\{{newtonsoft-json.targetFramework}}\Newtonsoft.Json.dll + ..\..\packages\Newtonsoft.Json.{{newtonsoft-json.version}}\lib\{{newtonsoft-json.targetFramework}}\Newtonsoft.Json.dll + {{binRelativePath}}\Newtonsoft.Json.{{newtonsoft-json.version}}\lib\{{newtonsoft-json.targetFramework}}\Newtonsoft.Json.dll - $(SolutionDir)\packages\JsonSubTypes.1.5.2\lib\{{targetFrameworkNuget}}\JsonSubTypes.dll - ..\packages\JsonSubTypes.1.5.2\lib\{{targetFrameworkNuget}}\JsonSubTypes.dll - ..\..\packages\JsonSubTypes.1.5.2\lib\{{targetFrameworkNuget}}\JsonSubTypes.dll - {{binRelativePath}}\JsonSubTypes.1.5.2\lib\{{targetFrameworkNuget}}\JsonSubTypes.dll + $(SolutionDir)\packages\JsonSubTypes.{{json-subtypes.version}}\lib\{{json-subtypes.targetFramework}}\JsonSubTypes.dll + ..\packages\JsonSubTypes.{{json-subtypes.version}}\lib\{{json-subtypes.targetFramework}}\JsonSubTypes.dll + ..\..\packages\JsonSubTypes.{{json-subtypes.version}}\lib\{{json-subtypes.targetFramework}}\JsonSubTypes.dll + {{binRelativePath}}\JsonSubTypes.{{json-subtypes.version}}\lib\{{json-subtypes.targetFramework}}\JsonSubTypes.dll - $(SolutionDir)\packages\RestSharp.105.1.0\lib\{{#isNet40}}net4{{/isNet40}}{{^isNet40}}{{targetFrameworkNuget}}{{/isNet40}}\RestSharp.dll - ..\packages\RestSharp.105.1.0\lib\{{#isNet40}}net4{{/isNet40}}{{^isNet40}}{{targetFrameworkNuget}}{{/isNet40}}\RestSharp.dll - ..\..\packages\RestSharp.105.1.0\lib\{{#isNet40}}net4{{/isNet40}}{{^isNet40}}{{targetFrameworkNuget}}{{/isNet40}}\RestSharp.dll - {{binRelativePath}}\RestSharp.105.1.0\lib\{{#isNet40}}net4{{/isNet40}}{{^isNet40}}{{targetFrameworkNuget}}{{/isNet40}}\RestSharp.dll + $(SolutionDir)\packages\RestSharp.{{restsharp.version}}\lib\{{restsharp.targetFramework}}\RestSharp.dll + ..\packages\RestSharp.{{restsharp.version}}\lib\{{restsharp.targetFramework}}\RestSharp.dll + ..\..\packages\RestSharp.{{restsharp.version}}\lib\{{restsharp.targetFramework}}\RestSharp.dll + {{binRelativePath}}\RestSharp.{{restsharp.version}}\lib\{{restsharp.targetFramework}}\RestSharp.dll - $(SolutionDir)\packages\NUnit.3.11.0\lib\net45\nunit.framework.dll - ..\packages\NUnit.3.11.0\lib\net45\nunit.framework.dll - ..\..\packages\NUnit.3.11.0\lib\net45\nunit.framework.dll - {{binRelativePath}}\NUnit.3.11.0\lib\net45\nunit.framework.dll + $(SolutionDir)\packages\NUnit.{{nunit.version}}\lib\{{nunit.targetFramework}}\nunit.framework.dll + ..\packages\NUnit.{{nunit.version}}\lib\{{nunit.targetFramework}}\nunit.framework.dll + ..\..\packages\NUnit.{{nunit.version}}\lib\{{nunit.targetFramework}}\nunit.framework.dll + {{binRelativePath}}\NUnit.{{nunit.version}}\lib\{{nunit.targetFramework}}\nunit.framework.dll diff --git a/modules/openapi-generator/src/main/resources/csharp/api.mustache b/modules/openapi-generator/src/main/resources/csharp/api.mustache index 9e68b292591e..a03009716943 100644 --- a/modules/openapi-generator/src/main/resources/csharp/api.mustache +++ b/modules/openapi-generator/src/main/resources/csharp/api.mustache @@ -248,7 +248,7 @@ namespace {{packageName}}.{{apiPackage}} if ({{paramName}} != null) localVarHeaderParams.Add("{{baseName}}", this.Configuration.ApiClient.ParameterToString({{paramName}})); // header parameter {{/headerParams}} {{#formParams}} - if ({{paramName}} != null) {{#isFile}}localVarFileParams.Add("{{baseName}}", this.Configuration.ApiClient.ParameterToFile("{{baseName}}", {{paramName}}));{{/isFile}}{{^isFile}}localVarFormParams.Add("{{baseName}}", this.Configuration.ApiClient.ParameterToString({{paramName}})); // form parameter{{/isFile}} + if ({{paramName}} != null) {{#isFile}}localVarFileParams.Add("{{baseName}}", this.Configuration.ApiClient.ParameterToFile("{{baseName}}", {{paramName}}));{{/isFile}}{{^isFile}}localVarFormParams.Add("{{baseName}}", this.Configuration.ApiClient.{{#isPrimitiveType}}ParameterToString{{/isPrimitiveType}}{{^isPrimitiveType}}Serialize{{/isPrimitiveType}}({{paramName}})); // form parameter{{/isFile}} {{/formParams}} {{#bodyParam}} if ({{paramName}} != null && {{paramName}}.GetType() != typeof(byte[])) @@ -278,11 +278,20 @@ namespace {{packageName}}.{{apiPackage}} {{/isKeyInQuery}} {{/isApiKey}} {{#isBasic}} + {{#isBasicBasic}} // http basic authentication required if (!String.IsNullOrEmpty(this.Configuration.Username) || !String.IsNullOrEmpty(this.Configuration.Password)) { localVarHeaderParams["Authorization"] = "Basic " + ApiClient.Base64Encode(this.Configuration.Username + ":" + this.Configuration.Password); } + {{/isBasicBasic}} + {{#isBasicBearer}} + // http beerer authentication required + if (!String.IsNullOrEmpty(this.Configuration.AccessToken)) + { + localVarHeaderParams["Authorization"] = "Bearer " + this.Configuration.AccessToken; + } + {{/isBasicBearer}} {{/isBasic}} {{#isOAuth}} // oauth required @@ -384,7 +393,7 @@ namespace {{packageName}}.{{apiPackage}} if ({{paramName}} != null) localVarHeaderParams.Add("{{baseName}}", this.Configuration.ApiClient.ParameterToString({{paramName}})); // header parameter {{/headerParams}} {{#formParams}} - if ({{paramName}} != null) {{#isFile}}localVarFileParams.Add("{{baseName}}", this.Configuration.ApiClient.ParameterToFile("{{baseName}}", {{paramName}}));{{/isFile}}{{^isFile}}localVarFormParams.Add("{{baseName}}", this.Configuration.ApiClient.ParameterToString({{paramName}})); // form parameter{{/isFile}} + if ({{paramName}} != null) {{#isFile}}localVarFileParams.Add("{{baseName}}", this.Configuration.ApiClient.ParameterToFile("{{baseName}}", {{paramName}}));{{/isFile}}{{^isFile}}localVarFormParams.Add("{{baseName}}", this.Configuration.ApiClient.{{#isPrimitiveType}}ParameterToString{{/isPrimitiveType}}{{^isPrimitiveType}}Serialize{{/isPrimitiveType}}({{paramName}})); // form parameter{{/isFile}} {{/formParams}} {{#bodyParam}} if ({{paramName}} != null && {{paramName}}.GetType() != typeof(byte[])) @@ -414,11 +423,20 @@ namespace {{packageName}}.{{apiPackage}} {{/isKeyInQuery}} {{/isApiKey}} {{#isBasic}} + {{#isBasicBasic}} // http basic authentication required if (!String.IsNullOrEmpty(this.Configuration.Username) || !String.IsNullOrEmpty(this.Configuration.Password)) { localVarHeaderParams["Authorization"] = "Basic " + ApiClient.Base64Encode(this.Configuration.Username + ":" + this.Configuration.Password); } + {{/isBasicBasic}} + {{#isBasicBearer}} + // http bearer authentication required + if (!String.IsNullOrEmpty(this.Configuration.AccessToken)) + { + localVarHeaderParams["Authorization"] = "Bearer " + this.Configuration.AccessToken; + } + {{/isBasicBearer}} {{/isBasic}} {{#isOAuth}} // oauth required diff --git a/modules/openapi-generator/src/main/resources/csharp/api_doc.mustache b/modules/openapi-generator/src/main/resources/csharp/api_doc.mustache index df59f42415cf..6e4bbf7c9a43 100644 --- a/modules/openapi-generator/src/main/resources/csharp/api_doc.mustache +++ b/modules/openapi-generator/src/main/resources/csharp/api_doc.mustache @@ -39,9 +39,15 @@ namespace Example {{#hasAuthMethods}} {{#authMethods}} {{#isBasic}} + {{#isBasicBasic}} // Configure HTTP basic authorization: {{{name}}} Configuration.Default.Username = "YOUR_USERNAME"; Configuration.Default.Password = "YOUR_PASSWORD"; + {{/isBasicBasic}} + {{#isBasicBearer}} + // Configure HTTP bearer authorization: {{{name}}} + Configuration.Default.AccessToken = "YOUR_ACCESS_TOKEN"; + {{/isBasicBearer}} {{/isBasic}} {{#isApiKey}} // Configure API key authorization: {{{name}}} diff --git a/modules/openapi-generator/src/main/resources/csharp/compile-mono.sh.mustache b/modules/openapi-generator/src/main/resources/csharp/compile-mono.sh.mustache index 3271da17f82e..06c5788a35e0 100644 --- a/modules/openapi-generator/src/main/resources/csharp/compile-mono.sh.mustache +++ b/modules/openapi-generator/src/main/resources/csharp/compile-mono.sh.mustache @@ -44,13 +44,13 @@ ${nuget_cmd} install src/{{packageName}}/packages.config -o packages; echo "[INFO] Copy DLLs to the 'bin' folder" mkdir -p bin; -cp packages/Newtonsoft.Json.12.0.1/lib/{{targetFrameworkNuget}}/Newtonsoft.Json.dll bin/Newtonsoft.Json.dll; -cp packages/RestSharp.105.1.0/lib/{{#isNet40}}net4{{/isNet40}}{{^isNet40}}{{targetFrameworkNuget}}{{/isNet40}}/RestSharp.dll bin/RestSharp.dll; -cp packages/JsonSubTypes.1.5.2/lib/{{targetFrameworkNuget}}/JsonSubTypes.dll bin/JsonSubTypes.dll +cp packages/Newtonsoft.Json.{{newtonsoft-json.version}}/lib/{{newtonsoft-json.targetFramework}}/Newtonsoft.Json.dll bin/Newtonsoft.Json.dll; +cp packages/RestSharp.{{restsharp.version}}/lib/{{restsharp.targetFramework}}/RestSharp.dll bin/RestSharp.dll; +cp packages/JsonSubTypes.{{json-subtypes.version}}/lib/{{json-subtypes.targetFramework}}/JsonSubTypes.dll bin/JsonSubTypes.dll {{#generatePropertyChanged}} -cp packages/Fody.1.29.4/Fody.dll bin/Fody.dll -cp packages/PropertyChanged.Fody.1.51.3/PropertyChanged.Fody.dll bin/PropertyChanged.Fody.dll -cp packages/PropertyChanged.Fody.1.51.3/Lib/dotnet/PropertyChanged.dll bin/PropertyChanged.dll +cp packages/Fody.{{fody.version}}/Fody.dll bin/Fody.dll +cp packages/PropertyChanged.Fody.{{propertychanged-fody.version}}/PropertyChanged.Fody.dll bin/PropertyChanged.Fody.dll +cp packages/PropertyChanged.Fody.{{propertychanged-fody.version}}/Lib/dotnet/PropertyChanged.dll bin/PropertyChanged.dll {{/generatePropertyChanged}} echo "[INFO] Run 'mcs' to build bin/{{{packageName}}}.dll" diff --git a/modules/openapi-generator/src/main/resources/csharp/compile.mustache b/modules/openapi-generator/src/main/resources/csharp/compile.mustache index 13f4569714b1..f80911357fd2 100644 --- a/modules/openapi-generator/src/main/resources/csharp/compile.mustache +++ b/modules/openapi-generator/src/main/resources/csharp/compile.mustache @@ -15,13 +15,13 @@ if not exist ".\nuget.exe" powershell -Command "(new-object System.Net.WebClient if not exist ".\bin" mkdir bin -copy packages\Newtonsoft.Json.12.0.1\lib\{{targetFrameworkNuget}}\Newtonsoft.Json.dll bin\Newtonsoft.Json.dll -copy packages\JsonSubTypes.1.5.2\lib\{{targetFrameworkNuget}}\JsonSubTypes.dll bin\JsonSubTypes.dll -copy packages\RestSharp.105.1.0\lib\{{#isNet40}}net4{{/isNet40}}{{^isNet40}}{{targetFrameworkNuget}}{{/isNet40}}\RestSharp.dll bin\RestSharp.dll +copy packages\Newtonsoft.Json.{{newtonsoft-json.version}}\lib\{{newtonsoft-json.targetFramework}}\Newtonsoft.Json.dll bin\Newtonsoft.Json.dll +copy packages\JsonSubTypes.{{json-subtypes.version}}\lib\{{json-subtypes.targetFramework}}\JsonSubTypes.dll bin\JsonSubTypes.dll +copy packages\RestSharp.{{restsharp.version}}\lib\{{restsharp.targetFramework}}\RestSharp.dll bin\RestSharp.dll {{#generatePropertyChanged}} -copy packages\Fody.1.29.4\Fody.dll bin\Fody.dll -copy packages\PropertyChanged.Fody.1.51.3\PropertyChanged.Fody.dll bin\PropertyChanged.Fody.dll -copy packages\PropertyChanged.Fody.1.51.3\Lib\dotnet\PropertyChanged.dll bin\PropertyChanged.dll +copy packages\Fody.{{fody.version}}\Fody.dll bin\Fody.dll +copy packages\PropertyChanged.Fody.{{propertychanged-fody.version}}\PropertyChanged.Fody.dll bin\PropertyChanged.Fody.dll +copy packages\PropertyChanged.Fody.{{propertychanged-fody.version}}\Lib\dotnet\PropertyChanged.dll bin\PropertyChanged.dll {{/generatePropertyChanged}} %CSCPATH%\csc /reference:bin\Newtonsoft.Json.dll;bin\JsonSubTypes.dll;bin\RestSharp.dll;System.ComponentModel.DataAnnotations.dll {{#generatePropertyChanged}}/r:bin\Fody.dll;bin\PropertyChanged.Fody.dll;bin\PropertyChanged.dll{{/generatePropertyChanged}} /target:library /out:bin\{{packageName}}.dll /recurse:src\{{packageName}}\*.cs /doc:bin\{{packageName}}.xml diff --git a/modules/openapi-generator/src/main/resources/csharp/modelGeneric.mustache b/modules/openapi-generator/src/main/resources/csharp/modelGeneric.mustache index 03117ce7de3f..65422c10c4de 100644 --- a/modules/openapi-generator/src/main/resources/csharp/modelGeneric.mustache +++ b/modules/openapi-generator/src/main/resources/csharp/modelGeneric.mustache @@ -3,7 +3,7 @@ /// [DataContract] {{#discriminator}} - [JsonConverter(typeof(JsonSubtypes), "{{{discriminatorName}}}")]{{#children}} + [JsonConverter(typeof(JsonSubtypes), "{{#lambda.camelcase_param}}{{{discriminatorName}}}{{/lambda.camelcase_param}}")]{{#children}} [JsonSubtypes.KnownSubType(typeof({{classname}}), "{{^vendorExtensions.x-discriminator-value}}{{name}}{{/vendorExtensions.x-discriminator-value}}{{#vendorExtensions.x-discriminator-value}}{{{vendorExtensions.x-discriminator-value}}}{{/vendorExtensions.x-discriminator-value}}")]{{/children}} {{/discriminator}} {{#generatePropertyChanged}} @@ -31,7 +31,7 @@ {{#description}} /// {{description}} {{/description}} - [DataMember(Name="{{baseName}}", EmitDefaultValue={{#vendorExtensions.x-emit-default-value}}true{{/vendorExtensions.x-emit-default-value}}{{^vendorExtensions.x-emit-default-value}}{{#isNullable}}true{{/isNullable}}{{^isNullable}}false{{/isNullable}}{{/vendorExtensions.x-emit-default-value}})] + [DataMember(Name="{{baseName}}", EmitDefaultValue={{#vendorExtensions.x-emit-default-value}}true{{/vendorExtensions.x-emit-default-value}}{{^vendorExtensions.x-emit-default-value}}{{#isNullable}}true{{/isNullable}}{{^isNullable}}{{#required}}true{{/required}}{{^required}}false{{/required}}{{/isNullable}}{{/vendorExtensions.x-emit-default-value}})] public {{#complexType}}{{{complexType}}}{{/complexType}}{{^complexType}}{{{datatypeWithEnum}}}{{/complexType}}{{^isContainer}}{{^required}}?{{/required}}{{/isContainer}} {{name}} { get; set; } {{/isEnum}} {{/vars}} @@ -108,7 +108,7 @@ this.{{name}} = {{#lambda.camelcase_param}}{{name}}{{/lambda.camelcase_param}}; /// {{^description}}Gets or Sets {{{name}}}{{/description}}{{#description}}{{description}}{{/description}} /// {{#description}} /// {{description}}{{/description}} - [DataMember(Name="{{baseName}}", EmitDefaultValue={{#vendorExtensions.x-emit-default-value}}true{{/vendorExtensions.x-emit-default-value}}{{^vendorExtensions.x-emit-default-value}}{{#isNullable}}true{{/isNullable}}{{^isNullable}}false{{/isNullable}}{{/vendorExtensions.x-emit-default-value}})]{{#isDate}} + [DataMember(Name="{{baseName}}", EmitDefaultValue={{#vendorExtensions.x-emit-default-value}}true{{/vendorExtensions.x-emit-default-value}}{{^vendorExtensions.x-emit-default-value}}{{#isNullable}}true{{/isNullable}}{{^isNullable}}{{#required}}true{{/required}}{{^required}}false{{/required}}{{/isNullable}}{{/vendorExtensions.x-emit-default-value}})]{{#isDate}} [JsonConverter(typeof(OpenAPIDateConverter))]{{/isDate}} public {{{dataType}}} {{name}} { get; {{#isReadOnly}}private {{/isReadOnly}}set; } {{/isEnum}} @@ -259,22 +259,44 @@ this.{{name}} = {{#lambda.camelcase_param}}{{name}}{{/lambda.camelcase_param}}; {{/parent}} {{#vars}} {{#hasValidation}} + {{#isEnum}} + {{#maxLength}} + // {{{name}}} ({{{dataType}}}) maxLength + if(this.{{{name}}} != null && this.{{{name}}}.ToString().Length > {{maxLength}}) + { + yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for {{{name}}}, length must be less than {{maxLength}}.", new [] { "{{{name}}}" }); + } + {{/maxLength}} + {{/isEnum}} + {{^isEnum}} {{#maxLength}} // {{{name}}} ({{{dataType}}}) maxLength if(this.{{{name}}} != null && this.{{{name}}}.Length > {{maxLength}}) { yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for {{{name}}}, length must be less than {{maxLength}}.", new [] { "{{{name}}}" }); } - {{/maxLength}} + {{/isEnum}} + + {{#isEnum}} + {{#minLength}} + // {{{name}}} ({{{dataType}}}) minLength + if(this.{{{name}}} != null && this.{{{name}}}.ToString().Length < {{minLength}}) + { + yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for {{{name}}}, length must be greater than {{minLength}}.", new [] { "{{{name}}}" }); + } + {{/minLength}} + {{/isEnum}} + {{^isEnum}} {{#minLength}} // {{{name}}} ({{{dataType}}}) minLength if(this.{{{name}}} != null && this.{{{name}}}.Length < {{minLength}}) { yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for {{{name}}}, length must be greater than {{minLength}}.", new [] { "{{{name}}}" }); } - {{/minLength}} + {{/isEnum}} + {{#maximum}} // {{{name}}} ({{{dataType}}}) maximum if(this.{{{name}}} > ({{{dataType}}}){{maximum}}) diff --git a/modules/openapi-generator/src/main/resources/csharp/netcore_project.mustache b/modules/openapi-generator/src/main/resources/csharp/netcore_project.mustache index 4d0e27a7b9ec..2cb30d650a5a 100644 --- a/modules/openapi-generator/src/main/resources/csharp/netcore_project.mustache +++ b/modules/openapi-generator/src/main/resources/csharp/netcore_project.mustache @@ -23,10 +23,10 @@ {{/netStandard}} {{^netStandard}} - + {{/netStandard}} - - + + {{^netStandard}} @@ -43,4 +43,4 @@ {{/netStandard}} - \ No newline at end of file + diff --git a/modules/openapi-generator/src/main/resources/csharp/netcore_testproject.mustache b/modules/openapi-generator/src/main/resources/csharp/netcore_testproject.mustache index cf00f15a8dad..bb052b0d7050 100644 --- a/modules/openapi-generator/src/main/resources/csharp/netcore_testproject.mustache +++ b/modules/openapi-generator/src/main/resources/csharp/netcore_testproject.mustache @@ -22,10 +22,10 @@ {{/netStandard}} {{^netStandard}} - + {{/netStandard}} - - + + {{^netStandard}} @@ -46,4 +46,4 @@ - \ No newline at end of file + diff --git a/modules/openapi-generator/src/main/resources/csharp/nuspec.mustache b/modules/openapi-generator/src/main/resources/csharp/nuspec.mustache index 003928a31a38..45ba3381de63 100644 --- a/modules/openapi-generator/src/main/resources/csharp/nuspec.mustache +++ b/modules/openapi-generator/src/main/resources/csharp/nuspec.mustache @@ -30,12 +30,12 @@ - - - + + + {{#generatePropertyChanged}} - - + + {{/generatePropertyChanged}} diff --git a/modules/openapi-generator/src/main/resources/csharp/packages.config.mustache b/modules/openapi-generator/src/main/resources/csharp/packages.config.mustache index c8d4841e60f4..56c892427aa7 100644 --- a/modules/openapi-generator/src/main/resources/csharp/packages.config.mustache +++ b/modules/openapi-generator/src/main/resources/csharp/packages.config.mustache @@ -1,10 +1,11 @@ - - - + + + + {{#generatePropertyChanged}} - - + + {{/generatePropertyChanged}} diff --git a/modules/openapi-generator/src/main/resources/csharp/packages_test.config.mustache b/modules/openapi-generator/src/main/resources/csharp/packages_test.config.mustache index 8ebdecf06b21..b6b6e7d980ff 100644 --- a/modules/openapi-generator/src/main/resources/csharp/packages_test.config.mustache +++ b/modules/openapi-generator/src/main/resources/csharp/packages_test.config.mustache @@ -1,7 +1,7 @@ - - - - + + + + diff --git a/modules/openapi-generator/src/main/resources/csharp/project.json.mustache b/modules/openapi-generator/src/main/resources/csharp/project.json.mustache index 29ad6d856939..9a85af07c5da 100644 --- a/modules/openapi-generator/src/main/resources/csharp/project.json.mustache +++ b/modules/openapi-generator/src/main/resources/csharp/project.json.mustache @@ -3,8 +3,8 @@ "dependencies": { "FubarCoder.RestSharp.Portable.Core": "4.0.7", "FubarCoder.RestSharp.Portable.HttpClient": "4.0.7", - "Newtonsoft.Json": "12.0.1", - "JsonSubTypes": "1.5.2" + "Newtonsoft.Json": "{{newtonsoft-json.version}}", + "JsonSubTypes": "{{json-subtypes.version}}" }, "frameworks": { "{{targetFrameworkNuget}}": {} diff --git a/modules/openapi-generator/src/main/resources/dart-dio/api.mustache b/modules/openapi-generator/src/main/resources/dart-dio/api.mustache index 112fd77f9993..48b73d914c02 100644 --- a/modules/openapi-generator/src/main/resources/dart-dio/api.mustache +++ b/modules/openapi-generator/src/main/resources/dart-dio/api.mustache @@ -55,6 +55,9 @@ class {{classname}} { } {{/isFile}} {{/isMultipart}} + {{^isMultipart}} + formData['{{baseName}}'] = parameterToString(_serializers, {{paramName}}); + {{/isMultipart}} {{/formParams}} bodyData = FormData.fromMap(formData); {{/hasFormParams}} diff --git a/modules/openapi-generator/src/main/resources/dart2/README.mustache b/modules/openapi-generator/src/main/resources/dart2/README.mustache index 54e7a4efd5f4..a16cba3d5fa2 100644 --- a/modules/openapi-generator/src/main/resources/dart2/README.mustache +++ b/modules/openapi-generator/src/main/resources/dart2/README.mustache @@ -53,9 +53,19 @@ import 'package:{{pubName}}/api.dart'; {{#hasAuthMethods}} {{#authMethods}} {{#isBasic}} +{{#isBasicBasic}} // TODO Configure HTTP basic authorization: {{{name}}} //defaultApiClient.getAuthentication('{{{name}}}').username = 'YOUR_USERNAME' //defaultApiClient.getAuthentication('{{{name}}}').password = 'YOUR_PASSWORD'; +{{/isBasicBasic}} +{{#isBasicBearer}} +// TODO Configure HTTP Bearer authorization: {{{name}}} +// Case 1. Use String Token +//defaultApiClient.getAuthentication('{{{name}}}').setAccessToken('YOUR_ACCESS_TOKEN'); +// Case 2. Use Function which generate token. +// String yourTokenGeneratorFunction() { ... } +//defaultApiClient.getAuthentication('{{{name}}}').setAccessToken(yourTokenGeneratorFunction); +{{/isBasicBearer}} {{/isBasic}} {{#isApiKey}} // TODO Configure API key authorization: {{{name}}} @@ -110,7 +120,13 @@ Class | Method | HTTP request | Description - **API key parameter name**: {{{keyParamName}}} - **Location**: {{#isKeyInQuery}}URL query string{{/isKeyInQuery}}{{#isKeyInHeader}}HTTP header{{/isKeyInHeader}} {{/isApiKey}} -{{#isBasic}}- **Type**: HTTP basic authentication +{{#isBasic}} +{{#isBasicBasic}} +- **Type**: HTTP basicc authentication +{{/isBasicBasic}} +{{#isBasicBearer}} +- **Type**: HTTP Bearer authentication +{{/isBasicBearer}} {{/isBasic}} {{#isOAuth}}- **Type**: OAuth - **Flow**: {{{flow}}} diff --git a/modules/openapi-generator/src/main/resources/dart2/api.mustache b/modules/openapi-generator/src/main/resources/dart2/api.mustache index c5acc6314dfc..44d413918e8b 100644 --- a/modules/openapi-generator/src/main/resources/dart2/api.mustache +++ b/modules/openapi-generator/src/main/resources/dart2/api.mustache @@ -46,10 +46,10 @@ class {{classname}} { List contentTypes = [{{#consumes}}"{{{mediaType}}}"{{#hasMore}},{{/hasMore}}{{/consumes}}]; - String contentType = contentTypes.isNotEmpty ? contentTypes[0] : "application/json"; + String nullableContentType = contentTypes.isNotEmpty ? contentTypes[0] : null; List authNames = [{{#authMethods}}"{{name}}"{{#hasMore}}, {{/hasMore}}{{/authMethods}}]; - if(contentType.startsWith("multipart/form-data")) { + if(nullableContentType != null && nullableContentType.startsWith("multipart/form-data")) { bool hasFields = false; MultipartRequest mp = MultipartRequest(null, null); {{#formParams}} @@ -85,7 +85,7 @@ class {{classname}} { postBody, headerParams, formParams, - contentType, + nullableContentType, authNames); return response; } diff --git a/modules/openapi-generator/src/main/resources/dart2/api_client.mustache b/modules/openapi-generator/src/main/resources/dart2/api_client.mustache index eaa3a3ed6063..d307654943b3 100644 --- a/modules/openapi-generator/src/main/resources/dart2/api_client.mustache +++ b/modules/openapi-generator/src/main/resources/dart2/api_client.mustache @@ -19,10 +19,25 @@ class ApiClient { final _regMap = RegExp(r'^Map$'); ApiClient({this.basePath = "{{{basePath}}}"}) { - // Setup authentications (key: authentication name, value: authentication).{{#authMethods}}{{#isBasic}} - _authentications['{{name}}'] = HttpBasicAuth();{{/isBasic}}{{#isApiKey}} - _authentications['{{name}}'] = ApiKeyAuth({{#isKeyInHeader}}"header"{{/isKeyInHeader}}{{^isKeyInHeader}}"query"{{/isKeyInHeader}}, "{{keyParamName}}");{{/isApiKey}}{{#isOAuth}} - _authentications['{{name}}'] = OAuth();{{/isOAuth}}{{/authMethods}} + {{#hasAuthMethods}} + // Setup authentications (key: authentication name, value: authentication). + {{#authMethods}} + {{#isBasic}} + {{#isBasicBasic}} + _authentications['{{name}}'] = HttpBasicAuth(); + {{/isBasicBasic}} + {{#isBasicBearer}} + _authentications['{{name}}'] = HttpBearerAuth(); + {{/isBasicBearer}} + {{/isBasic}} + {{#isApiKey}} + _authentications['{{name}}'] = ApiKeyAuth({{#isKeyInHeader}}"header"{{/isKeyInHeader}}{{^isKeyInHeader}}"query"{{/isKeyInHeader}}, "{{keyParamName}}"); + {{/isApiKey}} + {{#isOAuth}} + _authentications['{{name}}'] = OAuth(); + {{/isOAuth}} + {{/authMethods}} + {{/hasAuthMethods}} } void addDefaultHeader(String key, String value) { @@ -100,7 +115,7 @@ class ApiClient { Object body, Map headerParams, Map formParams, - String contentType, + String nullableContentType, List authNames) async { _updateParamsForAuth(authNames, queryParams, headerParams); @@ -116,7 +131,10 @@ class ApiClient { String url = basePath + path + queryString; headerParams.addAll(_defaultHeaderMap); - headerParams['Content-Type'] = contentType; + if (nullableContentType != null) { + final contentType = nullableContentType; + headerParams['Content-Type'] = contentType; + } if(body is MultipartRequest) { var request = MultipartRequest(method, Uri.parse(url)); @@ -127,20 +145,21 @@ class ApiClient { var response = await client.send(request); return Response.fromStream(response); } else { - var msgBody = contentType == "application/x-www-form-urlencoded" ? formParams : serialize(body); + var msgBody = nullableContentType == "application/x-www-form-urlencoded" ? formParams : serialize(body); + final nullableHeaderParams = (headerParams.isEmpty)? null: headerParams; switch(method) { case "POST": - return client.post(url, headers: headerParams, body: msgBody); + return client.post(url, headers: nullableHeaderParams, body: msgBody); case "PUT": - return client.put(url, headers: headerParams, body: msgBody); + return client.put(url, headers: nullableHeaderParams, body: msgBody); case "DELETE": - return client.delete(url, headers: headerParams); + return client.delete(url, headers: nullableHeaderParams); case "PATCH": - return client.patch(url, headers: headerParams, body: msgBody); + return client.patch(url, headers: nullableHeaderParams, body: msgBody); case "HEAD": - return client.head(url, headers: headerParams); + return client.head(url, headers: nullableHeaderParams); default: - return client.get(url, headers: headerParams); + return client.get(url, headers: nullableHeaderParams); } } } diff --git a/modules/openapi-generator/src/main/resources/dart2/api_doc.mustache b/modules/openapi-generator/src/main/resources/dart2/api_doc.mustache index 7ef24590d167..5e0192005d0b 100644 --- a/modules/openapi-generator/src/main/resources/dart2/api_doc.mustache +++ b/modules/openapi-generator/src/main/resources/dart2/api_doc.mustache @@ -28,9 +28,19 @@ import 'package:{{pubName}}/api.dart'; {{#hasAuthMethods}} {{#authMethods}} {{#isBasic}} +{{#isBasicBasic}} // TODO Configure HTTP basic authorization: {{{name}}} //defaultApiClient.getAuthentication('{{{name}}}').username = 'YOUR_USERNAME' //defaultApiClient.getAuthentication('{{{name}}}').password = 'YOUR_PASSWORD'; +{{/isBasicBasic}} +{{#isBasicBearer}} +// TODO Configure HTTP Bearer authorization: {{{name}}} +// Case 1. Use String Token +//defaultApiClient.getAuthentication('{{{name}}}').setAccessToken('YOUR_ACCESS_TOKEN'); +// Case 2. Use Function which generate token. +// String yourTokenGeneratorFunction() { ... } +//defaultApiClient.getAuthentication('{{{name}}}').setAccessToken(yourTokenGeneratorFunction); +{{/isBasicBearer}} {{/isBasic}} {{#isApiKey}} // TODO Configure API key authorization: {{{name}}} diff --git a/modules/openapi-generator/src/main/resources/dart2/apilib.mustache b/modules/openapi-generator/src/main/resources/dart2/apilib.mustache index 720ac0b0dbf5..365ae92eb1d3 100644 --- a/modules/openapi-generator/src/main/resources/dart2/apilib.mustache +++ b/modules/openapi-generator/src/main/resources/dart2/apilib.mustache @@ -11,6 +11,7 @@ part 'auth/authentication.dart'; part 'auth/api_key_auth.dart'; part 'auth/oauth.dart'; part 'auth/http_basic_auth.dart'; +part 'auth/http_bearer_auth.dart'; {{#apiInfo}}{{#apis}}part 'api/{{classFilename}}.dart'; {{/apis}}{{/apiInfo}} diff --git a/modules/openapi-generator/src/main/resources/dart2/auth/http_bearer_auth.mustache b/modules/openapi-generator/src/main/resources/dart2/auth/http_bearer_auth.mustache new file mode 100644 index 000000000000..7390098fc48a --- /dev/null +++ b/modules/openapi-generator/src/main/resources/dart2/auth/http_bearer_auth.mustache @@ -0,0 +1,25 @@ +part of {{pubName}}.api; + +class HttpBearerAuth implements Authentication { + dynamic _accessToken; + + HttpBearerAuth() { } + + @override + void applyToParams(List queryParams, Map headerParams) { + if (_accessToken is String) { + headerParams["Authorization"] = "Bearer " + _accessToken; + } else if (_accessToken is String Function()){ + headerParams["Authorization"] = "Bearer " + _accessToken(); + } else { + throw ArgumentError('Type of Bearer accessToken should be String or String Function().'); + } + } + + void setAccessToken(dynamic accessToken) { + if (!((accessToken is String) | (accessToken is String Function()))){ + throw ArgumentError('Type of Bearer accessToken should be String or String Function().'); + } + this._accessToken = accessToken; + } +} diff --git a/modules/openapi-generator/src/main/resources/dart2/enum.mustache b/modules/openapi-generator/src/main/resources/dart2/enum.mustache index df8d8ff90352..87bbed91767f 100644 --- a/modules/openapi-generator/src/main/resources/dart2/enum.mustache +++ b/modules/openapi-generator/src/main/resources/dart2/enum.mustache @@ -13,7 +13,7 @@ class {{classname}} { {{/enumVars}} {{/allowableValues}} - static {{classname}} fromJson(String value) { + static {{classname}} fromJson({{dataType}} value) { return new {{classname}}TypeTransformer().decode(value); } } diff --git a/modules/openapi-generator/src/main/resources/go-experimental/api.mustache b/modules/openapi-generator/src/main/resources/go-experimental/api.mustache index 96ac8f2d4a60..32bfc5a13367 100644 --- a/modules/openapi-generator/src/main/resources/go-experimental/api.mustache +++ b/modules/openapi-generator/src/main/resources/go-experimental/api.mustache @@ -286,6 +286,8 @@ func (r api{{operationId}}Request) Execute() ({{#returnType}}{{{.}}}, {{/returnT } {{#responses}} {{#dataType}} + {{^is1xx}} + {{^is2xx}} {{^wildcard}} if localVarHTTPResponse.StatusCode == {{{code}}} { {{/wildcard}} @@ -302,6 +304,8 @@ func (r api{{operationId}}Request) Execute() ({{#returnType}}{{{.}}}, {{/returnT {{^wildcard}} } {{/wildcard}} + {{/is2xx}} + {{/is1xx}} {{/dataType}} {{/responses}} return {{#returnType}}localVarReturnValue, {{/returnType}}localVarHTTPResponse, newErr diff --git a/modules/openapi-generator/src/main/resources/go-experimental/api_doc.mustache b/modules/openapi-generator/src/main/resources/go-experimental/api_doc.mustache index af211afe9b7b..0ab0d27a346a 100644 --- a/modules/openapi-generator/src/main/resources/go-experimental/api_doc.mustache +++ b/modules/openapi-generator/src/main/resources/go-experimental/api_doc.mustache @@ -20,6 +20,37 @@ Method | HTTP request | Description {{{unespacedNotes}}}{{/notes}} +### Example + +```go +package main + +import ( + "context" + "fmt" + "os" + {{goImportAlias}} "./openapi" +) + +func main() { + {{#allParams}} + {{paramName}} := {{{vendorExtensions.x-go-example}}} // {{{dataType}}} | {{{description}}}{{^required}} (optional){{/required}}{{#defaultValue}} (default to {{{.}}}){{/defaultValue}} + {{/allParams}} + + configuration := {{goImportAlias}}.NewConfiguration() + api_client := {{goImportAlias}}.NewAPIClient(configuration) + resp, r, err := api_client.{{classname}}.{{operationId}}(context.Background(), {{#requiredParams}}{{paramName}}{{^-last}}, {{/-last}}{{/requiredParams}}){{#optionalParams}}.{{{vendorExtensions.x-export-param-name}}}({{{paramName}}}){{/optionalParams}}.Execute() + if err != nil { + fmt.Fprintf(os.Stderr, "Error when calling `{{classname}}.{{operationId}}``: %v\n", err) + fmt.Fprintf(os.Stderr, "Full HTTP response: %v\n", r) + } + {{#returnType}} + // response from `{{operationId}}`: {{{.}}} + fmt.Fprintf(os.Stdout, "Response from `{{classname}}.{{operationId}}`: %v\n", resp) + {{/returnType}} +} +``` + ### Path Parameters {{^allParams}}This endpoint does not need any parameter.{{/allParams}}{{#pathParams}}{{#-last}} diff --git a/modules/openapi-generator/src/main/resources/go/api.mustache b/modules/openapi-generator/src/main/resources/go/api.mustache index d241805b54f7..7805eaae6895 100644 --- a/modules/openapi-generator/src/main/resources/go/api.mustache +++ b/modules/openapi-generator/src/main/resources/go/api.mustache @@ -320,6 +320,8 @@ func (a *{{{classname}}}Service) {{{nickname}}}(ctx _context.Context{{#hasParams } {{#responses}} {{#dataType}} + {{^is1xx}} + {{^is2xx}} {{^wildcard}} if localVarHTTPResponse.StatusCode == {{{code}}} { {{/wildcard}} @@ -336,6 +338,8 @@ func (a *{{{classname}}}Service) {{{nickname}}}(ctx _context.Context{{#hasParams {{^wildcard}} } {{/wildcard}} + {{/is2xx}} + {{/is1xx}} {{/dataType}} {{/responses}} return {{#returnType}}localVarReturnValue, {{/returnType}}localVarHTTPResponse, newErr diff --git a/modules/openapi-generator/src/main/resources/htmlDocs2/index.mustache b/modules/openapi-generator/src/main/resources/htmlDocs2/index.mustache index 1cb04a58a9f9..e82cd10725d7 100644 --- a/modules/openapi-generator/src/main/resources/htmlDocs2/index.mustache +++ b/modules/openapi-generator/src/main/resources/htmlDocs2/index.mustache @@ -101,6 +101,31 @@ //Convert elements with "marked" class to markdown processMarked(); }); + + function findNode(id, currentNode) { + return (Object.keys(currentNode)[0] === id) ? currentNode : findNodeInChildren(id, currentNode); + } + + function findNodeInChildren(id, currentNode) { + for (let prop in currentNode) { + if (currentNode.hasOwnProperty(prop)) { + let currentChild = currentNode[prop]; + if (id === prop) { + return currentChild; + } else { + // Search in the current child + if (typeof (currentChild) === 'object') { + let result = findNode(id, currentChild); + if (result !== false) { + return result; + } + } + } + } + } + return false; + } +