diff --git a/.gitignore b/.gitignore index 55ef266102..9fd7f8b7a6 100644 --- a/.gitignore +++ b/.gitignore @@ -115,14 +115,14 @@ samples/client/petstore/swift/**/SwaggerClientTests/SwaggerClient.xcworkspace/xc samples/client/petstore/swift/**/SwaggerClientTests/Pods/ #samples/client/petstore/swift/**/SwaggerClientTests/Pods/Pods.xcodeproj/xcuserdata #samples/client/petstore/swift/**/SwaggerClientTests/Pods/Pods.xcodeproj/xcshareddata/xcschemes -samples/client/petstore/swift/**/SwaggerClientTests/Podfile.lock +samples/client/petstore/swift/**/SwaggerClientTests/Podfile.lock # Swift3 samples/client/petstore/swift3/**/SwaggerClientTests/SwaggerClient.xcodeproj/xcuserdata samples/client/petstore/swift3/**/SwaggerClientTests/SwaggerClient.xcworkspace/xcuserdata #samples/client/petstore/swift3/**/SwaggerClientTests/Pods/ #samples/client/petstore/swift3/**/SwaggerClientTests/Pods/Pods.xcodeproj/xcuserdata #samples/client/petstore/swift3/**/SwaggerClientTests/Pods/Pods.xcodeproj/xcshareddata/xcschemes -samples/client/petstore/swift3/**/SwaggerClientTests/Podfile.lock +samples/client/petstore/swift3/**/SwaggerClientTests/Podfile.lock # C# *.csproj.user diff --git a/.hub.online.dockerfile b/.hub.online.dockerfile index 96eda34d32..083b84d4ea 100644 --- a/.hub.online.dockerfile +++ b/.hub.online.dockerfile @@ -26,7 +26,7 @@ RUN mkdir -p ${TARGET_DIR} WORKDIR ${TARGET_DIR} -COPY --from=builder ${GEN_DIR}/modules/openapi-generator-online/target/openapi-generator-*.jar ${TARGET_DIR}/openapi-generator-online.jar +COPY --from=builder ${GEN_DIR}/modules/openapi-generator-online/target/openapi-generator-online.jar ${TARGET_DIR}/openapi-generator-online.jar ENV GENERATOR_HOST=http://localhost diff --git a/.travis.yml b/.travis.yml index 9d83b1a1bb..51d8c4a6b7 100644 --- a/.travis.yml +++ b/.travis.yml @@ -125,7 +125,7 @@ after_success: ./gradlew -Psigning.keyId="$SIGNING_KEY" -Psigning.password="$SIGNING_PASSPHRASE" -Psigning.secretKeyRingFile="${TRAVIS_BUILD_DIR}/sec.gpg" -PossrhUsername="${SONATYPE_USERNAME}" -PossrhPassword="${SONATYPE_PASSWORD}" uploadArchives --no-daemon; echo "Finished ./gradlew uploadArchives"; popd; - elif ([ "$TRAVIS_BRANCH" == "4.0.x" ]) ; then + elif ([[ "$TRAVIS_BRANCH" =~ ^[0-9]+\.[0-9]+\.x$ ]]) ; then mvn clean deploy --settings CI/settings.xml; echo "Finished mvn clean deploy for $TRAVIS_BRANCH"; pushd .; diff --git a/CI/pom.xml.circleci b/CI/pom.xml.circleci index dad602d9f8..919bd96143 100644 --- a/CI/pom.xml.circleci +++ b/CI/pom.xml.circleci @@ -899,6 +899,7 @@ samples/client/petstore/java/retrofit2 samples/client/petstore/java/retrofit2rx samples/client/petstore/java/retrofit2-play25 + samples/client/petstore/java/retrofit2-play26 samples/client/petstore/jaxrs-cxf-client samples/client/petstore/java/resttemplate samples/client/petstore/java/resttemplate-withXml @@ -957,6 +958,7 @@ samples/server/petstore/scala-lagom-server samples/server/petstore/scalatra samples/server/petstore/finch + samples/server/petstore/kotlin-springboot diff --git a/README.md b/README.md index ee102011cb..57aadbcb36 100644 --- a/README.md +++ b/README.md @@ -2,7 +2,7 @@
-[Master](https://github.com/OpenAPITools/openapi-generator/tree/master) (`3.2.3`): [![Build Status](https://img.shields.io/travis/OpenAPITools/openapi-generator/master.svg?label=Integration%20Test)](https://travis-ci.org/OpenAPITools/openapi-generator) +[Master](https://github.com/OpenAPITools/openapi-generator/tree/master) (`3.3.0`): [![Build Status](https://img.shields.io/travis/OpenAPITools/openapi-generator/master.svg?label=Integration%20Test)](https://travis-ci.org/OpenAPITools/openapi-generator) [![Integration Test2](https://circleci.com/gh/OpenAPITools/openapi-generator.svg?style=shield)](https://circleci.com/gh/OpenAPITools/openapi-generator) [![Run Status](https://api.shippable.com/projects/5af6bf74e790f4070084a115/badge?branch=master)](https://app.shippable.com/github/OpenAPITools/openapi-generator) [![Windows Test](https://ci.appveyor.com/api/projects/status/github/openapitools/openapi-generator?branch=master&svg=true&passingText=Windows%20Test%20-%20OK&failingText=Windows%20Test%20-%20Fails)](https://ci.appveyor.com/project/WilliamCheng/openapi-generator-wh2wu) @@ -42,8 +42,8 @@ OpenAPI Generator allows generation of API client libraries (SDK generation), se | | Languages/Frameworks | |-|-| -**API clients** | **ActionScript**, **Ada**, **Apex**, **Bash**, **C#** (.net 2.0, 3.5 or later), **C++** (cpprest, Qt5, Tizen), **Clojure**, **Dart**, **Elixir**, **Elm**, **Eiffel**, **Erlang**, **Go**, **Groovy**, **Haskell** (http-client, Servant), **Java** (Jersey1.x, Jersey2.x, OkHttp, Retrofit1.x, Retrofit2.x, Feign, RestTemplate, RESTEasy, Vertx, Google API Client Library for Java, Rest-assured), **Kotlin**, **Lua**, **Node.js** (ES5, ES6, AngularJS with Google Closure Compiler annotations, Flow types) **Objective-C**, **Perl**, **PHP**, **PowerShell**, **Python**, **R**, **Ruby**, **Rust** (rust, rust-server), **Scala** (akka, http4s, scalaz, swagger-async-httpclient), **Swift** (2.x, 3.x, 4.x), **Typescript** (AngularJS, Angular (2.x - 6.x), Aurelia, Fetch, Inversify, jQuery, Node) -**Server stubs** | **Ada**, **C#** (ASP.NET Core, NancyFx), **C++** (Pistache, Restbed), **Erlang**, **Go**, **Haskell** (Servant), **Java** (MSF4J, Spring, Undertow, JAX-RS: CDI, CXF, Inflector, RestEasy, Play Framework, [PKMST](https://github.com/ProKarma-Inc/pkmst-getting-started-examples)), **Kotlin**, **PHP** (Lumen, Slim, Silex, [Symfony](https://symfony.com/), [Zend Expressive](https://github.com/zendframework/zend-expressive)), **Python** (Flask), **NodeJS**, **Ruby** (Sinatra, Rails5), **Rust** (rust-server), **Scala** ([Finch](https://github.com/finagle/finch), [Lagom](https://github.com/lagom/lagom), Scalatra) +**API clients** | **ActionScript**, **Ada**, **Apex**, **Bash**, **C#** (.net 2.0, 3.5 or later), **C++** (cpprest, Qt5, Tizen), **Clojure**, **Dart**, **Elixir**, **Elm**, **Eiffel**, **Erlang**, **Go**, **Groovy**, **Haskell** (http-client, Servant), **Java** (Jersey1.x, Jersey2.x, OkHttp, Retrofit1.x, Retrofit2.x, Feign, RestTemplate, RESTEasy, Vertx, Google API Client Library for Java, Rest-assured, Spring 5 Web Client), **Kotlin**, **Lua**, **Node.js** (ES5, ES6, AngularJS with Google Closure Compiler annotations, Flow types) **Objective-C**, **Perl**, **PHP**, **PowerShell**, **Python**, **R**, **Ruby**, **Rust** (rust, rust-server), **Scala** (akka, http4s, scalaz, swagger-async-httpclient), **Swift** (2.x, 3.x, 4.x), **Typescript** (AngularJS, Angular (2.x - 6.x), Aurelia, Fetch, Inversify, jQuery, Node) +**Server stubs** | **Ada**, **C#** (ASP.NET Core, NancyFx), **C++** (Pistache, Restbed), **Erlang**, **Go**, **Haskell** (Servant), **Java** (MSF4J, Spring, Undertow, JAX-RS: CDI, CXF, Inflector, RestEasy, Play Framework, [PKMST](https://github.com/ProKarma-Inc/pkmst-getting-started-examples)), **Kotlin** (Spring Boot), **PHP** (Laravel, Lumen, Slim, Silex, [Symfony](https://symfony.com/), [Zend Expressive](https://github.com/zendframework/zend-expressive)), **Python** (Flask), **NodeJS**, **Ruby** (Sinatra, Rails5), **Rust** (rust-server), **Scala** ([Finch](https://github.com/finagle/finch), [Lagom](https://github.com/lagom/lagom), Scalatra) **API documentation generators** | **HTML**, **Confluence Wiki** **Configuration files** | [**Apache2**](https://httpd.apache.org/) **Others** | **JMeter** @@ -83,9 +83,8 @@ The OpenAPI Specification has undergone 3 revisions since initial creation in 20 OpenAPI Generator Version | Release Date | Notes ---------------------------- | ------------ | ----- 4.0.0 (upcoming major release) [SNAPSHOT](https://oss.sonatype.org/content/repositories/snapshots/org/openapitools/openapi-generator-cli/4.0.0-SNAPSHOT/)| TBD | Major release with breaking changes (no fallback) -3.3.0 (upcoming minor release)| TBD | Minor release (breaking changes with fallbacks) -3.2.3 (current master, upcoming patch release) [SNAPSHOT](https://oss.sonatype.org/content/repositories/snapshots/org/openapitools/openapi-generator-cli/3.2.3-SNAPSHOT/)| TBD | Bugfix release -[3.2.2](https://github.com/OpenAPITools/openapi-generator/releases/tag/v3.2.2) (latest stable release) | 22.08.2018 | Bugfix release +3.3.0 (current master, upcoming minor release) [SNAPSHOT](https://oss.sonatype.org/content/repositories/snapshots/org/openapitools/openapi-generator-cli/3.3.0-SNAPSHOT/) | 07.09.2018 | Minor release (breaking changes with fallbacks) +[3.2.3](https://github.com/OpenAPITools/openapi-generator/releases/tag/v3.2.3) (latest stable release) | 30.08.2018 | Bugfix release OpenAPI Spec compatibility: 1.0, 1.1, 1.2, 2.0, 3.0 @@ -141,16 +140,16 @@ See the different versions of the [openapi-generator-cli](https://mvnrepository. If you're looking for the latest stable version, you can grab it directly from Maven.org (Java 8 runtime at a minimum): -JAR location: `http://central.maven.org/maven2/org/openapitools/openapi-generator-cli/3.2.2/openapi-generator-cli-3.2.2.jar` +JAR location: `http://central.maven.org/maven2/org/openapitools/openapi-generator-cli/3.2.3/openapi-generator-cli-3.2.3.jar` For **Mac/Linux** users: ```sh -wget http://central.maven.org/maven2/org/openapitools/openapi-generator-cli/3.2.2/openapi-generator-cli-3.2.2.jar -O openapi-generator-cli.jar +wget http://central.maven.org/maven2/org/openapitools/openapi-generator-cli/3.2.3/openapi-generator-cli-3.2.3.jar -O openapi-generator-cli.jar ``` For **Windows** users, you will need to install [wget](http://gnuwin32.sourceforge.net/packages/wget.htm) or you can use Invoke-WebRequest in PowerShell (3.0+), e.g. ``` -Invoke-WebRequest -OutFile openapi-generator-cli.jar http://central.maven.org/maven2/org/openapitools/openapi-generator-cli/3.2.2/openapi-generator-cli-3.2.2.jar +Invoke-WebRequest -OutFile openapi-generator-cli.jar http://central.maven.org/maven2/org/openapitools/openapi-generator-cli/3.2.3/openapi-generator-cli-3.2.3.jar ``` After downloading the JAR, run `java -jar openapi-generator-cli.jar help` to show the usage. @@ -469,6 +468,7 @@ Here are some companies/projects (alphabetical order) using OpenAPI Generator in - [Angular.Schule](https://angular.schule/) - [Bithost GmbH](https://www.bithost.ch) +- [Boxever](https://www.boxever.com/) - [GMO Pepabo](https://pepabo.com/en/) - [Raiffeisen Schweiz Genossenschaft](https://www.raiffeisen.ch) - [RepreZen API Studio](https://www.reprezen.com/swagger-openapi-code-generation-api-first-microservices-enterprise-development) @@ -476,6 +476,7 @@ Here are some companies/projects (alphabetical order) using OpenAPI Generator in - [Suva](https://www.suva.ch/) - [Telstra](https://dev.telstra.com) - [unblu inc.](https://www.unblu.com/) +- [Zalando](https://www.zalando.com) ## [5 - Presentations/Videos/Tutorials/Books](#table-of-contents) @@ -576,6 +577,7 @@ Here is a list of template creators: * JAX-RS CXF (CDI): @nickcmaynard * JAX-RS RestEasy (JBoss EAP): @jfiala * Kotlin: @jimschubert + * Kotlin (Spring Boot): @dr4ke616 * PHP Laravel: @renepardon * PHP Lumen: @abcsun * PHP Slim: @jfastnacht @@ -639,7 +641,7 @@ If you want to join the committee, please kindly apply by sending an email to te | Groovy | | | Haskell | | | Java | @bbdouglas (2017/07) @JFCote (2017/08) @sreeshas (2017/08) @jfiala (2017/08) @lukoyanov (2017/09) @cbornet (2017/09) @jeff9finger (2018/01) | -| Kotlin | @jimschubert (2017/09) | +| Kotlin | @jimschubert (2017/09) @dr4ke616 (2018/08) | | Lua | @daurnimator (2017/08) | | NodeJS/Javascript | @CodeNinjai (2017/07) @frol (2017/07) @cliffano (2017/07) | | ObjC | | diff --git a/bin/java-petstore-all.sh b/bin/java-petstore-all.sh index b8cb3014e0..190bf33fa5 100755 --- a/bin/java-petstore-all.sh +++ b/bin/java-petstore-all.sh @@ -13,6 +13,7 @@ ./bin/java8-petstore-jersey2.sh ./bin/java-petstore-retrofit2-play24.sh ./bin/java-petstore-retrofit2-play25.sh +./bin/java-petstore-retrofit2-play26.sh ./bin/java-petstore-jersey2-java6.sh ./bin/java-petstore-resttemplate.sh ./bin/java-petstore-resttemplate-withxml.sh diff --git a/bin/java-petstore-retrofit2-play26.json b/bin/java-petstore-retrofit2-play26.json new file mode 100644 index 0000000000..0c7456430d --- /dev/null +++ b/bin/java-petstore-retrofit2-play26.json @@ -0,0 +1 @@ +{"useBeanValidation":"true","enableBuilderSupport":"true","library":"retrofit2","usePlayWS":"true","playVersion":"play26"} diff --git a/bin/java-petstore-retrofit2-play26.sh b/bin/java-petstore-retrofit2-play26.sh new file mode 100755 index 0000000000..326f5fa5b3 --- /dev/null +++ b/bin/java-petstore-retrofit2-play26.sh @@ -0,0 +1,35 @@ +#!/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} -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties" +ags="generate --artifact-id petstore-java-client-retrofit2-play26 -i modules/openapi-generator/src/test/resources/2_0/petstore-with-fake-endpoints-models-for-testing.yaml -g java -c bin/java-petstore-retrofit2-play26.json -o samples/client/petstore/java/retrofit2-play26 -DhideGenerationTimestamp=true $@" + +echo "Removing files and folders under samples/client/petstore/java/retrofit2-play26/src/main" +rm -rf samples/client/petstore/java/retrofit2-play26/src/main +find samples/client/petstore/java/retrofit2-play26 -maxdepth 1 -type f ! -name "README.md" -exec rm {} + +java $JAVA_OPTS -jar $executable $ags diff --git a/bin/kotlin-springboot-petstore-server.sh b/bin/kotlin-springboot-petstore-server.sh new file mode 100755 index 0000000000..7e1c3888c8 --- /dev/null +++ b/bin/kotlin-springboot-petstore-server.sh @@ -0,0 +1,35 @@ +#!/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 clean package +fi + +export JAVA_OPTS="${JAVA_OPTS} -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties" +ags="$@ generate -i modules/openapi-generator/src/test/resources/2_0/petstore.yaml -t modules/openapi-generator/src/main/resources/kotlin-spring -g kotlin-spring -o samples/server/petstore/kotlin-springboot --additional-properties=library=spring-boot,beanValidations=true,swaggerAnnotations=true,serviceImplementation=true" + +echo "Cleaning previously generated files if any from samples/server/petstore/kotlin-springboot" +rm -rf samples/server/petstore/kotlin-springboot + +echo "Generating Kotling Spring Boot server..." +java $JAVA_OPTS -jar $executable $ags diff --git a/bin/meta-codegen.sh b/bin/meta-codegen.sh index 00b6798446..2a0f55cf8a 100755 --- a/bin/meta-codegen.sh +++ b/bin/meta-codegen.sh @@ -26,11 +26,11 @@ then fi export JAVA_OPTS="${JAVA_OPTS} -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties" -ags="meta -n myClientCodegen -p com.my.company.codegen -o samples/meta-codegen/lib $@" +ags="meta -n myClientCodegen -t DOCUMENTATION -p com.my.company.codegen -o samples/meta-codegen/lib $@" java $JAVA_OPTS -jar $executable $ags -mvn verify -f samples/meta-codegen/lib/pom.xml +mvn clean package -f samples/meta-codegen/pom.xml ags2="generate -g myClientCodegen -i modules/openapi-generator/src/test/resources/2_0/petstore.json -o samples/meta-codegen/usage $@" diff --git a/bin/openapi3/jaxrs-jersey-petstore.sh b/bin/openapi3/jaxrs-jersey-petstore.sh old mode 100644 new mode 100755 diff --git a/bin/openapi3/kotlin-springboot-petstore-server.sh b/bin/openapi3/kotlin-springboot-petstore-server.sh new file mode 100755 index 0000000000..3ac7b6f68e --- /dev/null +++ b/bin/openapi3/kotlin-springboot-petstore-server.sh @@ -0,0 +1,35 @@ +#!/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 clean package +fi + +export JAVA_OPTS="${JAVA_OPTS} -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties" +ags="$@ generate -i modules/openapi-generator/src/test/resources/3_0/petstore.yaml -t modules/openapi-generator/src/main/resources/kotlin-spring -g kotlin-spring -o samples/server/openapi3/petstore/kotlin-springboot --additional-properties=library=spring-boot,beanValidations=true,swaggerAnnotations=true,serviceImplementation=true" + +echo "Cleaning previously generated files if any from samples/server/openapi3/petstore/kotlin-springboot" +rm -rf samples/server/openapi3/petstore/kotlin-springboot + +echo "Generating Kotling Spring Boot server..." +java $JAVA_OPTS -jar $executable $ags diff --git a/bin/tests/run-all-test b/bin/tests/run-all-test new file mode 100755 index 0000000000..963f0d2ec6 --- /dev/null +++ b/bin/tests/run-all-test @@ -0,0 +1,33 @@ +#!/bin/bash +# this bash script will loop through all the .sh files under bin/tests +# execute the script and check the result (exit code) to see if +# there's any error + +echo "IMPORTANT: this script should be run by the CI (e.g. Shippable) only. There's no need to run this script manually." +echo "Please press CTRL+C to stop or the script will continue in 10 seconds." + +sleep 10 + +successes=0 +failures=0 +for SCRIPT in $(ls -l ./bin/tests/*.sh | grep -v all) +do + if [ -f ${SCRIPT} -a -x ${SCRIPT} ]; then + echo "Running $SCRIPT (output to /dev/null)" + ${SCRIPT} 2>&1 > /dev/null + rc=$? + if [[ ${rc} != 0 ]]; then + >&2 echo "ERROR!! FAILED TO RUN ${SCRIPT}" + ((failures+=1)) + else + ((successes+=1)) + fi + fi +done + +if (( failures > 0 )); then + >&2 echo "[ERROR] ${failures} out of $((failures+successes)) scripts failed." + exit 1 +else + echo "[SUCCESS] ${successes} generators finished." +fi diff --git a/bin/tests/test-debug-supporting-files.sh b/bin/tests/test-debug-supporting-files.sh new file mode 100755 index 0000000000..7360313f5c --- /dev/null +++ b/bin/tests/test-debug-supporting-files.sh @@ -0,0 +1,38 @@ +#!/bin/bash + +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} -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties" +ags="generate -t modules/openapi-generator/src/main/resources/python -i modules/openapi-generator/src/test/resources/3_0/issue_241.yaml -g python -o /tmp/test-debug-supporting-files/ -DpackageName=petstore_api -DdebugSupportingFiles=true $@" + +if [[ $(java $JAVA_OPTS -jar $executable $ags 2>&1 | grep "StackOverflowError") ]]; then + echo "There are StackOverflowError. Please check the result." + exit 1 +else + echo "No StackOverflowError found." +fi + diff --git a/bin/utils/ensure-up-to-date b/bin/utils/ensure-up-to-date index 6e2fd3a1ec..e29fed7643 100755 --- a/bin/utils/ensure-up-to-date +++ b/bin/utils/ensure-up-to-date @@ -32,6 +32,7 @@ sleep 5 ./bin/rust-server-petstore.sh > /dev/null 2>&1 ./bin/openapi3/haskell-http-client-petstore.sh > /dev/null 2>&1 ./bin/csharp-petstore.sh > /dev/null 2>&1 +./bin/meta-codegen.sh > /dev/null 2>&1 # Check: if [ -n "$(git status --porcelain)" ]; then diff --git a/bin/utils/release_version_update.sh b/bin/utils/release_version_update.sh index 6b91d2b15f..bdc155fd43 100755 --- a/bin/utils/release_version_update.sh +++ b/bin/utils/release_version_update.sh @@ -45,7 +45,7 @@ declare -a files=("CI/pom.xml.bash" "modules/openapi-generator-maven-plugin/pom.xml" "modules/openapi-generator-online/pom.xml" "modules/openapi-generator/pom.xml" - "modules/openapi-generator-online/Dockerfile" + "samples/meta-codegen/lib/pom.xml" "pom.xml") for filename in "${files[@]}"; do diff --git a/bin/windows/kotlin-springboot-petstore-server.bat b/bin/windows/kotlin-springboot-petstore-server.bat new file mode 100644 index 0000000000..6b7e1ad6e7 --- /dev/null +++ b/bin/windows/kotlin-springboot-petstore-server.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\petstore.yaml -g kotlin-spring -o samples\server\petstore\kotlin-springboot --additional-properties=library=spring-boot + +java %JAVA_OPTS% -jar %executable% %ags% diff --git a/bin/windows/openapi3/kotlin-springboot-petstore-server.bat b/bin/windows/openapi3/kotlin-springboot-petstore-server.bat new file mode 100644 index 0000000000..c86efaee3c --- /dev/null +++ b/bin/windows/openapi3/kotlin-springboot-petstore-server.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\3_0\petstore.yaml -g kotlin-spring -o samples\server\openapi3\petstore\kotlin-springboot --additional-properties=library=spring-boot + +java %JAVA_OPTS% -jar %executable% %ags% 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 edd85ff79a..83a3ada42c 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 @@ -1,7 +1,10 @@ package org.openapitools.codegen.cmd; +import com.google.common.base.Objects; + import io.airlift.airline.Command; import io.airlift.airline.Option; + import org.openapitools.codegen.CodegenConfig; import org.openapitools.codegen.CodegenConfigLoader; import org.openapitools.codegen.CodegenType; @@ -10,6 +13,7 @@ import java.util.Arrays; import java.util.Comparator; import java.util.List; import java.util.Locale; +import java.util.stream.Collectors; // NOTE: List can later have subcommands such as list languages, list types, list frameworks, etc. @Command(name = "list", description = "Lists the available generators") @@ -41,19 +45,29 @@ public class ListGenerators implements Runnable { sb.append(System.lineSeparator()); for (CodegenType type : types) { - sb.append(type.name()).append(" generators:"); - sb.append(System.lineSeparator()); - - generators.stream() - .filter(g -> g.getTag().equals(type)) - .sorted(Comparator.comparing(CodegenConfig::getName)) - .forEach(generator -> sb.append(" - ").append(generator.getName()).append(System.lineSeparator())); - - sb.append(System.lineSeparator()); - sb.append(System.lineSeparator()); + appendForType(sb, type, type.name(), generators); } + appendForType(sb, null, "UNSPECIFIED", generators); } - System.out.printf(Locale.ROOT,"%s%n", sb.toString()); + System.out.printf(Locale.ROOT, "%s%n", sb.toString()); + } + + private void appendForType(StringBuilder sb, CodegenType type, String typeName, List generators) { + List list = generators.stream() + .filter(g -> Objects.equal(type, g.getTag())) + .sorted(Comparator.comparing(CodegenConfig::getName)) + .collect(Collectors.toList()); + + if(list.size() > 0) { + sb.append(typeName).append(" generators:"); + sb.append(System.lineSeparator()); + + list.stream() + .forEach(generator -> sb.append(" - ").append(generator.getName()).append(System.lineSeparator())); + + sb.append(System.lineSeparator()); + sb.append(System.lineSeparator()); + } } } 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 1865550ca9..c373aaa8c7 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 @@ -67,6 +67,11 @@ public class Meta implements Runnable { description = "the package to put the main class into (defaults to org.openapitools.codegen)") private String targetPackage = "org.openapitools.codegen"; + @Option(name = {"-t", "--type"}, title = "type", + description = "the type of generator that is created", + allowedValues = {"CLIENT", "SERVER", "DOCUMENTATION", "CONFIG", "OTHER"}) + private String type = "OTHER"; + @Override public void run() { final File targetDir = new File(outputFolder); @@ -87,8 +92,11 @@ public class Meta implements Runnable { String currentVersion = Version.readVersionFromResources(); Map data = - new ImmutableMap.Builder().put("generatorPackage", targetPackage) - .put("generatorClass", mainClass).put("name", name) + new ImmutableMap.Builder() + .put("generatorPackage", targetPackage) + .put("generatorClass", mainClass) + .put("name", name) + .put("generatorType", type) .put("fullyQualifiedGeneratorClass", targetPackage + "." + mainClass) .put("openapiGeneratorVersion", currentVersion).build(); diff --git a/modules/openapi-generator-gradle-plugin/README.adoc b/modules/openapi-generator-gradle-plugin/README.adoc index c1fb0d0b8d..0a57f093d3 100644 --- a/modules/openapi-generator-gradle-plugin/README.adoc +++ b/modules/openapi-generator-gradle-plugin/README.adoc @@ -48,7 +48,7 @@ buildscript { mavenCentral() } dependencies { - classpath "org.openapitools:openapi-generator-gradle-plugin:3.2.2" + classpath "org.openapitools:openapi-generator-gradle-plugin:3.2.3" } } diff --git a/modules/openapi-generator-gradle-plugin/samples/local-spec/README.md b/modules/openapi-generator-gradle-plugin/samples/local-spec/README.md index 13889d521b..c55e8814d8 100644 --- a/modules/openapi-generator-gradle-plugin/samples/local-spec/README.md +++ b/modules/openapi-generator-gradle-plugin/samples/local-spec/README.md @@ -17,5 +17,5 @@ gradle generateGoWithInvalidSpec The samples can be tested against other versions of the plugin using the `openApiGeneratorVersion` property. For example: ```bash -gradle -PopenApiGeneratorVersion=3.2.2 openApiValidate +gradle -PopenApiGeneratorVersion=3.2.3 openApiValidate ``` diff --git a/modules/openapi-generator-gradle-plugin/samples/local-spec/gradle.properties b/modules/openapi-generator-gradle-plugin/samples/local-spec/gradle.properties index ed174a94c4..8d4fd89659 100644 --- a/modules/openapi-generator-gradle-plugin/samples/local-spec/gradle.properties +++ b/modules/openapi-generator-gradle-plugin/samples/local-spec/gradle.properties @@ -1 +1 @@ -openApiGeneratorVersion=3.2.2 +openApiGeneratorVersion=3.2.3 diff --git a/modules/openapi-generator-maven-plugin/README.md b/modules/openapi-generator-maven-plugin/README.md index 299ebbab34..6d07d84409 100644 --- a/modules/openapi-generator-maven-plugin/README.md +++ b/modules/openapi-generator-maven-plugin/README.md @@ -11,7 +11,7 @@ Add to your `build->plugins` section (default phase is `generate-sources` phase) org.openapitools openapi-generator-maven-plugin - 3.2.2 + 3.2.3 diff --git a/modules/openapi-generator-maven-plugin/examples/java-client.xml b/modules/openapi-generator-maven-plugin/examples/java-client.xml index 05b285d9ce..980ef56420 100644 --- a/modules/openapi-generator-maven-plugin/examples/java-client.xml +++ b/modules/openapi-generator-maven-plugin/examples/java-client.xml @@ -12,7 +12,7 @@ org.openapitools openapi-generator-maven-plugin - 3.2.2 + 3.2.3 diff --git a/modules/openapi-generator-maven-plugin/examples/non-java-invalid-spec.xml b/modules/openapi-generator-maven-plugin/examples/non-java-invalid-spec.xml index 35e5ce02e4..d47a5b0899 100644 --- a/modules/openapi-generator-maven-plugin/examples/non-java-invalid-spec.xml +++ b/modules/openapi-generator-maven-plugin/examples/non-java-invalid-spec.xml @@ -12,7 +12,7 @@ org.openapitools openapi-generator-maven-plugin - 3.2.2 + 3.2.3 diff --git a/modules/openapi-generator-maven-plugin/examples/non-java.xml b/modules/openapi-generator-maven-plugin/examples/non-java.xml index eece8d6efb..919b933e9f 100644 --- a/modules/openapi-generator-maven-plugin/examples/non-java.xml +++ b/modules/openapi-generator-maven-plugin/examples/non-java.xml @@ -12,7 +12,7 @@ org.openapitools openapi-generator-maven-plugin - 3.2.2 + 3.2.3 diff --git a/modules/openapi-generator-online/pom.xml b/modules/openapi-generator-online/pom.xml index 055890b3bb..d82da7bbc2 100644 --- a/modules/openapi-generator-online/pom.xml +++ b/modules/openapi-generator-online/pom.xml @@ -27,6 +27,7 @@ + openapi-generator-online src/main/java diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/CodegenCallback.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/CodegenCallback.java new file mode 100644 index 0000000000..3dcf7cfbea --- /dev/null +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/CodegenCallback.java @@ -0,0 +1,80 @@ +/* + * Copyright 2018 OpenAPI-Generator Contributors (https://openapi-generator.tech) + * Copyright 2018 SmartBear Software + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.openapitools.codegen; + +import java.util.*; + +public class CodegenCallback { + public String name; + public boolean hasMore; + public List urls = new ArrayList<>(); + public Map vendorExtensions = new HashMap<>(); + + public static class Url { + public String expression; + public boolean hasMore; + public List requests = new ArrayList<>(); + public Map vendorExtensions = new HashMap<>(); + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + + Url that = (Url) o; + return Objects.equals(that.expression, expression) && Objects.equals(that.hasMore, hasMore) && + Objects.equals(that.requests, requests) && Objects.equals(that.vendorExtensions, vendorExtensions); + } + @Override + public int hashCode() { + return Objects.hash(expression, hasMore, requests, vendorExtensions); + } + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("CodegenCallback.Urls {\n"); + sb.append(" expression: ").append(expression).append("\n"); + requests.forEach(r -> sb.append(" ").append(r).append("\n")); + sb.append("}"); + return sb.toString(); + } + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + + CodegenCallback that = (CodegenCallback) o; + return Objects.equals(that.name, name) && Objects.equals(that.hasMore, hasMore) && + Objects.equals(that.urls, urls) && Objects.equals(that.vendorExtensions, vendorExtensions); + } + @Override + public int hashCode() { + return Objects.hash(name, hasMore, urls, vendorExtensions); + } + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("CodegenCallback {\n"); + sb.append(" name: ").append(name).append("\n"); + urls.forEach(u -> sb.append(" ").append(u).append("\n")); + sb.append("}"); + return sb.toString(); + } +} 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 80ff121c36..8251bb2231 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 @@ -28,6 +28,9 @@ import java.util.Objects; import java.util.Set; import java.util.TreeSet; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; + +@JsonIgnoreProperties({"parentModel", "interfaceModels"}) public class CodegenModel { public String parent, parentSchema; public List interfaces; diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/CodegenOperation.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/CodegenOperation.java index 1e66e45ede..acc15ba321 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/CodegenOperation.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/CodegenOperation.java @@ -36,7 +36,7 @@ public class CodegenOperation { isListContainer, isMultipart, hasMore = true, isResponseBinary = false, isResponseFile = false, hasReference = false, isRestfulIndex, isRestfulShow, isRestfulCreate, isRestfulUpdate, isRestfulDestroy, - isRestful, isDeprecated; + isRestful, isDeprecated, isCallbackRequest; public String path, operationId, returnType, httpMethod, returnBaseType, returnContainer, summary, unescapedNotes, notes, baseName, defaultResponse; public CodegenDiscriminator discriminator; @@ -54,6 +54,7 @@ public class CodegenOperation { public List authMethods; public List tags; public List responses = new ArrayList(); + public List callbacks = new ArrayList<>(); public Set imports = new HashSet(); public List> examples; public List> requestBodyExamples; @@ -293,6 +294,8 @@ public class CodegenOperation { return false; if (isDeprecated != that.isDeprecated) return false; + if (isCallbackRequest != that.isCallbackRequest) + return false; if (path != null ? !path.equals(that.path) : that.path != null) return false; if (operationId != null ? !operationId.equals(that.operationId) : that.operationId != null) @@ -347,6 +350,8 @@ public class CodegenOperation { return false; if (responses != null ? !responses.equals(that.responses) : that.responses != null) return false; + if (callbacks != null ? !callbacks.equals(that.callbacks) : that.callbacks != null) + return false; if (imports != null ? !imports.equals(that.imports) : that.imports != null) return false; if (examples != null ? !examples.equals(that.examples) : that.examples != null) @@ -386,6 +391,7 @@ public class CodegenOperation { result = 31 * result + (isResponseFile ? 13:31); result = 31 * result + (hasReference ? 13:31); result = 31 * result + (isDeprecated ? 13:31); + result = 31 * result + (isCallbackRequest ? 13:31); result = 31 * result + (path != null ? path.hashCode() : 0); result = 31 * result + (operationId != null ? operationId.hashCode() : 0); result = 31 * result + (returnType != null ? returnType.hashCode() : 0); @@ -413,6 +419,7 @@ public class CodegenOperation { result = 31 * result + (authMethods != null ? authMethods.hashCode() : 0); result = 31 * result + (tags != null ? tags.hashCode() : 0); result = 31 * result + (responses != null ? responses.hashCode() : 0); + result = 31 * result + (callbacks != null ? callbacks.hashCode() : 0); result = 31 * result + (imports != null ? imports.hashCode() : 0); result = 31 * result + (examples != null ? examples.hashCode() : 0); result = 31 * result + (externalDocs != null ? externalDocs.hashCode() : 0); 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 eb6522a931..d290aa5c6a 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 @@ -41,6 +41,7 @@ public class CodegenParameter { public CodegenProperty mostInnerItems; public Map vendorExtensions = new HashMap(); public boolean hasValidation; + public boolean isNullable; /** * Determines whether this parameter is mandatory. If the parameter is in "path", @@ -150,6 +151,7 @@ public class CodegenParameter { output.vendorExtensions = new HashMap(this.vendorExtensions); } output.hasValidation = this.hasValidation; + output.isNullable = this.isNullable; output.isBinary = this.isBinary; output.isByteArray = this.isByteArray; output.isString = this.isString; @@ -269,6 +271,8 @@ public class CodegenParameter { return false; if (hasValidation != that.hasValidation) return false; + if (isNullable != that.isNullable) + return false; if (required != that.required) return false; if (maximum != null ? !maximum.equals(that.maximum) : that.maximum != null) @@ -344,6 +348,7 @@ public class CodegenParameter { result = 31 * result + (mostInnerItems != null ? mostInnerItems.hashCode() : 0); result = 31 * result + (vendorExtensions != null ? vendorExtensions.hashCode() : 0); result = 31 * result + (hasValidation ? 13:31); + result = 31 * result + (isNullable ? 13:31); result = 31 * result + (required ? 13:31); result = 31 * result + (maximum != null ? maximum.hashCode() : 0); result = 31 * result + (exclusiveMaximum ? 13:31); @@ -409,6 +414,7 @@ public class CodegenParameter { ", mostInnerItems=" + mostInnerItems + ", vendorExtensions=" + vendorExtensions + ", hasValidation=" + hasValidation + + ", isNullable=" + isNullable + ", required=" + required + ", maximum='" + maximum + '\'' + ", exclusiveMaximum=" + exclusiveMaximum + 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 61d1ae8315..c7adcd0b36 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 @@ -24,6 +24,7 @@ import com.samskivert.mustache.Mustache.Compiler; import io.swagger.v3.core.util.Json; import io.swagger.v3.oas.models.OpenAPI; import io.swagger.v3.oas.models.Operation; +import io.swagger.v3.oas.models.callbacks.Callback; import io.swagger.v3.oas.models.examples.Example; import io.swagger.v3.oas.models.headers.Header; import io.swagger.v3.oas.models.media.ArraySchema; @@ -50,6 +51,7 @@ import io.swagger.v3.parser.util.SchemaTypeUtil; import org.apache.commons.lang3.ObjectUtils; import org.apache.commons.lang3.StringEscapeUtils; import org.apache.commons.lang3.StringUtils; +import org.apache.commons.lang3.tuple.Pair; import org.openapitools.codegen.CodegenDiscriminator.MappedModel; import org.openapitools.codegen.examples.ExampleGenerator; import org.openapitools.codegen.serializer.SerializerUtils; @@ -76,6 +78,11 @@ import java.util.TreeSet; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.stream.Collectors; +import java.util.stream.Stream; + +import static org.openapitools.codegen.utils.StringUtils.camelize; +import static org.openapitools.codegen.utils.StringUtils.underscore; +import static org.openapitools.codegen.utils.StringUtils.escape; public class DefaultCodegen implements CodegenConfig { private static final Logger LOGGER = LoggerFactory.getLogger(DefaultCodegen.class); @@ -284,6 +291,8 @@ public class DefaultCodegen implements CodegenConfig { enumVar.put("isString", isDataTypeString(cm.dataType)); enumVars.add(enumVar); } + // if "x-enum-varnames" defined, update varnames + updateEnumVarsWithExtensions(enumVars, cm.getVendorExtensions()); cm.allowableValues.put("enumVars", enumVars); } @@ -772,7 +781,7 @@ public class DefaultCodegen implements CodegenConfig { if (reservedWords.contains(name)) { return escapeReservedWord(name); } else if (((CharSequence) name).chars().anyMatch(character -> specialCharReplacements.keySet().contains("" + ((char) character)))) { - return escapeSpecialCharacters(name, null, null); + return escape(name, specialCharReplacements, null, null); } else { return name; } @@ -790,7 +799,7 @@ public class DefaultCodegen implements CodegenConfig { if (reservedWords.contains(name)) { return escapeReservedWord(name); } else if (((CharSequence) name).chars().anyMatch(character -> specialCharReplacements.keySet().contains("" + ((char) character)))) { - return escapeSpecialCharacters(name, null, null); + return escape(name, specialCharReplacements, null, null); } return name; } @@ -832,27 +841,19 @@ public class DefaultCodegen implements CodegenConfig { /** * Return the name with escaped characters. * - * @param name the name to be escaped - * @param charactersToAllow characters that are not escaped + * @param name the name to be escaped + * @param charactersToAllow characters that are not escaped * @param appdendixToReplacement String to append to replaced characters. * @return the escaped word *

* throws Runtime exception as word is not escaped properly. + * @deprecated since version 3.2.3, may be removed with the next major release (4.0) + * @see org.openapitools.codegen.utils.StringUtils#escape directly instead + * */ + @Deprecated public String escapeSpecialCharacters(String name, List charactersToAllow, String appdendixToReplacement) { - String result = (String) ((CharSequence) name).chars().mapToObj(c -> { - String character = "" + (char) c; - if (charactersToAllow != null && charactersToAllow.contains(character)) { - return character; - } else if (specialCharReplacements.containsKey(character)) { - return specialCharReplacements.get(character) + (appdendixToReplacement != null ? appdendixToReplacement : ""); - } else { - return character; - } - }).reduce((c1, c2) -> "" + c1 + c2).orElse(null); - - if (result != null) return result; - throw new RuntimeException("Word '" + name + "' could not be escaped."); + return escape(name, specialCharReplacements, charactersToAllow, appdendixToReplacement); } /** @@ -1750,7 +1751,7 @@ public class DefaultCodegen implements CodegenConfig { if (name == null || name.length() == 0) { return name; } - return camelize(toVarName(name)); + return org.openapitools.codegen.utils.StringUtils.camelize(toVarName(name)); } /** @@ -1769,7 +1770,7 @@ public class DefaultCodegen implements CodegenConfig { CodegenProperty property = CodegenModelFactory.newInstance(CodegenModelType.PROPERTY); property.name = toVarName(name); property.baseName = name; - property.nameInCamelCase = camelize(property.name, false); + property.nameInCamelCase = org.openapitools.codegen.utils.StringUtils.camelize(property.name, false); property.nameInSnakeCase = CaseFormat.UPPER_CAMEL.to(CaseFormat.UPPER_UNDERSCORE, property.nameInCamelCase); property.description = escapeText(p.getDescription()); property.unescapedDescription = p.getDescription(); @@ -2228,14 +2229,17 @@ public class DefaultCodegen implements CodegenConfig { Map schemas, OpenAPI openAPI) { LOGGER.debug("fromOperation => operation: " + operation); + if (operation == null) + throw new RuntimeException("operation cannot be null in fromOperation"); + CodegenOperation op = CodegenModelFactory.newInstance(CodegenModelType.OPERATION); Set imports = new HashSet(); if (operation.getExtensions() != null && !operation.getExtensions().isEmpty()) { op.vendorExtensions.putAll(operation.getExtensions()); - } - if (operation == null) - throw new RuntimeException("operation cannot be null in fromOperation"); + Object isCallbackRequest = op.vendorExtensions.remove("x-callback-request"); + op.isCallbackRequest = Boolean.TRUE.equals(isCallbackRequest); + } // store the original operationId for plug-in op.operationIdOriginal = operation.getOperationId(); @@ -2249,6 +2253,7 @@ public class DefaultCodegen implements CodegenConfig { } } operationId = removeNonNameElementToCamelCase(operationId); + op.path = path; op.operationId = toOperationId(operationId); op.summary = escapeText(operation.getSummary()); @@ -2340,6 +2345,15 @@ public class DefaultCodegen implements CodegenConfig { } } + if (operation.getCallbacks() != null && !operation.getCallbacks().isEmpty()) { + operation.getCallbacks().forEach((name, callback) -> { + CodegenCallback c = fromCallback(name, callback, schemas, openAPI); + c.hasMore = true; + op.callbacks.add(c); + }); + op.callbacks.get(op.callbacks.size() - 1).hasMore = false; + } + List parameters = operation.getParameters(); List allParams = new ArrayList(); List bodyParams = new ArrayList(); @@ -2617,6 +2631,79 @@ public class DefaultCodegen implements CodegenConfig { return r; } + /** + * Convert OAS Callback object to Codegen Callback object + * + * @param name callback name + * @param callback OAS Callback object + * @param schemas a map of OAS models + * @param openAPI a OAS object representing the spec + * @return Codegen Response object + */ + public CodegenCallback fromCallback(String name, Callback callback, Map schemas, OpenAPI openAPI) { + CodegenCallback c = new CodegenCallback(); + c.name = name; + + if (callback.getExtensions() != null && !callback.getExtensions().isEmpty()) { + c.vendorExtensions.putAll(callback.getExtensions()); + } + + callback.forEach((expression, pi) -> { + CodegenCallback.Url u = new CodegenCallback.Url(); + u.expression = expression; + u.hasMore = true; + + if (pi.getExtensions() != null && !pi.getExtensions().isEmpty()) { + u.vendorExtensions.putAll(pi.getExtensions()); + } + + Stream.of( + Pair.of("get", pi.getGet()), + Pair.of("head", pi.getHead()), + Pair.of("put", pi.getPut()), + Pair.of("post", pi.getPost()), + Pair.of("delete", pi.getDelete()), + Pair.of("patch", pi.getPatch()), + Pair.of("options", pi.getOptions())) + .filter(p -> p.getValue() != null) + .forEach(p -> { + String method = p.getKey(); + Operation op = p.getValue(); + + boolean genId = op.getOperationId() == null; + if (genId) { + op.setOperationId(getOrGenerateOperationId(op, c.name+"_"+expression.replaceAll("\\{\\$.*}", ""), method)); + } + + if (op.getExtensions() == null) { + op.setExtensions(new HashMap<>()); + } + // This extension will be removed later by `fromOperation()` as it is only needed here to + // distinguish between normal operations and callback requests + op.getExtensions().put("x-callback-request", true); + + CodegenOperation co = fromOperation(expression, method, op, schemas, openAPI); + if (genId) { + co.operationIdOriginal = null; + // legacy (see `fromOperation()`) + co.nickname = co.operationId; + } + u.requests.add(co); + }); + + if (!u.requests.isEmpty()) { + u.requests.get(u.requests.size() - 1).hasMore = false; + } + c.urls.add(u); + }); + + if (!c.urls.isEmpty()) { + c.urls.get(c.urls.size() - 1).hasMore = false; + } + + return c; + } + /** * Convert OAS Parameter object to Codegen Parameter object * @@ -2649,6 +2736,11 @@ public class DefaultCodegen implements CodegenConfig { LOGGER.warn("warning! Schema not found for parameter \"" + parameter.getName() + "\", using String"); parameterSchema = new StringSchema().description("//TODO automatically added by openapi-generator due to missing type definition."); } + + if (Boolean.TRUE.equals(parameterSchema.getNullable())) { // use nullable defined in the spec + codegenParameter.isNullable = true; + } + // set default value if (parameterSchema.getDefault() != null) { codegenParameter.defaultValue = toDefaultValue(parameterSchema); @@ -3139,8 +3231,8 @@ public class DefaultCodegen implements CodegenConfig { } co.operationId = uniqueName; co.operationIdLowerCase = uniqueName.toLowerCase(Locale.ROOT); - co.operationIdCamelCase = DefaultCodegen.camelize(uniqueName); - co.operationIdSnakeCase = DefaultCodegen.underscore(uniqueName); + co.operationIdCamelCase = org.openapitools.codegen.utils.StringUtils.camelize(uniqueName); + co.operationIdSnakeCase = org.openapitools.codegen.utils.StringUtils.underscore(uniqueName); opList.add(co); co.baseName = tag; } @@ -3169,23 +3261,12 @@ public class DefaultCodegen implements CodegenConfig { * * @param word The word * @return The underscored version of the word + * @deprecated since version 3.2.3, may be removed with the next major release (4.0) + * @see org.openapitools.codegen.utils.StringUtils#underscore */ + @Deprecated public static String underscore(String word) { - String firstPattern = "([A-Z]+)([A-Z][a-z])"; - String secondPattern = "([a-z\\d])([A-Z])"; - String replacementPattern = "$1_$2"; - // Replace package separator with slash. - word = word.replaceAll("\\.", "/"); // FIXME: a parameter should not be assigned. Also declare the methods parameters as 'final'. - // Replace $ with two underscores for inner classes. - word = word.replaceAll("\\$", "__"); - // Replace capital letter with _ plus lowercase letter. - word = word.replaceAll(firstPattern, replacementPattern); - word = word.replaceAll(secondPattern, replacementPattern); - word = word.replace('-', '_'); - // replace space with underscore - word = word.replace(' ', '_'); - word = word.toLowerCase(Locale.ROOT); - return word; + return org.openapitools.codegen.utils.StringUtils.underscore(word); } /** @@ -3193,10 +3274,13 @@ public class DefaultCodegen implements CodegenConfig { * * @param word The word * @return The dashized version of the word, e.g. "my-name" + * @deprecated since version 3.2.3, may be removed with the next major release (4.0) + * @see org.openapitools.codegen.utils.StringUtils#dashize */ @SuppressWarnings("static-method") + @Deprecated protected String dashize(String word) { - return underscore(word).replaceAll("[_ ]", "-"); + return org.openapitools.codegen.utils.StringUtils.dashize(word); } /** @@ -3396,6 +3480,7 @@ public class DefaultCodegen implements CodegenConfig { return result; } + /** * Camelize name (parameter, property, method, etc) with upper case for first letter * copied from Twitter elephant bird @@ -3403,9 +3488,12 @@ public class DefaultCodegen implements CodegenConfig { * * @param word string to be camelize * @return camelized string + * @deprecated since version 3.2.3, may be removed with the next major release (4.0) + * @see org.openapitools.codegen.utils.StringUtils#camelize(String) */ + @Deprecated public static String camelize(String word) { - return camelize(word, false); + return org.openapitools.codegen.utils.StringUtils.camelize(word); } /** @@ -3414,80 +3502,15 @@ public class DefaultCodegen implements CodegenConfig { * @param word string to be camelize * @param lowercaseFirstLetter lower case for first letter if set to true * @return camelized string + * @deprecated since version 3.2.3, may be removed with the next major release (4.0) + * @see org.openapitools.codegen.utils.StringUtils#camelize(String, boolean) */ + @Deprecated public static String camelize(String word, boolean lowercaseFirstLetter) { - // Replace all slashes with dots (package separator) - Pattern p = Pattern.compile("\\/(.?)"); - Matcher m = p.matcher(word); - while (m.find()) { - word = m.replaceFirst("." + m.group(1)/*.toUpperCase(Locale.ROOT)*/); // FIXME: a parameter should not be assigned. Also declare the methods parameters as 'final'. - m = p.matcher(word); - } - - // case out dots - String[] parts = word.split("\\."); - StringBuilder f = new StringBuilder(); - for (String z : parts) { - if (z.length() > 0) { - f.append(Character.toUpperCase(z.charAt(0))).append(z.substring(1)); - } - } - word = f.toString(); - - m = p.matcher(word); - while (m.find()) { - word = m.replaceFirst("" + Character.toUpperCase(m.group(1).charAt(0)) + m.group(1).substring(1)/*.toUpperCase(Locale.ROOT)*/); - m = p.matcher(word); - } - - // Uppercase the class name. - p = Pattern.compile("(\\.?)(\\w)([^\\.]*)$"); - m = p.matcher(word); - if (m.find()) { - String rep = m.group(1) + m.group(2).toUpperCase(Locale.ROOT) + m.group(3); - rep = rep.replaceAll("\\$", "\\\\\\$"); - word = m.replaceAll(rep); - } - - // Remove all underscores (underscore_case to camelCase) - p = Pattern.compile("(_)(.)"); - m = p.matcher(word); - while (m.find()) { - String original = m.group(2); - String upperCase = original.toUpperCase(Locale.ROOT); - if (original.equals(upperCase)) { - word = word.replaceFirst("_", ""); - } else { - word = m.replaceFirst(upperCase); - } - m = p.matcher(word); - } - - // Remove all hyphens (hyphen-case to camelCase) - p = Pattern.compile("(-)(.)"); - m = p.matcher(word); - while (m.find()) { - word = m.replaceFirst(m.group(2).toUpperCase(Locale.ROOT)); - m = p.matcher(word); - } - - if (lowercaseFirstLetter && word.length() > 0) { - int i = 0; - char charAt = word.charAt(i); - while (i + 1 < word.length() && !((charAt >= 'a' && charAt <= 'z') || (charAt >= 'A' && charAt <= 'Z'))) { - i = i + 1; - charAt = word.charAt(i); - } - i = i + 1; - word = word.substring(0, i).toLowerCase(Locale.ROOT) + word.substring(i); - } - - // remove all underscore - word = word.replaceAll("_", ""); - - return word; + return org.openapitools.codegen.utils.StringUtils.camelize(word, lowercaseFirstLetter); } + public String apiFilename(String templateName, String tag) { String suffix = apiTemplateFiles().get(templateName); return apiFileFolder() + File.separator + toApiFilename(tag) + suffix; @@ -3902,6 +3925,8 @@ public class DefaultCodegen implements CodegenConfig { enumVar.put("isString", isDataTypeString(dataType)); enumVars.add(enumVar); } + // if "x-enum-varnames" defined, update varnames + updateEnumVarsWithExtensions(enumVars, var.getVendorExtensions()); allowableValues.put("enumVars", enumVars); // handle default value for enum, e.g. available => StatusEnum.AVAILABLE @@ -3919,6 +3944,16 @@ public class DefaultCodegen implements CodegenConfig { } } + private void updateEnumVarsWithExtensions(List> enumVars, Map vendorExtensions) { + if (vendorExtensions != null && vendorExtensions.containsKey("x-enum-varnames")) { + List alias = (List) vendorExtensions.get("x-enum-varnames"); + int size = Math.min(enumVars.size(), alias.size()); + for (int i = 0; i < size; i++) { + enumVars.get(i).put("name", alias.get(i)); + } + } + } + /** * If the pattern misses the delimiter, add "/" to the beginning and end * Otherwise, return the original pattern @@ -4265,6 +4300,9 @@ public class DefaultCodegen implements CodegenConfig { // default to csv: codegenParameter.collectionFormat = StringUtils.isEmpty(collectionFormat) ? "csv" : collectionFormat; + // set nullable + setParameterNullable(codegenParameter, codegenProperty); + // recursively add import while (codegenProperty != null) { imports.add(codegenProperty.baseType); @@ -4293,7 +4331,7 @@ public class DefaultCodegen implements CodegenConfig { public CodegenParameter fromFormProperty(String name, Schema propertySchema, Set imports) { CodegenParameter codegenParameter = CodegenModelFactory.newInstance(CodegenModelType.PARAMETER); - LOGGER.debug("Debugging fromFormProperty: " + name); + LOGGER.debug("Debugging fromFormProperty {}: {}", name, propertySchema); CodegenProperty codegenProperty = fromProperty(name, propertySchema); codegenParameter.isFormParam = Boolean.TRUE; @@ -4307,7 +4345,6 @@ public class DefaultCodegen implements CodegenConfig { codegenParameter.jsonSchema = Json.pretty(propertySchema); codegenParameter.defaultValue = codegenProperty.getDefaultValue(); - if (codegenProperty.getVendorExtensions() != null && !codegenProperty.getVendorExtensions().isEmpty()) { codegenParameter.vendorExtensions = codegenProperty.getVendorExtensions(); } @@ -4366,6 +4403,8 @@ public class DefaultCodegen implements CodegenConfig { setParameterBooleanFlagWithCodegenProperty(codegenParameter, codegenProperty); setParameterExampleValue(codegenParameter); + // set nullable + setParameterNullable(codegenParameter, codegenProperty); //TODO collectionFormat for form parameter not yet supported //codegenParameter.collectionFormat = getCollectionFormat(propertySchema); @@ -4415,6 +4454,9 @@ public class DefaultCodegen implements CodegenConfig { codegenParameter.isMapContainer = Boolean.TRUE; setParameterBooleanFlagWithCodegenProperty(codegenParameter, codegenProperty); + + // set nullable + setParameterNullable(codegenParameter, codegenProperty); } else if (ModelUtils.isArraySchema(schema)) { final ArraySchema arraySchema = (ArraySchema) schema; Schema inner = arraySchema.getItems(); @@ -4454,6 +4496,8 @@ public class DefaultCodegen implements CodegenConfig { codegenParameter.isListContainer = Boolean.TRUE; setParameterBooleanFlagWithCodegenProperty(codegenParameter, codegenProperty); + // set nullable + setParameterNullable(codegenParameter, codegenProperty); while (codegenProperty != null) { imports.add(codegenProperty.baseType); @@ -4516,6 +4560,8 @@ public class DefaultCodegen implements CodegenConfig { } } setParameterBooleanFlagWithCodegenProperty(codegenParameter, codegenProperty); + // set nullable + setParameterNullable(codegenParameter, codegenProperty); } } else { @@ -4539,6 +4585,8 @@ public class DefaultCodegen implements CodegenConfig { } setParameterBooleanFlagWithCodegenProperty(codegenParameter, codegenProperty); + // set nullable + setParameterNullable(codegenParameter, codegenProperty); } // set the parameter's example value @@ -4636,4 +4684,8 @@ public class DefaultCodegen implements CodegenConfig { } return codegenServerVariables; } + + private void setParameterNullable(CodegenParameter parameter, CodegenProperty property) { + parameter.isNullable = property.isNullable; + } } diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AbstractAdaCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AbstractAdaCodegen.java index d15b57315d..b395b739ad 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AbstractAdaCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AbstractAdaCodegen.java @@ -44,6 +44,7 @@ import java.util.List; import java.util.Locale; import java.util.Map; + abstract public class AbstractAdaCodegen extends DefaultCodegen implements CodegenConfig { private static final Logger LOGGER = LoggerFactory.getLogger(AbstractAdaCodegen.class); @@ -619,7 +620,7 @@ abstract public class AbstractAdaCodegen extends DefaultCodegen implements Codeg } } } - authMethod.name = camelize(sanitizeName(authMethod.name), true); + authMethod.name = org.openapitools.codegen.utils.StringUtils.camelize(sanitizeName(authMethod.name), true); } } } diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AbstractApexCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AbstractApexCodegen.java index 3968eaaca5..54abf6168e 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AbstractApexCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AbstractApexCodegen.java @@ -36,6 +36,7 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; + public abstract class AbstractApexCodegen extends DefaultCodegen implements CodegenConfig { private static final Logger LOGGER = LoggerFactory.getLogger(AbstractApexCodegen.class); @@ -112,7 +113,7 @@ public abstract class AbstractApexCodegen extends DefaultCodegen implements Code // camelize (lower first character) the variable name // pet_id => petId - name = camelize(name, true); + name = org.openapitools.codegen.utils.StringUtils.camelize(name, true); // for reserved word or word starting with number, append _ if (isReservedWord(name) || name.matches("^\\d.*")) { @@ -159,7 +160,7 @@ public abstract class AbstractApexCodegen extends DefaultCodegen implements Code // camelize the model name // phone_number => PhoneNumber - final String camelizedName = camelize(nameWithPrefixSuffix); + final String camelizedName = org.openapitools.codegen.utils.StringUtils.camelize(nameWithPrefixSuffix); // model name cannot use reserved keyword, e.g. return if (isReservedWord(camelizedName)) { @@ -422,11 +423,11 @@ public abstract class AbstractApexCodegen extends DefaultCodegen implements Code throw new RuntimeException("Empty method/operation name (operationId) not allowed"); } - operationId = camelize(sanitizeName(operationId), true); + operationId = org.openapitools.codegen.utils.StringUtils.camelize(sanitizeName(operationId), true); // method name cannot use reserved keyword, e.g. return if (isReservedWord(operationId)) { - String newOperationId = camelize("call_" + operationId, true); + String newOperationId = org.openapitools.codegen.utils.StringUtils.camelize("call_" + operationId, true); LOGGER.warn(operationId + " (reserved word) cannot be used as method name. Renamed to " + newOperationId); return newOperationId; } @@ -515,7 +516,7 @@ public abstract class AbstractApexCodegen extends DefaultCodegen implements Code @Override public String toEnumName(CodegenProperty property) { - return sanitizeName(camelize(property.name)) + "Enum"; + return sanitizeName(org.openapitools.codegen.utils.StringUtils.camelize(property.name)) + "Enum"; } @Override @@ -669,7 +670,7 @@ public abstract class AbstractApexCodegen extends DefaultCodegen implements Code @Override public String sanitizeTag(String tag) { - return camelize(sanitizeName(tag)); + return org.openapitools.codegen.utils.StringUtils.camelize(sanitizeName(tag)); } @Override 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 92c9f53606..2e99417e93 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 @@ -39,6 +39,7 @@ import org.slf4j.LoggerFactory; import java.io.File; import java.util.*; + public abstract class AbstractCSharpCodegen extends DefaultCodegen implements CodegenConfig { protected boolean optionalAssemblyInfoFlag = true; @@ -600,17 +601,17 @@ public abstract class AbstractCSharpCodegen extends DefaultCodegen implements Co // method name cannot use reserved keyword, e.g. return if (isReservedWord(operationId)) { - LOGGER.warn(operationId + " (reserved word) cannot be used as method name. Renamed to " + camelize(sanitizeName("call_" + operationId))); + LOGGER.warn(operationId + " (reserved word) cannot be used as method name. Renamed to " + org.openapitools.codegen.utils.StringUtils.camelize(sanitizeName("call_" + operationId))); operationId = "call_" + operationId; } // operationId starts with a number if (operationId.matches("^\\d.*")) { - LOGGER.warn(operationId + " (starting with a number) cannot be used as method name. Renamed to " + camelize(sanitizeName("call_" + operationId))); + LOGGER.warn(operationId + " (starting with a number) cannot be used as method name. Renamed to " + org.openapitools.codegen.utils.StringUtils.camelize(sanitizeName("call_" + operationId))); operationId = "call_" + operationId; } - return camelize(sanitizeName(operationId)); + return org.openapitools.codegen.utils.StringUtils.camelize(sanitizeName(operationId)); } @Override @@ -625,7 +626,7 @@ public abstract class AbstractCSharpCodegen extends DefaultCodegen implements Co // camelize the variable name // pet_id => PetId - name = camelize(name); + name = org.openapitools.codegen.utils.StringUtils.camelize(name); // for reserved word or word starting with number, append _ if (isReservedWord(name) || name.matches("^\\d.*")) { @@ -648,9 +649,9 @@ public abstract class AbstractCSharpCodegen extends DefaultCodegen implements Co return name; } - // camelize(lower) the variable name + // org.openapitools.codegen.utils.StringUtils.camelize(lower) the variable name // pet_id => petId - name = camelize(name, true); + name = org.openapitools.codegen.utils.StringUtils.camelize(name, true); // for reserved word or word starting with number, append _ if (isReservedWord(name) || name.matches("^\\d.*")) { @@ -836,19 +837,19 @@ public abstract class AbstractCSharpCodegen extends DefaultCodegen implements Co // 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)); + LOGGER.warn(name + " (reserved word) cannot be used as model name. Renamed to " + org.openapitools.codegen.utils.StringUtils.camelize("model_" + name)); name = "model_" + name; // e.g. return => ModelReturn (after camelize) } // model name starts with number if (name.matches("^\\d.*")) { - LOGGER.warn(name + " (model name starts with number) cannot be used as model name. Renamed to " + camelize("model_" + name)); + LOGGER.warn(name + " (model name starts with number) cannot be used as model name. Renamed to " + org.openapitools.codegen.utils.StringUtils.camelize("model_" + name)); name = "model_" + name; // e.g. 200Response => Model200Response (after camelize) } // camelize the model name // phone_number => PhoneNumber - return camelize(name); + return org.openapitools.codegen.utils.StringUtils.camelize(name); } @Override @@ -936,7 +937,7 @@ public abstract class AbstractCSharpCodegen extends DefaultCodegen implements Co // for symbol, e.g. $, # if (getSymbolName(name) != null) { - return camelize(getSymbolName(name)); + return org.openapitools.codegen.utils.StringUtils.camelize(getSymbolName(name)); } String enumName = sanitizeName(name); @@ -944,7 +945,7 @@ public abstract class AbstractCSharpCodegen extends DefaultCodegen implements Co enumName = enumName.replaceFirst("^_", ""); enumName = enumName.replaceFirst("_$", ""); - enumName = camelize(enumName) + "Enum"; + enumName = org.openapitools.codegen.utils.StringUtils.camelize(enumName) + "Enum"; if (enumName.matches("\\d.*")) { // starts with number return "_" + enumName; @@ -955,7 +956,7 @@ public abstract class AbstractCSharpCodegen extends DefaultCodegen implements Co @Override public String toEnumName(CodegenProperty property) { - return sanitizeName(camelize(property.name)) + "Enum"; + return sanitizeName(org.openapitools.codegen.utils.StringUtils.camelize(property.name)) + "Enum"; } public String testPackageName() { diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AbstractEiffelCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AbstractEiffelCodegen.java index 116a27d1ca..a9ad50d4b6 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AbstractEiffelCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AbstractEiffelCodegen.java @@ -17,6 +17,8 @@ package org.openapitools.codegen.languages; +import static com.google.common.base.Strings.isNullOrEmpty; + import com.google.common.collect.ArrayListMultimap; import com.google.common.collect.Multimap; import io.swagger.v3.core.util.Json; @@ -204,7 +206,7 @@ public abstract class AbstractEiffelCodegen extends DefaultCodegen implements Co // (after camelize) } - return underscore(name); + return org.openapitools.codegen.utils.StringUtils.underscore(name); } @Override @@ -215,7 +217,7 @@ public abstract class AbstractEiffelCodegen extends DefaultCodegen implements Co // methods parameters as 'final'. // e.g. PetApi.go => pet_api.go - return underscore(name) + "_api"; + return org.openapitools.codegen.utils.StringUtils.underscore(name) + "_api"; } @Override @@ -333,7 +335,7 @@ public abstract class AbstractEiffelCodegen extends DefaultCodegen implements Co // method name cannot use reserved keyword, e.g. return if (isReservedWord(sanitizedOperationId)) { LOGGER.warn(operationId + " (reserved word) cannot be used as method name. Renamed to " - + camelize("call_" + operationId)); + + org.openapitools.codegen.utils.StringUtils.camelize("call_" + operationId)); sanitizedOperationId = "call_" + sanitizedOperationId; } // method name from updateSomething to update_Something. @@ -351,7 +353,7 @@ public abstract class AbstractEiffelCodegen extends DefaultCodegen implements Co for (CodegenOperation operation : operations) { // http method verb conversion (e.g. PUT => Put) - operation.httpMethod = camelize(operation.httpMethod.toLowerCase(Locale.ROOT)); + operation.httpMethod = org.openapitools.codegen.utils.StringUtils.camelize(operation.httpMethod.toLowerCase(Locale.ROOT)); } // remove model imports to avoid error 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 e6d60a99df..3a274341d5 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 @@ -134,7 +134,7 @@ public abstract class AbstractGoCodegen extends DefaultCodegen implements Codege if (this.reservedWordsMappings().containsKey(name)) { return this.reservedWordsMappings().get(name); } - return camelize(name) + '_'; + return org.openapitools.codegen.utils.StringUtils.camelize(name) + '_'; } @Override @@ -149,7 +149,7 @@ public abstract class AbstractGoCodegen extends DefaultCodegen implements Codege // camelize (lower first character) the variable name // pet_id => PetId - name = camelize(name); + name = org.openapitools.codegen.utils.StringUtils.camelize(name); // for reserved word append _ if (isReservedWord(name)) { @@ -174,7 +174,7 @@ public abstract class AbstractGoCodegen extends DefaultCodegen implements Codege // params should be lowerCamelCase. E.g. "person Person", instead of // "Person Person". // - name = camelize(toVarName(name), true); + name = org.openapitools.codegen.utils.StringUtils.camelize(toVarName(name), true); // REVISIT: Actually, for idiomatic go, the param name should // really should just be a letter, e.g. "p Person"), but we'll get @@ -191,7 +191,7 @@ public abstract class AbstractGoCodegen extends DefaultCodegen implements Codege public String toModelName(String name) { // camelize the model name // phone_number => PhoneNumber - return camelize(toModel(name)); + return org.openapitools.codegen.utils.StringUtils.camelize(toModel(name)); } @Override @@ -228,7 +228,7 @@ public abstract class AbstractGoCodegen extends DefaultCodegen implements Codege name = "model_" + name; // e.g. 200Response => Model200Response (after camelize) } - return underscore(name); + return org.openapitools.codegen.utils.StringUtils.underscore(name); } @Override @@ -237,7 +237,7 @@ public abstract class AbstractGoCodegen extends DefaultCodegen implements Codege name = name.replaceAll("-", "_"); // FIXME: a parameter should not be assigned. Also declare the methods parameters as 'final'. // e.g. PetApi.go => pet_api.go - name = "api_" + underscore(name); + name = "api_" + org.openapitools.codegen.utils.StringUtils.underscore(name); if (name.endsWith("_test")) { LOGGER.warn(name + ".go with `_test.go` suffix (reserved word) cannot be used as filename. Renamed to " + name + "_.go"); name += "_"; @@ -308,17 +308,17 @@ public abstract class AbstractGoCodegen extends DefaultCodegen implements Codege // method name cannot use reserved keyword, e.g. return if (isReservedWord(sanitizedOperationId)) { LOGGER.warn(operationId + " (reserved word) cannot be used as method name. Renamed to " - + camelize("call_" + sanitizedOperationId)); + + org.openapitools.codegen.utils.StringUtils.camelize("call_" + sanitizedOperationId)); sanitizedOperationId = "call_" + sanitizedOperationId; } // operationId starts with a number if (sanitizedOperationId.matches("^\\d.*")) { - LOGGER.warn(operationId + " (starting with a number) cannot be used as method name. Renamed to " + camelize("call_" + sanitizedOperationId)); + LOGGER.warn(operationId + " (starting with a number) cannot be used as method name. Renamed to " + org.openapitools.codegen.utils.StringUtils.camelize("call_" + sanitizedOperationId)); sanitizedOperationId = "call_" + sanitizedOperationId; } - return camelize(sanitizedOperationId); + return org.openapitools.codegen.utils.StringUtils.camelize(sanitizedOperationId); } @Override @@ -329,7 +329,7 @@ public abstract class AbstractGoCodegen extends DefaultCodegen implements Codege List operations = (List) objectMap.get("operation"); for (CodegenOperation operation : operations) { // http method verb conversion (e.g. PUT => Put) - operation.httpMethod = camelize(operation.httpMethod.toLowerCase(Locale.ROOT)); + operation.httpMethod = org.openapitools.codegen.utils.StringUtils.camelize(operation.httpMethod.toLowerCase(Locale.ROOT)); } // remove model imports to avoid error @@ -560,7 +560,7 @@ public abstract class AbstractGoCodegen extends DefaultCodegen implements Codege } // string - String enumName = sanitizeName(underscore(name).toUpperCase(Locale.ROOT)); + String enumName = sanitizeName(org.openapitools.codegen.utils.StringUtils.underscore(name).toUpperCase(Locale.ROOT)); enumName = enumName.replaceFirst("^_", ""); enumName = enumName.replaceFirst("_$", ""); @@ -575,7 +575,7 @@ public abstract class AbstractGoCodegen extends DefaultCodegen implements Codege @Override public String toEnumName(CodegenProperty property) { - String enumName = underscore(toModelName(property.name)).toUpperCase(Locale.ROOT); + String enumName = org.openapitools.codegen.utils.StringUtils.underscore(toModelName(property.name)).toUpperCase(Locale.ROOT); // remove [] for array or map of enum enumName = enumName.replace("[]", ""); 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 eb0d56a947..ed83be48a3 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 @@ -53,6 +53,9 @@ import java.util.Locale; import java.util.Map; import java.util.regex.Pattern; +import static org.openapitools.codegen.utils.StringUtils.escape; + + public abstract class AbstractJavaCodegen extends DefaultCodegen implements CodegenConfig { private static final Logger LOGGER = LoggerFactory.getLogger(AbstractJavaCodegen.class); @@ -552,7 +555,7 @@ public abstract class AbstractJavaCodegen extends DefaultCodegen implements Code if (name.length() == 0) { return "DefaultApi"; } - return camelize(name) + "Api"; + return org.openapitools.codegen.utils.StringUtils.camelize(name) + "Api"; } @Override @@ -587,12 +590,12 @@ public abstract class AbstractJavaCodegen extends DefaultCodegen implements Code List allowedCharacters = new ArrayList<>(); allowedCharacters.add("_"); allowedCharacters.add("$"); - name = escapeSpecialCharacters(name, allowedCharacters, "_"); + name = escape(name, specialCharReplacements, allowedCharacters, "_"); } // camelize (lower first character) the variable name // pet_id => petId - name = camelize(name, true); + name = org.openapitools.codegen.utils.StringUtils.camelize(name, true); // for reserved word or word starting with number, append _ if (isReservedWord(name) || name.matches("^\\d.*")) { @@ -644,7 +647,7 @@ public abstract class AbstractJavaCodegen extends DefaultCodegen implements Code // camelize the model name // phone_number => PhoneNumber - final String camelizedName = camelize(nameWithPrefixSuffix); + final String camelizedName = org.openapitools.codegen.utils.StringUtils.camelize(nameWithPrefixSuffix); // model name cannot use reserved keyword, e.g. return if (isReservedWord(camelizedName)) { @@ -876,19 +879,19 @@ public abstract class AbstractJavaCodegen extends DefaultCodegen implements Code throw new RuntimeException("Empty method/operation name (operationId) not allowed"); } - operationId = camelize(sanitizeName(operationId), true); + operationId = org.openapitools.codegen.utils.StringUtils.camelize(sanitizeName(operationId), true); // method name cannot use reserved keyword, e.g. return if (isReservedWord(operationId)) { - String newOperationId = camelize("call_" + operationId, true); + String newOperationId = org.openapitools.codegen.utils.StringUtils.camelize("call_" + operationId, true); LOGGER.warn(operationId + " (reserved word) cannot be used as method name. Renamed to " + newOperationId); return newOperationId; } // operationId starts with a number if (operationId.matches("^\\d.*")) { - LOGGER.warn(operationId + " (starting with a number) cannot be used as method sname. Renamed to " + camelize("call_" + operationId), true); - operationId = camelize("call_" + operationId, true); + LOGGER.warn(operationId + " (starting with a number) cannot be used as method sname. Renamed to " + org.openapitools.codegen.utils.StringUtils.camelize("call_" + operationId), true); + operationId = org.openapitools.codegen.utils.StringUtils.camelize("call_" + operationId, true); } return operationId; @@ -1039,7 +1042,7 @@ public abstract class AbstractJavaCodegen extends DefaultCodegen implements Code @Override public String toEnumName(CodegenProperty property) { - return sanitizeName(camelize(property.name)) + "Enum"; + return sanitizeName(org.openapitools.codegen.utils.StringUtils.camelize(property.name)) + "Enum"; } @Override @@ -1335,7 +1338,7 @@ public abstract class AbstractJavaCodegen extends DefaultCodegen implements Code @Override public String sanitizeTag(String tag) { - tag = camelize(underscore(sanitizeName(tag))); + tag = org.openapitools.codegen.utils.StringUtils.camelize(org.openapitools.codegen.utils.StringUtils.underscore(sanitizeName(tag))); // tag starts with numbers if (tag.matches("^\\d.*")) { diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AbstractJavaJAXRSServerCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AbstractJavaJAXRSServerCodegen.java index e24b1e7bd7..b57ca9e244 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AbstractJavaJAXRSServerCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AbstractJavaJAXRSServerCodegen.java @@ -40,6 +40,7 @@ import java.util.HashMap; import java.util.List; import java.util.Map; + public abstract class AbstractJavaJAXRSServerCodegen extends AbstractJavaCodegen implements BeanValidationFeatures { public static final String SERVER_PORT = "serverPort"; /** @@ -250,7 +251,7 @@ public abstract class AbstractJavaJAXRSServerCodegen extends AbstractJavaCodegen return "DefaultApi"; } computed = sanitizeName(computed); - return camelize(computed) + "Api"; + return org.openapitools.codegen.utils.StringUtils.camelize(computed) + "Api"; } @Override 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 774c96fe33..37c5124c9f 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 @@ -19,6 +19,7 @@ package org.openapitools.codegen.languages; import io.swagger.v3.oas.models.media.ArraySchema; import io.swagger.v3.oas.models.media.Schema; +import org.apache.commons.lang3.StringUtils; import org.openapitools.codegen.CliOption; import org.openapitools.codegen.CodegenConfig; import org.openapitools.codegen.CodegenConstants; @@ -28,11 +29,8 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.File; -import java.util.Arrays; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Locale; -import java.util.Map; +import java.util.*; + public abstract class AbstractKotlinCodegen extends DefaultCodegen implements CodegenConfig { private static final Logger LOGGER = LoggerFactory.getLogger(AbstractKotlinCodegen.class); @@ -55,6 +53,7 @@ public abstract class AbstractKotlinCodegen extends DefaultCodegen implements Co languageSpecificPrimitives = new HashSet(Arrays.asList( "kotlin.Byte", + "kotlin.ByteArray", "kotlin.Short", "kotlin.Int", "kotlin.Long", @@ -139,6 +138,7 @@ public abstract class AbstractKotlinCodegen extends DefaultCodegen implements Co defaultIncludes = new HashSet(Arrays.asList( "kotlin.Byte", + "kotlin.ByteArray", "kotlin.Short", "kotlin.Int", "kotlin.Long", @@ -159,21 +159,22 @@ public abstract class AbstractKotlinCodegen extends DefaultCodegen implements Co typeMapping.put("float", "kotlin.Float"); typeMapping.put("long", "kotlin.Long"); typeMapping.put("double", "kotlin.Double"); + typeMapping.put("ByteArray", "kotlin.ByteArray"); typeMapping.put("number", "java.math.BigDecimal"); typeMapping.put("date-time", "java.time.LocalDateTime"); typeMapping.put("date", "java.time.LocalDateTime"); typeMapping.put("file", "java.io.File"); typeMapping.put("array", "kotlin.Array"); - typeMapping.put("list", "kotlin.Array"); + typeMapping.put("list", "kotlin.collections.List"); typeMapping.put("map", "kotlin.collections.Map"); typeMapping.put("object", "kotlin.Any"); typeMapping.put("binary", "kotlin.Array"); typeMapping.put("Date", "java.time.LocalDateTime"); typeMapping.put("DateTime", "java.time.LocalDateTime"); - instantiationTypes.put("array", "arrayOf"); - instantiationTypes.put("list", "arrayOf"); - instantiationTypes.put("map", "mapOf"); + instantiationTypes.put("array", "kotlin.arrayOf"); + instantiationTypes.put("list", "kotlin.arrayOf"); + instantiationTypes.put("map", "kotlin.mapOf"); importMapping = new HashMap(); importMapping.put("BigDecimal", "java.math.BigDecimal"); @@ -400,16 +401,16 @@ public abstract class AbstractKotlinCodegen extends DefaultCodegen implements Co break; case camelCase: // NOTE: Removes hyphens and underscores - modified = camelize(modified, true); + modified = org.openapitools.codegen.utils.StringUtils.camelize(modified, true); break; case PascalCase: // NOTE: Removes hyphens and underscores - String result = camelize(modified); + String result = org.openapitools.codegen.utils.StringUtils.camelize(modified); modified = titleCase(result); break; case snake_case: // NOTE: Removes hyphens - modified = underscore(modified); + modified = org.openapitools.codegen.utils.StringUtils.underscore(modified); break; case UPPERCASE: modified = modified.toUpperCase(Locale.ROOT); @@ -471,15 +472,55 @@ public abstract class AbstractKotlinCodegen extends DefaultCodegen implements Co modifiedName = sanitizeKotlinSpecificNames(modifiedName); // Camelize name of nested properties - modifiedName = camelize(modifiedName); + modifiedName = org.openapitools.codegen.utils.StringUtils.camelize(modifiedName); - if (reservedWords.contains(modifiedName)) { - modifiedName = escapeReservedWord(modifiedName); + // model name cannot use reserved keyword, e.g. return + if (isReservedWord(modifiedName)) { + final String modelName = "Model" + modifiedName; + LOGGER.warn(modifiedName + " (reserved word) cannot be used as model name. Renamed to " + modelName); + return modelName; + } + + // model name starts with number + if (modifiedName.matches("^\\d.*")) { + final String modelName = "Model" + modifiedName; // e.g. 200Response => Model200Response (after camelize) + LOGGER.warn(name + " (model name starts with number) cannot be used as model name. Renamed to " + modelName); + return modelName; } return titleCase(modifiedName); } + /** + * Return the operation ID (method name) + * + * @param operationId operation ID + * @return the sanitized method name + */ + @Override + public String toOperationId(String operationId) { + // throw exception if method name is empty + if (StringUtils.isEmpty(operationId)) + throw new RuntimeException("Empty method/operation name (operationId) not allowed"); + + operationId = camelize(sanitizeName(operationId), true); + + // method name cannot use reserved keyword, e.g. return + if (isReservedWord(operationId)) { + String newOperationId = camelize("call_" + operationId, true); + LOGGER.warn(operationId + " (reserved word) cannot be used as method name. Renamed to " + newOperationId); + return newOperationId; + } + + // operationId starts with a number + if (operationId.matches("^\\d.*")) { + LOGGER.warn(operationId + " (starting with a number) cannot be used as method sname. Renamed to " + camelize("call_" + operationId), true); + operationId = camelize("call_" + operationId, true); + } + + return operationId; + } + @Override public String toModelFilename(String name) { // Should be the same as the model name @@ -577,4 +618,70 @@ public abstract class AbstractKotlinCodegen extends DefaultCodegen implements Co public boolean isDataTypeString(final String dataType) { return "String".equals(dataType) || "kotlin.String".equals(dataType); } + + @Override + public String toParamName(String name) { + // to avoid conflicts with 'callback' parameter for async call + if ("callback".equals(name)) { + return "paramCallback"; + } + + // should be the same as variable name + return toVarName(name); + } + + @Override + public String toVarName(String name) { + // sanitize name + name = sanitizeName(name, "\\W-[\\$]"); + + if (name.toLowerCase(Locale.ROOT).matches("^_*class$")) { + return "propertyClass"; + } + + if ("_".equals(name)) { + name = "_u"; + } + + // if it's all uppper case, do nothing + if (name.matches("^[A-Z_]*$")) { + return name; + } + + if (startsWithTwoUppercaseLetters(name)) { + name = name.substring(0, 2).toLowerCase(Locale.ROOT) + name.substring(2); + } + + // If name contains special chars -> replace them. + if ((name.chars().anyMatch(character -> specialCharReplacements.keySet().contains("" + ((char) character))))) { + List allowedCharacters = new ArrayList<>(); + allowedCharacters.add("_"); + allowedCharacters.add("$"); + name = escapeSpecialCharacters(name, allowedCharacters, "_"); + } + + // camelize (lower first character) the variable name + // pet_id => petId + name = camelize(name, true); + + // for reserved word or word starting with number or containing dollar symbol, escape it + if (isReservedWord(name) || name.matches("(^\\d.*)|(.*[$].*)")) { + name = escapeReservedWord(name); + } + + return name; + } + + @Override + public String toRegularExpression(String pattern) { + return escapeText(pattern); + } + + private boolean startsWithTwoUppercaseLetters(String name) { + boolean startsWithTwoUppercaseLetters = false; + if (name.length() > 1) { + startsWithTwoUppercaseLetters = name.substring(0, 2).equals(name.substring(0, 2).toUpperCase(Locale.ROOT)); + } + return startsWithTwoUppercaseLetters; + } } diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AbstractPhpCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AbstractPhpCodegen.java index 98161179c1..2b27fdbae1 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AbstractPhpCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AbstractPhpCodegen.java @@ -40,6 +40,12 @@ import java.util.Locale; import java.util.Map; import java.util.regex.Matcher; +import org.apache.commons.lang3.StringUtils; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + + public abstract class AbstractPhpCodegen extends DefaultCodegen implements CodegenConfig { private static final Logger LOGGER = LoggerFactory.getLogger(AbstractPhpCodegen.class); @@ -408,11 +414,11 @@ public abstract class AbstractPhpCodegen extends DefaultCodegen implements Codeg if ("camelCase".equals(variableNamingConvention)) { // return the name in camelCase style // phone_number => phoneNumber - name = camelize(name, true); + name = org.openapitools.codegen.utils.StringUtils.camelize(name, true); } else { // default to snake case // return the name in underscore style // PhoneNumber => phone_number - name = underscore(name); + name = org.openapitools.codegen.utils.StringUtils.underscore(name); } // parameter name starting with number won't compile @@ -443,13 +449,13 @@ public abstract class AbstractPhpCodegen extends DefaultCodegen implements Codeg // model name cannot use reserved keyword if (isReservedWord(name)) { - LOGGER.warn(name + " (reserved word) cannot be used as model name. Renamed to " + camelize("model_" + name)); + LOGGER.warn(name + " (reserved word) cannot be used as model name. Renamed to " + org.openapitools.codegen.utils.StringUtils.camelize("model_" + name)); name = "model_" + name; // e.g. return => ModelReturn (after camelize) } // model name starts with number if (name.matches("^\\d.*")) { - LOGGER.warn(name + " (model name starts with number) cannot be used as model name. Renamed to " + camelize("model_" + name)); + LOGGER.warn(name + " (model name starts with number) cannot be used as model name. Renamed to " + org.openapitools.codegen.utils.StringUtils.camelize("model_" + name)); name = "model_" + name; // e.g. 200Response => Model200Response (after camelize) } @@ -466,7 +472,7 @@ public abstract class AbstractPhpCodegen extends DefaultCodegen implements Codeg // camelize the model name // phone_number => PhoneNumber - return camelize(name); + return org.openapitools.codegen.utils.StringUtils.camelize(name); } @Override @@ -490,17 +496,17 @@ public abstract class AbstractPhpCodegen extends DefaultCodegen implements Codeg // method name cannot use reserved keyword, e.g. return if (isReservedWord(operationId)) { - LOGGER.warn(operationId + " (reserved word) cannot be used as method name. Renamed to " + camelize(sanitizeName("call_" + operationId), true)); + LOGGER.warn(operationId + " (reserved word) cannot be used as method name. Renamed to " + org.openapitools.codegen.utils.StringUtils.camelize(sanitizeName("call_" + operationId), true)); operationId = "call_" + operationId; } // operationId starts with a number if (operationId.matches("^\\d.*")) { - LOGGER.warn(operationId + " (starting with a number) cannot be used as method name. Renamed to " + camelize(sanitizeName("call_" + operationId), true)); + LOGGER.warn(operationId + " (starting with a number) cannot be used as method name. Renamed to " + org.openapitools.codegen.utils.StringUtils.camelize(sanitizeName("call_" + operationId), true)); operationId = "call_" + operationId; } - return camelize(sanitizeName(operationId), true); + return org.openapitools.codegen.utils.StringUtils.camelize(sanitizeName(operationId), true); } /** @@ -638,7 +644,7 @@ public abstract class AbstractPhpCodegen extends DefaultCodegen implements Codeg } // string - String enumName = sanitizeName(underscore(name).toUpperCase(Locale.ROOT)); + String enumName = sanitizeName(org.openapitools.codegen.utils.StringUtils.underscore(name).toUpperCase(Locale.ROOT)); enumName = enumName.replaceFirst("^_", ""); enumName = enumName.replaceFirst("_$", ""); @@ -651,7 +657,7 @@ public abstract class AbstractPhpCodegen extends DefaultCodegen implements Codeg @Override public String toEnumName(CodegenProperty property) { - String enumName = underscore(toModelName(property.name)).toUpperCase(Locale.ROOT); + String enumName = org.openapitools.codegen.utils.StringUtils.underscore(toModelName(property.name)).toUpperCase(Locale.ROOT); // remove [] for array or map of enum enumName = enumName.replace("[]", ""); @@ -676,7 +682,7 @@ public abstract class AbstractPhpCodegen extends DefaultCodegen implements Codeg for (CodegenOperation op : operationList) { // for API test method name // e.g. public function test{{vendorExtensions.x-testOperationId}}() - op.vendorExtensions.put("x-testOperationId", camelize(op.operationId)); + op.vendorExtensions.put("x-testOperationId", org.openapitools.codegen.utils.StringUtils.camelize(op.operationId)); } return objs; } diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AbstractRubyCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AbstractRubyCodegen.java index b26a99dd43..c977c7cb89 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AbstractRubyCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AbstractRubyCodegen.java @@ -28,6 +28,7 @@ import org.slf4j.LoggerFactory; import java.util.Arrays; import java.util.Locale; + abstract class AbstractRubyCodegen extends DefaultCodegen implements CodegenConfig { private static final Logger LOGGER = LoggerFactory.getLogger(AbstractRubyCodegen.class); @@ -123,7 +124,7 @@ abstract class AbstractRubyCodegen extends DefaultCodegen implements CodegenConf // camelize (lower first character) the variable name // petId => pet_id - name = underscore(name); + name = org.openapitools.codegen.utils.StringUtils.underscore(name); // for reserved word or word starting with number, append _ if (isReservedWord(name) || name.matches("^\\d.*")) { @@ -143,12 +144,12 @@ abstract class AbstractRubyCodegen extends DefaultCodegen implements CodegenConf public String toOperationId(String operationId) { // method name cannot use reserved keyword, e.g. return if (isReservedWord(operationId)) { - String newOperationId = underscore("call_" + operationId); + String newOperationId = org.openapitools.codegen.utils.StringUtils.underscore("call_" + operationId); LOGGER.warn(operationId + " (reserved word) cannot be used as method name. Renamed to " + newOperationId); return newOperationId; } - return underscore(operationId); + return org.openapitools.codegen.utils.StringUtils.underscore(operationId); } @Override diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AbstractScalaCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AbstractScalaCodegen.java index 05b9f4dea4..80528f08ff 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AbstractScalaCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AbstractScalaCodegen.java @@ -35,6 +35,7 @@ import java.util.Iterator; import java.util.List; import java.util.Map; + public abstract class AbstractScalaCodegen extends DefaultCodegen { private static final Logger LOGGER = LoggerFactory.getLogger(AbstractScalaCodegen.class); @@ -273,7 +274,7 @@ public abstract class AbstractScalaCodegen extends DefaultCodegen { } protected String formatIdentifier(String name, boolean capitalized) { - String identifier = camelize(sanitizeName(name), true); + String identifier = org.openapitools.codegen.utils.StringUtils.camelize(sanitizeName(name), true); if (capitalized) { identifier = StringUtils.capitalize(identifier); } diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AbstractTypeScriptClientCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AbstractTypeScriptClientCodegen.java index 491fdf0b03..313588199f 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AbstractTypeScriptClientCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AbstractTypeScriptClientCodegen.java @@ -29,6 +29,7 @@ import org.slf4j.LoggerFactory; import java.io.File; import java.util.*; + public abstract class AbstractTypeScriptClientCodegen extends DefaultCodegen implements CodegenConfig { private static final Logger LOGGER = LoggerFactory.getLogger(AbstractTypeScriptClientCodegen.class); @@ -191,27 +192,27 @@ public abstract class AbstractTypeScriptClientCodegen extends DefaultCodegen imp // model name cannot use reserved keyword, e.g. return if (isReservedWord(name)) { - String modelName = camelize("model_" + name); + String modelName = org.openapitools.codegen.utils.StringUtils.camelize("model_" + name); LOGGER.warn(name + " (reserved word) cannot be used as model name. Renamed to " + modelName); return modelName; } // model name starts with number if (name.matches("^\\d.*")) { - String modelName = camelize("model_" + name); // e.g. 200Response => Model200Response (after camelize) + String modelName = org.openapitools.codegen.utils.StringUtils.camelize("model_" + name); // e.g. 200Response => Model200Response (after camelize) LOGGER.warn(name + " (model name starts with number) cannot be used as model name. Renamed to " + modelName); return modelName; } if (languageSpecificPrimitives.contains(name)) { - String modelName = camelize("model_" + name); + String modelName = org.openapitools.codegen.utils.StringUtils.camelize("model_" + name); LOGGER.warn(name + " (model name matches existing language type) cannot be used as a model name. Renamed to " + modelName); return modelName; } // camelize the model name // phone_number => PhoneNumber - return camelize(name); + return org.openapitools.codegen.utils.StringUtils.camelize(name); } @Override @@ -375,10 +376,10 @@ public abstract class AbstractTypeScriptClientCodegen extends DefaultCodegen imp // method name cannot use reserved keyword, e.g. return // append _ at the beginning, e.g. _return if (isReservedWord(operationId)) { - return escapeReservedWord(camelize(sanitizeName(operationId), true)); + return escapeReservedWord(org.openapitools.codegen.utils.StringUtils.camelize(sanitizeName(operationId), true)); } - return camelize(sanitizeName(operationId), true); + return org.openapitools.codegen.utils.StringUtils.camelize(sanitizeName(operationId), true); } public void setModelPropertyNaming(String naming) { @@ -401,11 +402,11 @@ public abstract class AbstractTypeScriptClientCodegen extends DefaultCodegen imp case original: return name; case camelCase: - return camelize(name, true); + return org.openapitools.codegen.utils.StringUtils.camelize(name, true); case PascalCase: - return camelize(name); + return org.openapitools.codegen.utils.StringUtils.camelize(name); case snake_case: - return underscore(name); + return org.openapitools.codegen.utils.StringUtils.underscore(name); default: throw new IllegalArgumentException("Invalid model property naming '" + name + "'. Must be 'original', 'camelCase', " + @@ -436,7 +437,7 @@ public abstract class AbstractTypeScriptClientCodegen extends DefaultCodegen imp // for symbol, e.g. $, # if (getSymbolName(name) != null) { - return camelize(getSymbolName(name)); + return org.openapitools.codegen.utils.StringUtils.camelize(getSymbolName(name)); } // number @@ -456,7 +457,7 @@ public abstract class AbstractTypeScriptClientCodegen extends DefaultCodegen imp // camelize the enum variable name // ref: https://basarat.gitbooks.io/typescript/content/docs/enums.html - enumName = camelize(enumName); + enumName = org.openapitools.codegen.utils.StringUtils.camelize(enumName); if (enumName.matches("\\d.*")) { // starts with number return "_" + enumName; diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AndroidClientCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AndroidClientCodegen.java index ea267ac8cb..6c2a10ce57 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AndroidClientCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AndroidClientCodegen.java @@ -36,6 +36,7 @@ import java.io.File; import java.util.Arrays; import java.util.HashSet; + public class AndroidClientCodegen extends DefaultCodegen implements CodegenConfig { private static final Logger LOGGER = LoggerFactory.getLogger(AndroidClientCodegen.class); public static final String USE_ANDROID_MAVEN_GRADLE_PLUGIN = "useAndroidMavenGradlePlugin"; @@ -228,7 +229,7 @@ public class AndroidClientCodegen extends DefaultCodegen implements CodegenConfi // camelize (lower first character) the variable name // pet_id => petId - name = camelize(name, true); + name = org.openapitools.codegen.utils.StringUtils.camelize(name, true); // for reserved word or word starting with number, append _ if (isReservedWord(name) || name.matches("^\\d.*")) { @@ -257,7 +258,7 @@ public class AndroidClientCodegen extends DefaultCodegen implements CodegenConfi // camelize the model name // phone_number => PhoneNumber - name = camelize(sanitizeName(name)); + name = org.openapitools.codegen.utils.StringUtils.camelize(sanitizeName(name)); // model name cannot use reserved keyword, e.g. return if (isReservedWord(name)) { @@ -354,11 +355,11 @@ public class AndroidClientCodegen extends DefaultCodegen implements CodegenConfi throw new RuntimeException("Empty method name (operationId) not allowed"); } - operationId = camelize(sanitizeName(operationId), true); + operationId = org.openapitools.codegen.utils.StringUtils.camelize(sanitizeName(operationId), true); // method name cannot use reserved keyword, e.g. return if (isReservedWord(operationId)) { - String newOperationId = camelize("call_" + operationId, true); + String newOperationId = org.openapitools.codegen.utils.StringUtils.camelize("call_" + operationId, true); LOGGER.warn(operationId + " (reserved word) cannot be used as method name. Renamed to " + newOperationId); return newOperationId; } diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/ApexClientCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/ApexClientCodegen.java index 66dcb89a52..65e0299062 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/ApexClientCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/ApexClientCodegen.java @@ -29,6 +29,7 @@ import org.slf4j.LoggerFactory; import java.io.File; import java.util.*; + public class ApexClientCodegen extends AbstractApexCodegen { private static final String CLASS_PREFIX = "classPrefix"; @@ -191,7 +192,7 @@ public class ApexClientCodegen extends AbstractApexCodegen { @Override public String toApiName(String name) { - return camelize(classPrefix + super.toApiName(name)); + return org.openapitools.codegen.utils.StringUtils.camelize(classPrefix + super.toApiName(name)); } @Override diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/CSharpClientCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/CSharpClientCodegen.java index 470641d928..f17c354de7 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/CSharpClientCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/CSharpClientCodegen.java @@ -17,6 +17,8 @@ package org.openapitools.codegen.languages; +import static org.apache.commons.lang3.StringUtils.isEmpty; + import com.google.common.collect.ImmutableMap; import com.samskivert.mustache.Mustache; import io.swagger.v3.oas.models.media.Schema; @@ -702,7 +704,7 @@ public class CSharpClientCodegen extends AbstractCSharpCodegen { // for symbol, e.g. $, # if (getSymbolName(value) != null) { - return camelize(getSymbolName(value)); + return org.openapitools.codegen.utils.StringUtils.camelize(getSymbolName(value)); } // number @@ -718,7 +720,7 @@ public class CSharpClientCodegen extends AbstractCSharpCodegen { // string String var = value.replaceAll("_", " "); //var = WordUtils.capitalizeFully(var); - var = camelize(var); + var = org.openapitools.codegen.utils.StringUtils.camelize(var); var = var.replaceAll("\\W+", ""); if (var.matches("\\d.*")) { @@ -753,11 +755,11 @@ public class CSharpClientCodegen extends AbstractCSharpCodegen { case original: return name; case camelCase: - return camelize(name, true); + return org.openapitools.codegen.utils.StringUtils.camelize(name, true); case PascalCase: - return camelize(name); + return org.openapitools.codegen.utils.StringUtils.camelize(name); case snake_case: - return underscore(name); + return org.openapitools.codegen.utils.StringUtils.underscore(name); default: throw new IllegalArgumentException("Invalid model property naming '" + name + "'. Must be 'original', 'camelCase', " + diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/CSharpNancyFXServerCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/CSharpNancyFXServerCodegen.java index be5147d3da..25106c48ee 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/CSharpNancyFXServerCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/CSharpNancyFXServerCodegen.java @@ -36,6 +36,7 @@ import org.openapitools.codegen.utils.URLPathUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; + import java.io.File; import java.net.URL; import java.util.ArrayList; @@ -332,7 +333,7 @@ public class CSharpNancyFXServerCodegen extends AbstractCSharpCodegen { return "Empty"; } - final String enumName = camelize( + final String enumName = org.openapitools.codegen.utils.StringUtils.camelize( sanitizeName(name) .replaceFirst("^_", "") .replaceFirst("_$", "") @@ -399,7 +400,7 @@ public class CSharpNancyFXServerCodegen extends AbstractCSharpCodegen { @Override public String toEnumName(final CodegenProperty property) { - return sanitizeName(camelize(property.name)) + "Enum"; + return sanitizeName(org.openapitools.codegen.utils.StringUtils.camelize(property.name)) + "Enum"; } @Override diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/ClojureClientCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/ClojureClientCodegen.java index 89309b512d..9bf751e2ac 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/ClojureClientCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/ClojureClientCodegen.java @@ -35,6 +35,7 @@ import java.util.List; import java.util.Locale; import java.util.Map; + public class ClojureClientCodegen extends DefaultCodegen implements CodegenConfig { private static final String PROJECT_NAME = "projectName"; private static final String PROJECT_DESCRIPTION = "projectDescription"; @@ -109,7 +110,7 @@ public class ClojureClientCodegen extends DefaultCodegen implements CodegenConfi Info info = openAPI.getInfo(); if (projectName == null && info.getTitle() != null) { // when projectName is not specified, generate it from info.title - projectName = dashize(info.getTitle()); + projectName = org.openapitools.codegen.utils.StringUtils.dashize(info.getTitle()); } if (projectVersion == null) { // when projectVersion is not specified, use info.version @@ -148,7 +149,7 @@ public class ClojureClientCodegen extends DefaultCodegen implements CodegenConfi projectDescription = "Client library of " + projectName; } if (baseNamespace == null) { - baseNamespace = dashize(projectName); + baseNamespace = org.openapitools.codegen.utils.StringUtils.dashize(projectName); } apiPackage = baseNamespace + ".api"; @@ -182,17 +183,17 @@ public class ClojureClientCodegen extends DefaultCodegen implements CodegenConfi throw new RuntimeException("Empty method/operation name (operationId) not allowed"); } - return dashize(sanitizeName(operationId)); + return org.openapitools.codegen.utils.StringUtils.dashize(sanitizeName(operationId)); } @Override public String toApiFilename(String name) { - return underscore(toApiName(name)); + return org.openapitools.codegen.utils.StringUtils.underscore(toApiName(name)); } @Override public String toApiName(String name) { - return dashize(name); + return org.openapitools.codegen.utils.StringUtils.dashize(name); } @Override @@ -203,7 +204,7 @@ public class ClojureClientCodegen extends DefaultCodegen implements CodegenConfi @Override public String toVarName(String name) { name = name.replaceAll("[^a-zA-Z0-9_-]+", ""); // FIXME: a parameter should not be assigned. Also declare the methods parameters as 'final'. - name = dashize(name); + name = org.openapitools.codegen.utils.StringUtils.dashize(name); return name; } diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/CppPistacheServerCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/CppPistacheServerCodegen.java index 70ba645a4e..7f7a4e33b8 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/CppPistacheServerCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/CppPistacheServerCodegen.java @@ -41,6 +41,7 @@ import java.util.Locale; import java.util.Map; import java.util.Set; + public class CppPistacheServerCodegen extends AbstractCppCodegen { protected String implFolder = "impl"; protected boolean isAddExternalLibs = true; @@ -198,8 +199,8 @@ public class CppPistacheServerCodegen extends AbstractCppCodegen { public Map postProcessOperationsWithModels(Map objs, List allModels) { Map operations = (Map) objs.get("operations"); String classname = (String) operations.get("classname"); - operations.put("classnameSnakeUpperCase", DefaultCodegen.underscore(classname).toUpperCase(Locale.ROOT)); - operations.put("classnameSnakeLowerCase", DefaultCodegen.underscore(classname).toLowerCase(Locale.ROOT)); + operations.put("classnameSnakeUpperCase", org.openapitools.codegen.utils.StringUtils.underscore(classname).toUpperCase(Locale.ROOT)); + operations.put("classnameSnakeLowerCase", org.openapitools.codegen.utils.StringUtils.underscore(classname).toLowerCase(Locale.ROOT)); List operationList = (List) operations.get("operation"); for (CodegenOperation op : operationList) { @@ -246,11 +247,13 @@ public class CppPistacheServerCodegen extends AbstractCppCodegen { } op.vendorExtensions.put("x-codegen-pistache-consumesJson", consumeJson); op.vendorExtensions.put("x-codegen-pistache-isParsingSupported", isParsingSupported); + + // Check if any one of the operations needs a model, then at API file level, at least one model has to be included. for(String hdr : op.imports) { if(importMapping.containsKey(hdr)) { continue; } - additionalProperties.put("hasModelImport", true); + operations.put("hasModelImport", true); } } diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/CppQt5ClientCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/CppQt5ClientCodegen.java index 0d3d963f0f..e033b7c44b 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/CppQt5ClientCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/CppQt5ClientCodegen.java @@ -37,6 +37,7 @@ import java.util.Locale; import java.util.Map; import java.util.Set; + public class CppQt5ClientCodegen extends AbstractCppCodegen implements CodegenConfig { private static final Logger LOGGER = LoggerFactory.getLogger(CppQt5ClientCodegen.class); @@ -380,7 +381,7 @@ public class CppQt5ClientCodegen extends AbstractCppCodegen implements CodegenCo // camelize (lower first character) the variable name // petId => pet_id - varName = underscore(varName); + varName = org.openapitools.codegen.utils.StringUtils.underscore(varName); // for reserved word or word starting with number, append _ if (isReservedWord(varName) || varName.matches("^\\d.*")) { diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/CppQt5QHttpEngineServerCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/CppQt5QHttpEngineServerCodegen.java index 37f14e75c8..776602bce7 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/CppQt5QHttpEngineServerCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/CppQt5QHttpEngineServerCodegen.java @@ -23,19 +23,24 @@ import io.swagger.v3.parser.util.SchemaTypeUtil; import org.apache.commons.lang3.StringUtils; import org.openapitools.codegen.CodegenConfig; import org.openapitools.codegen.CodegenType; +import org.openapitools.codegen.CodegenOperation; +import org.openapitools.codegen.CodegenParameter; import org.openapitools.codegen.SupportingFile; import org.openapitools.codegen.utils.ModelUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.File; +import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; +import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Set; + public class CppQt5QHttpEngineServerCodegen extends AbstractCppCodegen implements CodegenConfig { @SuppressWarnings("unused") private static final Logger LOGGER = LoggerFactory.getLogger(CppQt5QHttpEngineServerCodegen.class); @@ -55,7 +60,7 @@ public class CppQt5QHttpEngineServerCodegen extends AbstractCppCodegen implement protected Map namespaces = new HashMap(); protected Set systemIncludes = new HashSet(); protected String cppNamespace = "OpenAPI"; - + protected Set nonFrameworkPrimitives = new HashSet(); public CppQt5QHttpEngineServerCodegen() { super(); @@ -135,7 +140,17 @@ public class CppQt5QHttpEngineServerCodegen extends AbstractCppCodegen implement "float", "double") ); - + nonFrameworkPrimitives.addAll(languageSpecificPrimitives); + + foundationClasses.addAll( + Arrays.asList( + "QString", + "QDate", + "QDateTime", + "QByteArray") + ); + languageSpecificPrimitives.addAll(foundationClasses); + supportingFiles.add(new SupportingFile("helpers-header.mustache", sourceFolder + MODEL_DIR, PREFIX + "Helpers.h")); supportingFiles.add(new SupportingFile("helpers-body.mustache", sourceFolder + MODEL_DIR, PREFIX + "Helpers.cpp")); supportingFiles.add(new SupportingFile("object.mustache", sourceFolder + MODEL_DIR, PREFIX + "Object.h")); @@ -174,7 +189,7 @@ public class CppQt5QHttpEngineServerCodegen extends AbstractCppCodegen implement importMapping = new HashMap(); namespaces = new HashMap(); - foundationClasses.add("QString"); + systemIncludes.add("QString"); systemIncludes.add("QList"); @@ -415,7 +430,7 @@ public class CppQt5QHttpEngineServerCodegen extends AbstractCppCodegen implement // camelize (lower first character) the variable name // petId => pet_id - varName = underscore(varName); + varName = org.openapitools.codegen.utils.StringUtils.underscore(varName); // for reserved word or word starting with number, append _ if (isReservedWord(varName) || varName.matches("^\\d.*")) { @@ -434,4 +449,71 @@ public class CppQt5QHttpEngineServerCodegen extends AbstractCppCodegen implement public String getTypeDeclaration(String str) { return str; } + + @Override + protected boolean needToImport(String type) { + return StringUtils.isNotBlank(type) && !defaultIncludes.contains(type) + && !nonFrameworkPrimitives.contains(type); + } + + @Override + @SuppressWarnings("unchecked") + public Map postProcessOperations(Map objs) { + Map objectMap = (Map) objs.get("operations"); + List operations = (List) objectMap.get("operation"); + + List> imports = (List>) objs.get("imports"); + for (CodegenOperation operation : operations) { + // Check all return parameter baseType if there is a necessity to include, include it if not + // already done + if (operation.returnBaseType != null && needToImport(operation.returnBaseType)) { + if(!isIncluded(operation.returnBaseType, imports)) { + imports.add(createMapping("import", operation.returnBaseType)); + } + } + List params = new ArrayList(); + if (operation.allParams != null)params.addAll(operation.allParams); + + // Check all parameter baseType if there is a necessity to include, include it if not + // already done + for(CodegenParameter param : params) { + if(param.isPrimitiveType && needToImport(param.baseType)) { + if(!isIncluded(param.baseType, imports)) { + imports.add(createMapping("import", param.baseType)); + } + } + } + if (operation.pathParams != null) { + // We use QString to pass path params, add it to include + if(!isIncluded("QString", imports)) { + imports.add(createMapping("import", "QString")); + } + } + } + if(isIncluded("QMap", imports)) { + // Maps uses QString as key + if(!isIncluded("QString", imports)) { + imports.add(createMapping("import", "QString")); + } + } + return objs; + } + + public Map createMapping(String key, String value) { + Map customImport = new HashMap(); + customImport.put(key, toModelImport(value)); + return customImport; + } + + private boolean isIncluded(String type, List> imports) { + boolean included = false; + String inclStr = toModelImport(type); + for (Map importItem : imports) { + if(importItem.containsValue(inclStr)) { + included = true; + break; + } + } + return included; + } } diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/CppTizenClientCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/CppTizenClientCodegen.java index 049a906182..7033661bdd 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/CppTizenClientCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/CppTizenClientCodegen.java @@ -32,6 +32,7 @@ import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; + public class CppTizenClientCodegen extends AbstractCppCodegen implements CodegenConfig { protected static String PREFIX = "ArtikCloud"; protected String sourceFolder = "src"; @@ -283,7 +284,7 @@ public class CppTizenClientCodegen extends AbstractCppCodegen implements Codegen } // add_pet_by_id => addPetById - return camelize(operationId, true); + return org.openapitools.codegen.utils.StringUtils.camelize(operationId, true); } /** * Output the Getter name for boolean property, e.g. getActive 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 d2d83170d9..a041bda543 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 @@ -39,6 +39,7 @@ import java.util.HashSet; import java.util.List; import java.util.Map; + public class DartClientCodegen extends DefaultCodegen implements CodegenConfig { private static final Logger LOGGER = LoggerFactory.getLogger(DartClientCodegen.class); @@ -243,7 +244,7 @@ public class DartClientCodegen extends DefaultCodegen implements CodegenConfig { // camelize (lower first character) the variable name // pet_id => petId - name = camelize(name, true); + name = org.openapitools.codegen.utils.StringUtils.camelize(name, true); if (name.matches("^\\d.*")) { name = "n" + name; @@ -266,23 +267,23 @@ public class DartClientCodegen extends DefaultCodegen implements CodegenConfig { public String toModelName(String name) { // model name cannot use reserved keyword, e.g. return if (isReservedWord(name)) { - LOGGER.warn(name + " (reserved word) cannot be used as model filename. Renamed to " + camelize("model_" + name)); + LOGGER.warn(name + " (reserved word) cannot be used as model filename. Renamed to " + org.openapitools.codegen.utils.StringUtils.camelize("model_" + name)); name = "model_" + name; // e.g. return => ModelReturn (after camelize) } // camelize the model name // phone_number => PhoneNumber - return camelize(name); + return org.openapitools.codegen.utils.StringUtils.camelize(name); } @Override public String toModelFilename(String name) { - return underscore(toModelName(name)); + return org.openapitools.codegen.utils.StringUtils.underscore(toModelName(name)); } @Override public String toApiFilename(String name) { - return underscore(toApiName(name)); + return org.openapitools.codegen.utils.StringUtils.underscore(toApiName(name)); } @Override @@ -401,7 +402,7 @@ public class DartClientCodegen extends DefaultCodegen implements CodegenConfig { new ArrayList>(); for (Map value : values) { Map enumVar = new HashMap(); - String name = camelize((String) value.get("identifier"), true); + String name = org.openapitools.codegen.utils.StringUtils.camelize((String) value.get("identifier"), true); if (isReservedWord(name)) { name = escapeReservedWord(name); } @@ -427,7 +428,7 @@ public class DartClientCodegen extends DefaultCodegen implements CodegenConfig { "int".equalsIgnoreCase(datatype)) { var = "Number" + var; } - return escapeReservedWord(camelize(var, true)); + return escapeReservedWord(org.openapitools.codegen.utils.StringUtils.camelize(var, true)); } @Override @@ -444,12 +445,12 @@ public class DartClientCodegen extends DefaultCodegen implements CodegenConfig { public String toOperationId(String operationId) { // method name cannot use reserved keyword, e.g. return if (isReservedWord(operationId)) { - String newOperationId = camelize("call_" + operationId, true); + String newOperationId = org.openapitools.codegen.utils.StringUtils.camelize("call_" + operationId, true); LOGGER.warn(operationId + " (reserved word) cannot be used as method name. Renamed to " + newOperationId); return newOperationId; } - return camelize(operationId, true); + return org.openapitools.codegen.utils.StringUtils.camelize(operationId, true); } public void setBrowserClient(boolean browserClient) { diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/ElixirClientCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/ElixirClientCodegen.java index 48da038035..94cd4bb5c1 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/ElixirClientCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/ElixirClientCodegen.java @@ -38,6 +38,7 @@ import java.util.*; import java.util.regex.Matcher; import java.util.regex.Pattern; + public class ElixirClientCodegen extends DefaultCodegen implements CodegenConfig { private static final Logger LOGGER = LoggerFactory.getLogger(ElixirClientCodegen.class); @@ -276,7 +277,7 @@ public class ElixirClientCodegen extends DefaultCodegen implements CodegenConfig StringBuffer buffer = new StringBuffer(); while (matcher.find()) { String pathTemplateName = matcher.group(1); - matcher.appendReplacement(buffer, "#{" + underscore(pathTemplateName) + "}" + "$2"); + matcher.appendReplacement(buffer, "#{" + org.openapitools.codegen.utils.StringUtils.underscore(pathTemplateName) + "}" + "$2"); pathTemplateNames.add(pathTemplateName); } ExtendedCodegenOperation eco = new ExtendedCodegenOperation(o); @@ -324,7 +325,7 @@ public class ElixirClientCodegen extends DefaultCodegen implements CodegenConfig String underscored(String words) { ArrayList underscoredWords = new ArrayList(); for (String word : words.split(" ")) { - underscoredWords.add(underscore(word)); + underscoredWords.add(org.openapitools.codegen.utils.StringUtils.underscore(word)); } return join("_", underscoredWords); } @@ -332,7 +333,7 @@ public class ElixirClientCodegen extends DefaultCodegen implements CodegenConfig String modulized(String words) { ArrayList modulizedWords = new ArrayList(); for (String word : words.split(" ")) { - modulizedWords.add(camelize(word)); + modulizedWords.add(org.openapitools.codegen.utils.StringUtils.camelize(word)); } return join("", modulizedWords); } @@ -351,7 +352,7 @@ public class ElixirClientCodegen extends DefaultCodegen implements CodegenConfig private String sourceFolder() { ArrayList underscoredWords = new ArrayList(); for (String word : moduleName.split("\\.")) { - underscoredWords.add(underscore(word)); + underscoredWords.add(org.openapitools.codegen.utils.StringUtils.underscore(word)); } return ("lib/" + join("/", underscoredWords)).replace('/', File.separatorChar); } @@ -378,7 +379,7 @@ public class ElixirClientCodegen extends DefaultCodegen implements CodegenConfig if (name.length() == 0) { return "Default"; } - return camelize(name); + return org.openapitools.codegen.utils.StringUtils.camelize(name); } @Override @@ -387,14 +388,14 @@ public class ElixirClientCodegen extends DefaultCodegen implements CodegenConfig name = name.replaceAll("-", "_"); // e.g. PetApi.go => pet_api.go - return underscore(name); + return org.openapitools.codegen.utils.StringUtils.underscore(name); } @Override public String toModelName(String name) { // camelize the model name // phone_number => PhoneNumber - return camelize(toModelFilename(name)); + return org.openapitools.codegen.utils.StringUtils.camelize(toModelFilename(name)); } @Override @@ -421,7 +422,7 @@ public class ElixirClientCodegen extends DefaultCodegen implements CodegenConfig name = "model_" + name; // e.g. 200Response => Model200Response (after camelize) } - return underscore(name); + return org.openapitools.codegen.utils.StringUtils.underscore(name); } @Override @@ -431,7 +432,7 @@ public class ElixirClientCodegen extends DefaultCodegen implements CodegenConfig throw new RuntimeException("Empty method name (operationId) not allowed"); } - return camelize(sanitizeName(operationId)); + return org.openapitools.codegen.utils.StringUtils.camelize(sanitizeName(operationId)); } /** @@ -584,7 +585,7 @@ public class ElixirClientCodegen extends DefaultCodegen implements CodegenConfig public String typespec() { StringBuilder sb = new StringBuilder("@spec "); - sb.append(underscore(operationId)); + sb.append(org.openapitools.codegen.utils.StringUtils.underscore(operationId)); sb.append("(Tesla.Env.client, "); for (CodegenParameter param : allParams) { diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/ElmClientCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/ElmClientCodegen.java index 4f041c6843..3867be62e4 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/ElmClientCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/ElmClientCodegen.java @@ -47,6 +47,7 @@ import java.util.Map; import java.util.Set; import java.util.TreeSet; + public class ElmClientCodegen extends DefaultCodegen implements CodegenConfig { private static final String X_ENCODER = "x-encoder"; private static final String X_DECODER = "x-decoder"; @@ -172,7 +173,7 @@ public class ElmClientCodegen extends DefaultCodegen implements CodegenConfig { @Override public String toModelName(String name) { - final String modelName = camelize(name); + final String modelName = org.openapitools.codegen.utils.StringUtils.camelize(name); return defaultIncludes.contains(modelName) ? modelName + "_" : modelName; } @@ -188,13 +189,13 @@ public class ElmClientCodegen extends DefaultCodegen implements CodegenConfig { @Override public String toVarName(String name) { - final String varName = camelize(name, true); + final String varName = org.openapitools.codegen.utils.StringUtils.camelize(name, true); return isReservedWord(varName) ? escapeReservedWord(name) : varName; } @Override public String toEnumVarName(String value, String datatype) { - final String camelized = camelize(value.replace(" ", "_").replace("(", "_").replace(")", "")); // TODO FIXME escape properly + final String camelized = org.openapitools.codegen.utils.StringUtils.camelize(value.replace(" ", "_").replace("(", "_").replace(")", "")); // TODO FIXME escape properly if (!Character.isUpperCase(camelized.charAt(0))) { return "N" + camelized; } @@ -297,8 +298,8 @@ public class ElmClientCodegen extends DefaultCodegen implements CodegenConfig { elmImport.moduleName = modulePrefix + cm.arrayModelType; elmImport.exposures = new TreeSet<>(); elmImport.exposures.add(cm.arrayModelType); - elmImport.exposures.add(camelize(cm.arrayModelType, true) + "Decoder"); - elmImport.exposures.add(camelize(cm.arrayModelType, true) + "Encoder"); + elmImport.exposures.add(org.openapitools.codegen.utils.StringUtils.camelize(cm.arrayModelType, true) + "Decoder"); + elmImport.exposures.add(org.openapitools.codegen.utils.StringUtils.camelize(cm.arrayModelType, true) + "Encoder"); elmImport.hasExposures = true; elmImports.add(elmImport); } @@ -534,7 +535,7 @@ public class ElmClientCodegen extends DefaultCodegen implements CodegenConfig { if (isMapContainer) { isPrimitiveType = isPrimitiveDataType(dataType); } - final String baseName = camelize(dataType, true); + final String baseName = org.openapitools.codegen.utils.StringUtils.camelize(dataType, true); String encoderName; String decoderName; if (isPrimitiveType) { diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/ErlangClientCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/ErlangClientCodegen.java index ed5889a92f..d202e75526 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/ErlangClientCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/ErlangClientCodegen.java @@ -34,6 +34,7 @@ import java.util.regex.Pattern; import org.slf4j.Logger; import org.slf4j.LoggerFactory; + public class ErlangClientCodegen extends DefaultCodegen implements CodegenConfig { private static final Logger LOGGER = LoggerFactory.getLogger(ErlangClientCodegen.class); @@ -203,7 +204,7 @@ public class ErlangClientCodegen extends DefaultCodegen implements CodegenConfig if (this.reservedWordsMappings().containsKey(name)) { return this.reservedWordsMappings().get(name); } - return camelize(name) + '_'; + return org.openapitools.codegen.utils.StringUtils.camelize(name) + '_'; } @Override @@ -229,7 +230,7 @@ public class ErlangClientCodegen extends DefaultCodegen implements CodegenConfig @Override public String toParamName(String name) { - return camelize(toVarName(name)); + return org.openapitools.codegen.utils.StringUtils.camelize(toVarName(name)); } @Override @@ -248,17 +249,17 @@ public class ErlangClientCodegen extends DefaultCodegen implements CodegenConfig @Override public String toModelName(String name) { - return this.packageName + "_" + underscore(name.replaceAll("-", "_").replaceAll("\\.", "_")); + return this.packageName + "_" + org.openapitools.codegen.utils.StringUtils.underscore(name.replaceAll("-", "_").replaceAll("\\.", "_")); } @Override public String toApiName(String name) { - return this.packageName + "_" + underscore(name.replaceAll("-", "_").replaceAll("\\.", "_")); + return this.packageName + "_" + org.openapitools.codegen.utils.StringUtils.underscore(name.replaceAll("-", "_").replaceAll("\\.", "_")); } @Override public String toModelFilename(String name) { - return this.packageName + "_" + underscore(name.replaceAll("\\.", "_")); + return this.packageName + "_" + org.openapitools.codegen.utils.StringUtils.underscore(name.replaceAll("\\.", "_")); } @Override @@ -268,18 +269,18 @@ public class ErlangClientCodegen extends DefaultCodegen implements CodegenConfig name = name.replaceAll("-", "_").replaceAll("\\.", "_"); // e.g. PetApi.erl => pet_api.erl - return this.packageName + "_" + underscore(name) + "_api"; + return this.packageName + "_" + org.openapitools.codegen.utils.StringUtils.underscore(name) + "_api"; } @Override public String toOperationId(String operationId) { // method name cannot use reserved keyword, e.g. return if (isReservedWord(operationId)) { - LOGGER.warn(operationId + " (reserved word) cannot be used as method name. Renamed to " + underscore(sanitizeName("call_" + operationId)).replaceAll("\\.", "_")); + LOGGER.warn(operationId + " (reserved word) cannot be used as method name. Renamed to " + org.openapitools.codegen.utils.StringUtils.underscore(sanitizeName("call_" + operationId)).replaceAll("\\.", "_")); operationId = "call_" + operationId; } - return underscore(operationId.replaceAll("\\.", "_")); + return org.openapitools.codegen.utils.StringUtils.underscore(operationId.replaceAll("\\.", "_")); } @Override @@ -301,7 +302,7 @@ public class ErlangClientCodegen extends DefaultCodegen implements CodegenConfig StringBuffer buffer = new StringBuffer(); while (matcher.find()) { String pathTemplateName = matcher.group(1); - matcher.appendReplacement(buffer, "\", " + camelize(pathTemplateName) + ", \""); + matcher.appendReplacement(buffer, "\", " + org.openapitools.codegen.utils.StringUtils.camelize(pathTemplateName) + ", \""); pathTemplateNames.add(pathTemplateName); } matcher.appendTail(buffer); diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/ErlangServerCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/ErlangServerCodegen.java index 80349e2d6f..3abb6e1343 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/ErlangServerCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/ErlangServerCodegen.java @@ -32,6 +32,7 @@ import java.util.Arrays; import java.util.List; import java.util.Map; + public class ErlangServerCodegen extends DefaultCodegen implements CodegenConfig { private static final Logger LOGGER = LoggerFactory.getLogger(ErlangServerCodegen.class); @@ -184,7 +185,7 @@ public class ErlangServerCodegen extends DefaultCodegen implements CodegenConfig if (name.length() == 0) { return this.packageName + "_default_handler"; } - return this.packageName + "_" + underscore(name) + "_handler"; + return this.packageName + "_" + org.openapitools.codegen.utils.StringUtils.underscore(name) + "_handler"; } /** @@ -212,18 +213,18 @@ public class ErlangServerCodegen extends DefaultCodegen implements CodegenConfig @Override public String toModelName(String name) { - return camelize(toModelFilename(name)); + return org.openapitools.codegen.utils.StringUtils.camelize(toModelFilename(name)); } @Override public String toOperationId(String operationId) { // method name cannot use reserved keyword, e.g. return if (isReservedWord(operationId)) { - LOGGER.warn(operationId + " (reserved word) cannot be used as method name. Renamed to " + camelize(sanitizeName("call_" + operationId))); + LOGGER.warn(operationId + " (reserved word) cannot be used as method name. Renamed to " + org.openapitools.codegen.utils.StringUtils.camelize(sanitizeName("call_" + operationId))); operationId = "call_" + operationId; } - return camelize(operationId); + return org.openapitools.codegen.utils.StringUtils.camelize(operationId); } @Override @@ -258,7 +259,7 @@ public class ErlangServerCodegen extends DefaultCodegen implements CodegenConfig } protected String toModuleName(String name) { - return this.packageName + "_" + underscore(name.replaceAll("-", "_")); + return this.packageName + "_" + org.openapitools.codegen.utils.StringUtils.underscore(name.replaceAll("-", "_")); } protected String toSourceFilePath(String name, String extension) { diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/FlashClientCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/FlashClientCodegen.java index 73ca27fa18..2925a1f893 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/FlashClientCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/FlashClientCodegen.java @@ -29,6 +29,7 @@ import java.util.Arrays; import java.util.HashMap; import java.util.Locale; + public class FlashClientCodegen extends DefaultCodegen implements CodegenConfig { private static final Logger LOGGER = LoggerFactory.getLogger(FlashClientCodegen.class); @@ -264,7 +265,7 @@ public class FlashClientCodegen extends DefaultCodegen implements CodegenConfig // underscore the variable name // petId => pet_id - name = camelize(dropDots(name), true); + name = org.openapitools.codegen.utils.StringUtils.camelize(dropDots(name), true); // for reserved word or word starting with number, append _ if (isReservedWord(name) || name.matches("^\\d.*")) { @@ -294,13 +295,13 @@ public class FlashClientCodegen extends DefaultCodegen implements CodegenConfig // 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)); + LOGGER.warn(name + " (reserved word) cannot be used as model name. Renamed to " + org.openapitools.codegen.utils.StringUtils.camelize("model_" + name)); name = "model_" + name; // e.g. return => ModelReturn (after camelize) } // camelize the model name // phone_number => PhoneNumber - return camelize(name); + return org.openapitools.codegen.utils.StringUtils.camelize(name); } @Override @@ -315,7 +316,7 @@ public class FlashClientCodegen extends DefaultCodegen implements CodegenConfig name = name.replaceAll("-", "_"); // FIXME: a parameter should not be assigned. Also declare the methods parameters as 'final'. // e.g. PhoneNumberApi.rb => phone_number_api.rb - return camelize(name) + "Api"; + return org.openapitools.codegen.utils.StringUtils.camelize(name) + "Api"; } @Override @@ -324,7 +325,7 @@ public class FlashClientCodegen extends DefaultCodegen implements CodegenConfig return "DefaultApi"; } // e.g. phone_number_api => PhoneNumberApi - return camelize(name) + "Api"; + return org.openapitools.codegen.utils.StringUtils.camelize(name) + "Api"; } @Override @@ -332,7 +333,7 @@ public class FlashClientCodegen extends DefaultCodegen implements CodegenConfig if (name.length() == 0) { return "DefaultApi"; } - return camelize(name) + "Api"; + return org.openapitools.codegen.utils.StringUtils.camelize(name) + "Api"; } @Override @@ -344,11 +345,11 @@ public class FlashClientCodegen extends DefaultCodegen implements CodegenConfig // method name cannot use reserved keyword, e.g. return if (isReservedWord(operationId)) { - LOGGER.warn(operationId + " (reserved word) cannot be used as method name. Renamed to " + underscore(sanitizeName("call_" + operationId))); + LOGGER.warn(operationId + " (reserved word) cannot be used as method name. Renamed to " + org.openapitools.codegen.utils.StringUtils.underscore(sanitizeName("call_" + operationId))); operationId = "call_" + operationId; } - return underscore(operationId); + return org.openapitools.codegen.utils.StringUtils.underscore(operationId); } public void setPackageName(String packageName) { 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 fdbc171813..94c89e0843 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 @@ -21,6 +21,7 @@ import org.openapitools.codegen.*; import java.io.File; + public class GroovyClientCodegen extends AbstractJavaCodegen { public static final String CONFIG_PACKAGE = "configPackage"; protected String title = "Petstore Server"; @@ -98,7 +99,7 @@ public class GroovyClientCodegen extends AbstractJavaCodegen { return "DefaultApi"; } name = sanitizeName(name); - return camelize(name) + "Api"; + return org.openapitools.codegen.utils.StringUtils.camelize(name) + "Api"; } public void setConfigPackage(String configPackage) { diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/HaskellHttpClientCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/HaskellHttpClientCodegen.java index 418ecd3576..a17db9ebd1 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/HaskellHttpClientCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/HaskellHttpClientCodegen.java @@ -35,6 +35,7 @@ import java.util.*; import java.util.regex.Matcher; import java.util.regex.Pattern; + public class HaskellHttpClientCodegen extends DefaultCodegen implements CodegenConfig { private static final Logger LOGGER = LoggerFactory.getLogger(HaskellHttpClientCodegen.class); @@ -616,8 +617,8 @@ public class HaskellHttpClientCodegen extends DefaultCodegen implements CodegenC } op.operationId = uniqueName; op.operationIdLowerCase = uniqueName.toLowerCase(Locale.ROOT); - op.operationIdCamelCase = DefaultCodegen.camelize(uniqueName); - op.operationIdSnakeCase = DefaultCodegen.underscore(uniqueName); + op.operationIdCamelCase = org.openapitools.codegen.utils.StringUtils.camelize(uniqueName); + op.operationIdSnakeCase = org.openapitools.codegen.utils.StringUtils.underscore(uniqueName); opList.add(op); op.baseName = tag; @@ -1077,8 +1078,8 @@ public class HaskellHttpClientCodegen extends DefaultCodegen implements CodegenC public String toVarName(String prefix, String name) { Boolean hasPrefix = !StringUtils.isBlank(prefix); - name = underscore(sanitizeName(name.replaceAll("-", "_"))); - name = camelize(name, !hasPrefix); + name = org.openapitools.codegen.utils.StringUtils.underscore(sanitizeName(name.replaceAll("-", "_"))); + name = org.openapitools.codegen.utils.StringUtils.camelize(name, !hasPrefix); if (hasPrefix) { return prefix + name; } else { @@ -1123,7 +1124,7 @@ public class HaskellHttpClientCodegen extends DefaultCodegen implements CodegenC } public String toTypeName(String prefix, String name) { - name = escapeIdentifier(prefix, camelize(sanitizeName(name))); + name = escapeIdentifier(prefix, org.openapitools.codegen.utils.StringUtils.camelize(sanitizeName(name))); return name; } @@ -1132,7 +1133,7 @@ public class HaskellHttpClientCodegen extends DefaultCodegen implements CodegenC if (StringUtils.isEmpty(operationId)) { throw new RuntimeException("Empty method/operation name (operationId) not allowed"); } - operationId = escapeIdentifier("op", camelize(sanitizeName(operationId), true)); + operationId = escapeIdentifier("op", org.openapitools.codegen.utils.StringUtils.camelize(sanitizeName(operationId), true)); return operationId; } diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/HaskellServantCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/HaskellServantCodegen.java index 9408d6b8f5..62029b6065 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/HaskellServantCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/HaskellServantCodegen.java @@ -45,6 +45,7 @@ import java.util.Locale; import java.util.Map; import java.util.regex.Pattern; + public class HaskellServantCodegen extends DefaultCodegen implements CodegenConfig { private static final Logger LOGGER = LoggerFactory.getLogger(HaskellServantCodegen.class); @@ -453,7 +454,7 @@ public class HaskellServantCodegen extends DefaultCodegen implements CodegenConf } } else if(op.getHasFormParams()) { // Use the FormX data type, where X is the conglomerate of all things being passed - String formName = "Form" + camelize(op.operationId); + String formName = "Form" + org.openapitools.codegen.utils.StringUtils.camelize(op.operationId); bodyType = formName; path.add("ReqBody '[FormUrlEncoded] " + formName); } @@ -478,7 +479,7 @@ public class HaskellServantCodegen extends DefaultCodegen implements CodegenConf // store form parameter name in the vendor extensions for (CodegenParameter param : op.formParams) { - param.vendorExtensions.put("x-formParamName", camelize(param.baseName)); + param.vendorExtensions.put("x-formParamName", org.openapitools.codegen.utils.StringUtils.camelize(param.baseName)); } // Add the HTTP method and return type @@ -494,9 +495,9 @@ public class HaskellServantCodegen extends DefaultCodegen implements CodegenConf op.vendorExtensions.put("x-routeType", joinStrings(" :> ", path)); op.vendorExtensions.put("x-clientType", joinStrings(" -> ", type)); - op.vendorExtensions.put("x-formName", "Form" + camelize(op.operationId)); + op.vendorExtensions.put("x-formName", "Form" + org.openapitools.codegen.utils.StringUtils.camelize(op.operationId)); for(CodegenParameter param : op.formParams) { - param.vendorExtensions.put("x-formPrefix", camelize(op.operationId, true)); + param.vendorExtensions.put("x-formPrefix", org.openapitools.codegen.utils.StringUtils.camelize(op.operationId, true)); } return op; } @@ -554,9 +555,9 @@ public class HaskellServantCodegen extends DefaultCodegen implements CodegenConf } // From the model name, compute the prefix for the fields. - String prefix = camelize(model.classname, true); + String prefix = org.openapitools.codegen.utils.StringUtils.camelize(model.classname, true); for(CodegenProperty prop : model.vars) { - prop.name = toVarName(prefix + camelize(fixOperatorChars(prop.name))); + prop.name = toVarName(prefix + org.openapitools.codegen.utils.StringUtils.camelize(fixOperatorChars(prop.name))); } // Create newtypes for things with non-object types 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 a7a5046ea3..fa943553e5 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 @@ -17,10 +17,6 @@ package org.openapitools.codegen.languages; -import static com.google.common.base.CaseFormat.LOWER_CAMEL; -import static com.google.common.base.CaseFormat.UPPER_UNDERSCORE; -import static java.util.Collections.sort; - import org.apache.commons.lang3.BooleanUtils; import org.apache.commons.lang3.StringUtils; import org.openapitools.codegen.CliOption; @@ -43,12 +39,14 @@ import java.util.ArrayList; import java.util.Comparator; import java.util.HashMap; import java.util.Iterator; -import java.util.LinkedHashMap; -import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.regex.Pattern; +import static com.google.common.base.CaseFormat.LOWER_CAMEL; +import static com.google.common.base.CaseFormat.UPPER_UNDERSCORE; +import static java.util.Collections.sort; + public class JavaClientCodegen extends AbstractJavaCodegen implements BeanValidationFeatures, PerformBeanValidationFeatures, GzipFeatures { @@ -67,6 +65,7 @@ public class JavaClientCodegen extends AbstractJavaCodegen public static final String PLAY_24 = "play24"; public static final String PLAY_25 = "play25"; + public static final String PLAY_26 = "play26"; public static final String FEIGN = "feign"; public static final String GOOGLE_API_CLIENT = "google-api-client"; @@ -333,7 +332,9 @@ public class JavaClientCodegen extends AbstractJavaCodegen supportingFiles.add(new SupportingFile("play24/Play24CallFactory.mustache", invokerFolder, "Play24CallFactory.java")); supportingFiles.add(new SupportingFile("play24/Play24CallAdapterFactory.mustache", invokerFolder, "Play24CallAdapterFactory.java")); - } else { + } + + if (PLAY_25.equals(playVersion)) { additionalProperties.put(PLAY_25, true); apiTemplateFiles.put("play25/api.mustache", ".java"); @@ -344,6 +345,17 @@ public class JavaClientCodegen extends AbstractJavaCodegen additionalProperties.put("java8", "true"); } + if (PLAY_26.equals(playVersion)) { + additionalProperties.put(PLAY_26, true); + apiTemplateFiles.put("play26/api.mustache", ".java"); + + supportingFiles.add(new SupportingFile("play26/ApiClient.mustache", invokerFolder, "ApiClient.java")); + supportingFiles.add(new SupportingFile("play26/Play26CallFactory.mustache", invokerFolder, "Play26CallFactory.java")); + supportingFiles.add(new SupportingFile("play26/Play26CallAdapterFactory.mustache", invokerFolder, + "Play26CallAdapterFactory.java")); + additionalProperties.put("java8", "true"); + } + supportingFiles.add(new SupportingFile("play-common/auth/ApiKeyAuth.mustache", authFolder, "ApiKeyAuth.java")); supportingFiles.add(new SupportingFile("auth/Authentication.mustache", authFolder, "Authentication.java")); supportingFiles.add(new SupportingFile("Pair.mustache", invokerFolder, "Pair.java")); @@ -426,7 +438,7 @@ public class JavaClientCodegen extends AbstractJavaCodegen for (int i = 0; i < items.length; ++i) { if (items[i].matches("^\\{(.*)\\}$")) { // wrap in {} // camelize path variable - items[i] = "{" + camelize(items[i].substring(1, items[i].length() - 1), true) + "}"; + items[i] = "{" + org.openapitools.codegen.utils.StringUtils.camelize(items[i].substring(1, items[i].length() - 1), true) + "}"; } } op.path = StringUtils.join(items, "/"); 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 6cd8ad9815..30b0474315 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/JavaInflectorServerCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/JavaInflectorServerCodegen.java @@ -34,6 +34,7 @@ import java.util.List; import java.util.Locale; import java.util.Map; + public class JavaInflectorServerCodegen extends AbstractJavaCodegen { private static final Logger LOGGER = LoggerFactory.getLogger(JavaInflectorServerCodegen.class); @@ -226,6 +227,6 @@ public class JavaInflectorServerCodegen extends AbstractJavaCodegen { return "DefaultController"; } name = name.replaceAll("[^a-zA-Z0-9]+", "_"); - return camelize(name) + "Controller"; + return org.openapitools.codegen.utils.StringUtils.camelize(name) + "Controller"; } } 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 3a7cb617d1..e345903101 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 @@ -19,6 +19,7 @@ package org.openapitools.codegen.languages; import io.swagger.v3.oas.models.Operation; import io.swagger.v3.oas.models.media.Schema; + import org.apache.commons.lang3.StringUtils; import org.openapitools.codegen.CliOption; import org.openapitools.codegen.CodegenConstants; @@ -32,6 +33,7 @@ import java.util.LinkedHashMap; import java.util.List; import java.util.Map; + public class JavaJAXRSSpecServerCodegen extends AbstractJavaJAXRSServerCodegen { public static final String INTERFACE_ONLY = "interfaceOnly"; @@ -130,6 +132,7 @@ public class JavaJAXRSSpecServerCodegen extends AbstractJavaJAXRSServerCodegen { super.processOpts(); supportingFiles.clear(); // Don't need extra files provided by AbstractJAX-RS & Java Codegen + writeOptional(outputFolder, new SupportingFile("README.mustache", "", "README.md")); if (generatePom) { writeOptional(outputFolder, new SupportingFile("pom.mustache", "", "pom.xml")); } @@ -219,6 +222,6 @@ public class JavaJAXRSSpecServerCodegen extends AbstractJavaJAXRSServerCodegen { return primaryResourceName + "Api"; } computed = sanitizeName(computed); - return camelize(computed) + "Api"; + return org.openapitools.codegen.utils.StringUtils.camelize(computed) + "Api"; } } diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/JavaPKMSTServerCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/JavaPKMSTServerCodegen.java index 40932e2023..aa638d5d25 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/JavaPKMSTServerCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/JavaPKMSTServerCodegen.java @@ -41,6 +41,7 @@ import java.util.List; import java.util.Locale; import java.util.Map; + /** * Created by prokarma on 04/09/17. */ @@ -545,7 +546,7 @@ public class JavaPKMSTServerCodegen extends AbstractJavaCodegen { title = title.substring(0, title.length() - 3); } - this.title = camelize(sanitizeName(title), true); + this.title = org.openapitools.codegen.utils.StringUtils.camelize(sanitizeName(title), true); } additionalProperties.put(TITLE, this.title); } @@ -594,7 +595,7 @@ public class JavaPKMSTServerCodegen extends AbstractJavaCodegen { return "DefaultApi"; } name = sanitizeName(name); - return camelize(name) + "Api"; + return org.openapitools.codegen.utils.StringUtils.camelize(name) + "Api"; } @Override diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/JavaPlayFrameworkCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/JavaPlayFrameworkCodegen.java index 64b1418665..4fb3905280 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/JavaPlayFrameworkCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/JavaPlayFrameworkCodegen.java @@ -35,6 +35,7 @@ import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; + public class JavaPlayFrameworkCodegen extends AbstractJavaCodegen implements BeanValidationFeatures { public static final String TITLE = "title"; @@ -301,7 +302,7 @@ public class JavaPlayFrameworkCodegen extends AbstractJavaCodegen implements Bea Matcher match = pathVariableMatcher.matcher(operation.path); while (match.find()) { String completeMatch = match.group(); - String replacement = ":" + camelize(match.group(1), true); + String replacement = ":" + org.openapitools.codegen.utils.StringUtils.camelize(match.group(1), true); operation.path = operation.path.replace(completeMatch, replacement); } diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/JavaUndertowServerCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/JavaUndertowServerCodegen.java index 2be6e49770..5c602bf2ca 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/JavaUndertowServerCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/JavaUndertowServerCodegen.java @@ -30,6 +30,7 @@ import java.util.HashMap; import java.util.List; import java.util.Map; + public class JavaUndertowServerCodegen extends AbstractJavaCodegen { private static final Logger LOGGER = LoggerFactory.getLogger(JavaUndertowServerCodegen.class); @@ -201,6 +202,6 @@ public class JavaUndertowServerCodegen extends AbstractJavaCodegen { return "DefaultHandler"; } name = name.replaceAll("[^a-zA-Z0-9]+", "_"); // FIXME: a parameter should not be assigned. Also declare the methods parameters as 'final'. - return camelize(name) + "Handler"; + return org.openapitools.codegen.utils.StringUtils.camelize(name) + "Handler"; } } diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/JavascriptClientCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/JavascriptClientCodegen.java index 2991842b88..e22c37a450 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/JavascriptClientCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/JavascriptClientCodegen.java @@ -47,6 +47,7 @@ import java.util.List; import java.util.Locale; import java.util.Map; + public class JavascriptClientCodegen extends DefaultCodegen implements CodegenConfig { @SuppressWarnings("hiding") private static final Logger LOGGER = LoggerFactory.getLogger(JavascriptClientCodegen.class); @@ -283,7 +284,7 @@ public class JavascriptClientCodegen extends DefaultCodegen implements CodegenCo Info info = openAPI.getInfo(); if (StringUtils.isBlank(projectName) && info.getTitle() != null) { // when projectName is not specified, generate it from info.title - projectName = sanitizeName(dashize(info.getTitle())); + projectName = sanitizeName(org.openapitools.codegen.utils.StringUtils.dashize(info.getTitle())); } if (StringUtils.isBlank(projectVersion)) { // when projectVersion is not specified, use info.version @@ -306,7 +307,7 @@ public class JavascriptClientCodegen extends DefaultCodegen implements CodegenCo projectName = "openapi-js-client"; } if (StringUtils.isBlank(moduleName)) { - moduleName = camelize(underscore(projectName)); + moduleName = org.openapitools.codegen.utils.StringUtils.camelize(org.openapitools.codegen.utils.StringUtils.underscore(projectName)); } if (StringUtils.isBlank(projectVersion)) { projectVersion = "1.0.0"; @@ -501,9 +502,9 @@ public class JavascriptClientCodegen extends DefaultCodegen implements CodegenCo private String getNameUsingModelPropertyNaming(String name) { switch (CodegenConstants.MODEL_PROPERTY_NAMING_TYPE.valueOf(getModelPropertyNaming())) { case original: return name; - case camelCase: return camelize(name, true); - case PascalCase: return camelize(name); - case snake_case: return underscore(name); + case camelCase: return org.openapitools.codegen.utils.StringUtils.camelize(name, true); + case PascalCase: return org.openapitools.codegen.utils.StringUtils.camelize(name); + case snake_case: return org.openapitools.codegen.utils.StringUtils.underscore(name); default: throw new IllegalArgumentException("Invalid model property naming '" + name + "'. Must be 'original', 'camelCase', " + "'PascalCase' or 'snake_case'"); @@ -556,7 +557,7 @@ public class JavascriptClientCodegen extends DefaultCodegen implements CodegenCo // camelize the model name // phone_number => PhoneNumber - name = camelize(name); + name = org.openapitools.codegen.utils.StringUtils.camelize(name); // model name cannot use reserved keyword, e.g. return if (isReservedWord(name)) { @@ -825,18 +826,18 @@ public class JavascriptClientCodegen extends DefaultCodegen implements CodegenCo throw new RuntimeException("Empty method/operation name (operationId) not allowed"); } - operationId = camelize(sanitizeName(operationId), true); + operationId = org.openapitools.codegen.utils.StringUtils.camelize(sanitizeName(operationId), true); // method name cannot use reserved keyword, e.g. return if (isReservedWord(operationId)) { - String newOperationId = camelize("call_" + operationId, true); + String newOperationId = org.openapitools.codegen.utils.StringUtils.camelize("call_" + operationId, true); LOGGER.warn(operationId + " (reserved word) cannot be used as method name. Renamed to " + newOperationId); return newOperationId; } // operationId starts with a number if (operationId.matches("^\\d.*")) { - String newOperationId = camelize("call_" + operationId, true); + String newOperationId = org.openapitools.codegen.utils.StringUtils.camelize("call_" + operationId, true); LOGGER.warn(operationId + " (starting with a number) cannot be used as method name. Renamed to " + newOperationId); return newOperationId; } @@ -1118,7 +1119,7 @@ public class JavascriptClientCodegen extends DefaultCodegen implements CodegenCo @Override public String toEnumName(CodegenProperty property) { - return sanitizeName(camelize(property.name)) + "Enum"; + return sanitizeName(org.openapitools.codegen.utils.StringUtils.camelize(property.name)) + "Enum"; } @Override diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/JavascriptClosureAngularClientCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/JavascriptClosureAngularClientCodegen.java index c756bf8ac9..6e8182c507 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/JavascriptClosureAngularClientCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/JavascriptClosureAngularClientCodegen.java @@ -42,6 +42,7 @@ import java.io.File; import org.apache.commons.lang3.StringUtils; + public class JavascriptClosureAngularClientCodegen extends DefaultCodegen implements CodegenConfig { private static final Logger LOGGER = LoggerFactory.getLogger(JavascriptClosureAngularClientCodegen.class); @@ -187,7 +188,7 @@ public class JavascriptClosureAngularClientCodegen extends DefaultCodegen implem // camelize the variable name // pet_id => PetId - name = camelize(name, true); + name = org.openapitools.codegen.utils.StringUtils.camelize(name, true); // for reserved word or word starting with number, append _ if (isReservedWord(name) || name.matches("^\\d.*")) @@ -214,13 +215,13 @@ public class JavascriptClosureAngularClientCodegen extends DefaultCodegen implem // 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)); + LOGGER.warn(name + " (reserved word) cannot be used as model name. Renamed to " + org.openapitools.codegen.utils.StringUtils.camelize("model_" + name)); name = "model_" + name; // e.g. return => ModelReturn (after camelize) } // camelize the model name // phone_number => PhoneNumber - return camelize(name); + return org.openapitools.codegen.utils.StringUtils.camelize(name); } @Override @@ -304,11 +305,11 @@ public class JavascriptClosureAngularClientCodegen extends DefaultCodegen implem throw new RuntimeException("Empty method/operation name (operationId) not allowed"); } - operationId = camelize(sanitizeName(operationId), true); + operationId = org.openapitools.codegen.utils.StringUtils.camelize(sanitizeName(operationId), true); // method name cannot use reserved keyword, e.g. return if (isReservedWord(operationId)) { - String newOperationId = camelize("call_" + operationId, true); + String newOperationId = org.openapitools.codegen.utils.StringUtils.camelize("call_" + operationId, true); LOGGER.warn(operationId + " (reserved word) cannot be used as method name. Renamed to " + newOperationId); return newOperationId; } diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/JavascriptFlowtypedClientCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/JavascriptFlowtypedClientCodegen.java index cc0c78c387..003b2f305c 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/JavascriptFlowtypedClientCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/JavascriptFlowtypedClientCodegen.java @@ -29,6 +29,7 @@ import org.openapitools.codegen.utils.ModelUtils; import java.text.SimpleDateFormat; import java.util.*; + public class JavascriptFlowtypedClientCodegen extends AbstractTypeScriptClientCodegen { private static final SimpleDateFormat SNAPSHOT_SUFFIX_FORMAT = new SimpleDateFormat("yyyyMMddHHmm", Locale.ROOT); @@ -185,7 +186,7 @@ public class JavascriptFlowtypedClientCodegen extends AbstractTypeScriptClientCo Info info = openAPI.getInfo(); if (StringUtils.isBlank(npmName) && info.getTitle() != null) { // when projectName is not specified, generate it from info.title - npmName = sanitizeName(dashize(info.getTitle())); + npmName = sanitizeName(org.openapitools.codegen.utils.StringUtils.dashize(info.getTitle())); } if (StringUtils.isBlank(npmVersion)) { // when projectVersion is not specified, use info.version diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/KotlinSpringServerCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/KotlinSpringServerCodegen.java new file mode 100644 index 0000000000..c06863cc37 --- /dev/null +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/KotlinSpringServerCodegen.java @@ -0,0 +1,501 @@ +/* + * Copyright 2018 OpenAPI-Generator Contributors (https://openapi-generator.tech) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.openapitools.codegen.languages; + +import com.google.common.collect.ImmutableMap; +import com.samskivert.mustache.Mustache; +import com.samskivert.mustache.Template; +import io.swagger.v3.oas.models.OpenAPI; +import org.openapitools.codegen.*; +import org.openapitools.codegen.languages.features.BeanValidationFeatures; +import org.openapitools.codegen.utils.URLPathUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.io.File; +import java.io.IOException; +import java.io.Writer; +import java.net.URL; +import java.util.*; +import java.util.regex.Matcher; + + +public class KotlinSpringServerCodegen extends AbstractKotlinCodegen + implements BeanValidationFeatures { + + private static Logger LOGGER = + LoggerFactory.getLogger(KotlinSpringServerCodegen.class); + + private static final HashSet VARIABLE_RESERVED_WORDS = + new HashSet(Arrays.asList( + "ApiClient", + "ApiException", + "ApiResponse" + )); + + public static final String TITLE = "title"; + public static final String LAMBDA = "lambda"; + public static final String SERVER_PORT = "serverPort"; + public static final String BASE_PACKAGE = "basePackage"; + public static final String SPRING_BOOT = "spring-boot"; + public static final String EXCEPTION_HANDLER = "exceptionHandler"; + public static final String GRADLE_BUILD_FILE = "gradleBuildFile"; + public static final String SWAGGER_ANNOTATIONS = "swaggerAnnotations"; + public static final String SERVICE_INTERFACE = "serviceInterface"; + public static final String SERVICE_IMPLEMENTATION = "serviceImplementation"; + + private String basePackage; + private String serverPort = "8080"; + private String title = "OpenAPI Kotlin Spring"; + private String resourceFolder = "src/main/resources"; + private boolean useBeanValidation = true; + private boolean exceptionHandler = true; + private boolean gradleBuildFile = true; + private boolean swaggerAnnotations = false; + private boolean serviceInterface = false; + private boolean serviceImplementation = false; + + public KotlinSpringServerCodegen() { + super(); + + reservedWords.addAll(VARIABLE_RESERVED_WORDS); + + outputFolder = "generated-code/kotlin-spring"; + apiTestTemplateFiles.clear(); // TODO: add test template + embeddedTemplateDir = templateDir = "kotlin-spring"; + + artifactId = "openapi-spring"; + basePackage = "org.openapitools"; + apiPackage = "org.openapitools.api"; + modelPackage = "org.openapitools.model"; + + addOption(TITLE, "server title name or client service name", title); + addOption(BASE_PACKAGE, "base package for generated code", basePackage); + addOption(SERVER_PORT, "configuration the port in which the sever is to run on", serverPort); + addOption(CodegenConstants.MODEL_PACKAGE, "model package for generated code", modelPackage); + addOption(CodegenConstants.API_PACKAGE, "api package for generated code", apiPackage); + addSwitch(EXCEPTION_HANDLER, "generate default global exception handlers", exceptionHandler); + addSwitch(GRADLE_BUILD_FILE, "generate a gradle build file using the Kotlin DSL", gradleBuildFile); + addSwitch(SWAGGER_ANNOTATIONS, "generate swagger annotations to go alongside controllers and models", swaggerAnnotations); + addSwitch(SERVICE_INTERFACE, "generate service interfaces to go alongside controllers. In most " + + "cases this option would be used to update an existing project, so not to override implementations. " + + "Useful to help facilitate the generation gap pattern", serviceInterface); + addSwitch(SERVICE_IMPLEMENTATION, "generate stub service implementations that extends service " + + "interfaces. If this is set to true service interfaces will also be generated", serviceImplementation); + addSwitch(USE_BEANVALIDATION, "Use BeanValidation API annotations to validate data types", useBeanValidation); + + supportedLibraries.put(SPRING_BOOT, "Spring-boot Server application."); + setLibrary(SPRING_BOOT); + + CliOption cliOpt = new CliOption(CodegenConstants.LIBRARY, "library template (sub-template) to use"); + cliOpt.setDefault(SPRING_BOOT); + cliOpt.setEnum(supportedLibraries); + cliOptions.add(cliOpt); + } + + public String getResourceFolder() { + return this.resourceFolder; + } + + public void setResourceFolder(String resourceFolder) { + this.resourceFolder = resourceFolder; + } + + public String getBasePackage() { + return this.basePackage; + } + + public void setBasePackage(String basePackage) { + this.basePackage = basePackage; + } + + public String getServerPort() { + return this.serverPort; + } + + public void setServerPort(String serverPort) { + this.serverPort = serverPort; + } + + public boolean getExceptionHandler() { + return this.exceptionHandler; + } + + public void setExceptionHandler(boolean exceptionHandler) { + this.exceptionHandler = exceptionHandler; + } + + public boolean getGradleBuildFile() { + return this.gradleBuildFile; + } + + public void setGradleBuildFile(boolean gradleBuildFile) { + this.gradleBuildFile = gradleBuildFile; + } + + public boolean getSwaggerAnnotations() { + return this.swaggerAnnotations; + } + + public void setSwaggerAnnotations(boolean swaggerAnnotations) { + this.swaggerAnnotations = swaggerAnnotations; + } + + public boolean getServiceInterface() { + return this.serviceInterface; + } + + public void setServiceInterface(boolean serviceInterface) { + this.serviceInterface = serviceInterface; + } + + public boolean getServiceImplementation() { + return this.serviceImplementation; + } + + public void setServiceImplementation(boolean serviceImplementation) { + this.serviceImplementation = serviceImplementation; + } + + public boolean getUseBeanValidation() { + return this.useBeanValidation; + } + + @Override + public void setUseBeanValidation(boolean useBeanValidation) { + this.useBeanValidation = useBeanValidation; + } + + @Override + public CodegenType getTag() { + return CodegenType.SERVER; + } + + @Override + public String getName() { + return "kotlin-spring"; + } + + @Override + public String getHelp() { + return "Generates a Kotlin Spring application."; + } + + @Override + public void processOpts() { + super.processOpts(); + + typeMapping.put("date", "java.time.LocalDate"); + typeMapping.put("date-time", "java.time.OffsetDateTime"); + typeMapping.put("Date", "java.time.LocalDate"); + typeMapping.put("DateTime", "java.time.OffsetDateTime"); + + importMapping.put("Date", "java.time.LocalDate"); + importMapping.put("DateTime", "java.time.OffsetDateTime"); + + // optional jackson mappings for BigDecimal support + importMapping.put("ToStringSerializer", "com.fasterxml.jackson.databind.ser.std.ToStringSerializer"); + importMapping.put("JsonSerialize", "com.fasterxml.jackson.databind.annotation.JsonSerialize"); + + // Swagger import mappings + importMapping.put("ApiModel", "io.swagger.annotations.ApiModel"); + importMapping.put("ApiModelProperty", "io.swagger.annotations.ApiModelProperty"); + + // Jackson import mappings + importMapping.put("JsonValue", "com.fasterxml.jackson.annotation.JsonValue"); + importMapping.put("JsonCreator", "com.fasterxml.jackson.annotation.JsonCreator"); + importMapping.put("JsonProperty", "com.fasterxml.jackson.annotation.JsonProperty"); + importMapping.put("JsonSubTypes", "com.fasterxml.jackson.annotation.JsonSubTypes"); + importMapping.put("JsonTypeInfo", "com.fasterxml.jackson.annotation.JsonTypeInfo"); + // import JsonCreator if JsonProperty is imported + // used later in recursive import in postProcessingModels + importMapping.put("com.fasterxml.jackson.annotation.JsonProperty", "com.fasterxml.jackson.annotation.JsonCreator"); + + // TODO when adding invokerPackage + //importMapping.put("StringUtil", invokerPackage + ".StringUtil"); + + if (!additionalProperties.containsKey(CodegenConstants.LIBRARY)) { + additionalProperties.put(CodegenConstants.LIBRARY, library); + } + + if (additionalProperties.containsKey(BASE_PACKAGE)) { + this.setBasePackage((String) additionalProperties.get(BASE_PACKAGE)); + } else { + additionalProperties.put(BASE_PACKAGE, basePackage); + } + + if (additionalProperties.containsKey(SERVER_PORT)) { + this.setServerPort((String) additionalProperties.get(SERVER_PORT)); + } else { + additionalProperties.put(SERVER_PORT, serverPort); + } + + if (additionalProperties.containsKey(EXCEPTION_HANDLER)) { + this.setExceptionHandler(Boolean.valueOf(additionalProperties.get(EXCEPTION_HANDLER).toString())); + } + writePropertyBack(EXCEPTION_HANDLER, exceptionHandler); + + if (additionalProperties.containsKey(GRADLE_BUILD_FILE)) { + this.setGradleBuildFile(Boolean.valueOf(additionalProperties.get(GRADLE_BUILD_FILE).toString())); + } + writePropertyBack(GRADLE_BUILD_FILE, gradleBuildFile); + + if (additionalProperties.containsKey(SWAGGER_ANNOTATIONS)) { + this.setSwaggerAnnotations(Boolean.valueOf(additionalProperties.get(SWAGGER_ANNOTATIONS).toString())); + } + writePropertyBack(SWAGGER_ANNOTATIONS, swaggerAnnotations); + + if (additionalProperties.containsKey(SERVICE_INTERFACE)) { + this.setServiceInterface(Boolean.valueOf(additionalProperties.get(SERVICE_INTERFACE).toString())); + } + writePropertyBack(SERVICE_INTERFACE, serviceInterface); + + if (additionalProperties.containsKey(SERVICE_IMPLEMENTATION)) { + this.setServiceImplementation(Boolean.valueOf(additionalProperties.get(SERVICE_IMPLEMENTATION).toString())); + } + writePropertyBack(SERVICE_IMPLEMENTATION, serviceImplementation); + + if (additionalProperties.containsKey(USE_BEANVALIDATION)) { + this.setUseBeanValidation(convertPropertyToBoolean(USE_BEANVALIDATION)); + } + writePropertyBack(USE_BEANVALIDATION, useBeanValidation); + + modelTemplateFiles.put("model.mustache", ".kt"); + apiTemplateFiles.put("api.mustache", ".kt"); + supportingFiles.add(new SupportingFile("README.mustache", "", "README.md")); + + if (this.serviceInterface) { + apiTemplateFiles.put("service.mustache", "Service.kt"); + } else if (this.serviceImplementation) { + LOGGER.warn("If you set `serviceImplementation` to true, `serviceInterface` will also be set to true"); + additionalProperties.put(SERVICE_INTERFACE, true); + apiTemplateFiles.put("service.mustache", "Service.kt"); + apiTemplateFiles.put("serviceImpl.mustache", "ServiceImpl.kt"); + } + + if (this.exceptionHandler) { + supportingFiles.add(new SupportingFile("exceptions.mustache", + sanitizeDirectory(sourceFolder + File.separator + apiPackage), "Exceptions.kt")); + } + + if (library.equals(SPRING_BOOT)) { + LOGGER.info("Setup code generator for Kotlin Spring Boot"); + supportingFiles.add(new SupportingFile("pom.mustache", "", "pom.xml")); + + if (this.gradleBuildFile) { + supportingFiles.add(new SupportingFile("buildGradleKts.mustache", "", "build.gradle.kts")); + supportingFiles.add(new SupportingFile("settingsGradle.mustache", "", "settings.gradle")); + } + + supportingFiles.add(new SupportingFile("application.mustache", resourceFolder, "application.yaml")); + supportingFiles.add(new SupportingFile("springBootApplication.mustache", + sanitizeDirectory(sourceFolder + File.separator + basePackage), "Application.kt")); + } + + addMustacheLambdas(additionalProperties); + + // spring uses the jackson lib, and we disallow configuration. + additionalProperties.put("jackson", "true"); + } + + private void addMustacheLambdas(final Map objs) { + Map lambdas = + new ImmutableMap.Builder() + .put("escapeDoubleQuote", new EscapeLambda("\"", "\\\"")) + .build(); + + if (objs.containsKey(LAMBDA)) { + LOGGER.warn("The lambda property is a reserved word, and will be overwritten!"); + } + objs.put(LAMBDA, lambdas); + } + + @Override + public void preprocessOpenAPI(OpenAPI openAPI) { + super.preprocessOpenAPI(openAPI); + + if (!additionalProperties.containsKey(TITLE)) { + // The purpose of the title is for: + // - README documentation + // - The spring.application.name + // - And linking the @RequestMapping + // This is an additional step we add when pre-processing the API spec, if + // there is no user configuration set for the `title` of the project, + // we try build and normalise a title from the API spec itself. + String title = openAPI.getInfo().getTitle(); + + // Drop any API suffix + if (title != null) { + title = title.trim().replace(" ", "-"); + if (title.toUpperCase(Locale.ROOT).endsWith("API")) + title = title.substring(0, title.length() - 3); + + this.title = camelize(sanitizeName(title), true); + } + additionalProperties.put(TITLE, this.title); + } + + if (!additionalProperties.containsKey(SERVER_PORT)) { + URL url = URLPathUtils.getServerURL(openAPI); + this.additionalProperties.put(SERVER_PORT, URLPathUtils.getPort(url, 8080)); + } + + // TODO: Handle tags + } + + @Override + public void postProcessModelProperty(CodegenModel model, CodegenProperty property) { + super.postProcessModelProperty(model, property); + + if ("null".equals(property.example)) { + property.example = null; + } + + //Add imports for Jackson + if (!Boolean.TRUE.equals(model.isEnum)) { + model.imports.add("JsonProperty"); + if (Boolean.TRUE.equals(model.hasEnums)) { + model.imports.add("JsonValue"); + } + + } else { + //Needed imports for Jackson's JsonCreator + if (additionalProperties.containsKey("jackson")) { + model.imports.add("JsonCreator"); + } + } + + } + + @Override + public Map postProcessModelsEnum(Map objs) { + objs = super.postProcessModelsEnum(objs); + + //Add imports for Jackson + List> imports = (List>) objs.get("imports"); + List models = (List) objs.get("models"); + + models.stream() + .map(mo -> (Map) mo) + .map(mo -> (CodegenModel) mo.get("model")) + .filter(cm -> Boolean.TRUE.equals(cm.isEnum) && cm.allowableValues != null) + .forEach(cm -> { + cm.imports.add(importMapping.get("JsonValue")); + Map item = new HashMap<>(); + item.put("import", importMapping.get("JsonValue")); + imports.add(item); + }); + + return objs; + } + + @Override + public Map postProcessOperationsWithModels(Map objs, List allModels) { + Map operations = (Map) objs.get("operations"); + if (operations != null) { + List ops = (List) operations.get("operation"); + ops.forEach(operation -> { + List responses = operation.responses; + if (responses != null) { + responses.forEach(resp -> { + + if ("0".equals(resp.code)) { + resp.code = "200"; + } + + doDataTypeAssignment(resp.dataType, new DataTypeAssigner() { + @Override + public void setReturnType(final String returnType) { + resp.dataType = returnType; + } + + @Override + public void setReturnContainer(final String returnContainer) { + resp.containerType = returnContainer; + } + }); + }); + } + doDataTypeAssignment(operation.returnType, new DataTypeAssigner() { + + @Override + public void setReturnType(final String returnType) { + operation.returnType = returnType; + } + + @Override + public void setReturnContainer(final String returnContainer) { + operation.returnContainer = returnContainer; + } + }); +// if(implicitHeaders){ +// removeHeadersFromAllParams(operation.allParams); +// } + }); + } + + return objs; + } + + private interface DataTypeAssigner { + void setReturnType(String returnType); + + void setReturnContainer(String returnContainer); + } + + /** + * @param returnType The return type that needs to be converted + * @param dataTypeAssigner An object that will assign the data to the respective fields in the model. + */ + private void doDataTypeAssignment(final String returnType, DataTypeAssigner dataTypeAssigner) { + if (returnType == null) { + dataTypeAssigner.setReturnType("Unit"); + } else if (returnType.startsWith("kotlin.Array")) { + int end = returnType.lastIndexOf(">"); + if (end > 0) { + dataTypeAssigner.setReturnType(returnType.substring("kotlin.Array<".length(), end).trim()); + dataTypeAssigner.setReturnContainer("List"); + } + } else if (returnType.startsWith("kotlin.collections.Map")) { + int end = returnType.lastIndexOf(">"); + if (end > 0) { + dataTypeAssigner.setReturnType(returnType.substring("kotlin.collections.Map<".length(), end).split(",")[1].trim()); + dataTypeAssigner.setReturnContainer("Map"); + } + } + } + + private static String sanitizeDirectory(String in) { + return in.replace(".", File.separator); + } + + // TODO could probably be made more generic, and moved to the `mustache` package if required by other components. + private static class EscapeLambda implements Mustache.Lambda { + private String from; + private String to; + + EscapeLambda(final String from, final String to) { + this.from = from; + this.to = Matcher.quoteReplacement(to); + } + + @Override + public void execute(Template.Fragment fragment, Writer writer) throws IOException { + writer.write(fragment.execute().replaceAll(from, to)); + } + } +} diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/LuaClientCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/LuaClientCodegen.java index c41deb8be3..9a34537902 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/LuaClientCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/LuaClientCodegen.java @@ -43,6 +43,7 @@ import java.util.ListIterator; import java.util.Locale; import java.util.Map; + public class LuaClientCodegen extends DefaultCodegen implements CodegenConfig { private static final Logger LOGGER = LoggerFactory.getLogger(LuaClientCodegen.class); @@ -202,7 +203,7 @@ public class LuaClientCodegen extends DefaultCodegen implements CodegenConfig { if (this.reservedWordsMappings().containsKey(name)) { return this.reservedWordsMappings().get(name); } - return camelize(name) + '_'; + return org.openapitools.codegen.utils.StringUtils.camelize(name) + '_'; } @Override @@ -225,7 +226,7 @@ public class LuaClientCodegen extends DefaultCodegen implements CodegenConfig { // convert variable name to snake case // PetId => pet_id - name = underscore(name); + name = org.openapitools.codegen.utils.StringUtils.underscore(name); // for reserved word or word starting with number, append _ if (isReservedWord(name)) @@ -272,7 +273,7 @@ public class LuaClientCodegen extends DefaultCodegen implements CodegenConfig { name = "model_" + name; // e.g. 200Response => Model200Response (after camelize) } - return underscore(name); + return org.openapitools.codegen.utils.StringUtils.underscore(name); } @Override @@ -281,7 +282,7 @@ public class LuaClientCodegen extends DefaultCodegen implements CodegenConfig { name = name.replaceAll("-", "_"); // FIXME: a parameter should not be assigned. Also declare the methods parameters as 'final'. // e.g. PetApi.lua => pet_api.lua - return underscore(name) + "_api"; + return org.openapitools.codegen.utils.StringUtils.underscore(name) + "_api"; } @Override @@ -338,7 +339,7 @@ public class LuaClientCodegen extends DefaultCodegen implements CodegenConfig { @Override public String toApiName(String name) { - return underscore(super.toApiName(name)); + return org.openapitools.codegen.utils.StringUtils.underscore(super.toApiName(name)); } @Override @@ -390,11 +391,11 @@ public class LuaClientCodegen extends DefaultCodegen implements CodegenConfig { // method name cannot use reserved keyword, e.g. return if (isReservedWord(sanitizedOperationId)) { - LOGGER.warn(operationId + " (reserved word) cannot be used as method name. Renamed to " + underscore("call_" + operationId)); + LOGGER.warn(operationId + " (reserved word) cannot be used as method name. Renamed to " + org.openapitools.codegen.utils.StringUtils.underscore("call_" + operationId)); sanitizedOperationId = "call_" + sanitizedOperationId; } - return underscore(sanitizedOperationId); + return org.openapitools.codegen.utils.StringUtils.underscore(sanitizedOperationId); } @Override @@ -529,7 +530,7 @@ public class LuaClientCodegen extends DefaultCodegen implements CodegenConfig { } // string - String enumName = sanitizeName(underscore(name).toUpperCase(Locale.ROOT)); + String enumName = sanitizeName(org.openapitools.codegen.utils.StringUtils.underscore(name).toUpperCase(Locale.ROOT)); enumName = enumName.replaceFirst("^_", ""); enumName = enumName.replaceFirst("_$", ""); @@ -542,7 +543,7 @@ public class LuaClientCodegen extends DefaultCodegen implements CodegenConfig { @Override public String toEnumName(CodegenProperty property) { - String enumName = underscore(toModelName(property.name)).toUpperCase(Locale.ROOT); + String enumName = org.openapitools.codegen.utils.StringUtils.underscore(toModelName(property.name)).toUpperCase(Locale.ROOT); // remove [] for array or map of enum enumName = enumName.replace("[]", ""); diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/ObjcClientCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/ObjcClientCodegen.java index 6800e3af38..4662fd132c 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/ObjcClientCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/ObjcClientCodegen.java @@ -43,6 +43,9 @@ import java.util.Locale; import java.util.Map; import java.util.Set; +import org.apache.commons.lang3.StringUtils; + + public class ObjcClientCodegen extends DefaultCodegen implements CodegenConfig { private static final Logger LOGGER = LoggerFactory.getLogger(ObjcClientCodegen.class); @@ -429,7 +432,7 @@ public class ObjcClientCodegen extends DefaultCodegen implements CodegenConfig { // model name starts with number /* no need for the fix below as objc model starts with prefix (e.g. SWG) if (type.matches("^\\d.*")) { - LOGGER.warn(type + " (model name starts with number) cannot be used as model name. Renamed to " + camelize("model_" + type)); + LOGGER.warn(type + " (model name starts with number) cannot be used as model name. Renamed to " + org.openapitools.codegen.utils.StringUtils.camelize("model_" + type)); type = "model_" + type; // e.g. 200Response => Model200Response (after camelize) } */ @@ -453,7 +456,7 @@ public class ObjcClientCodegen extends DefaultCodegen implements CodegenConfig { importMapping.values().contains(type) || defaultIncludes.contains(type) || languageSpecificPrimitives.contains(type)) { - return camelize(type); + return org.openapitools.codegen.utils.StringUtils.camelize(type); } // custom classes else { @@ -465,7 +468,7 @@ public class ObjcClientCodegen extends DefaultCodegen implements CodegenConfig { type = modelNamePrefix + "_" + type; } - return classPrefix + camelize(type); // add class prefix + return classPrefix + org.openapitools.codegen.utils.StringUtils.camelize(type); // add class prefix } } @@ -526,12 +529,12 @@ public class ObjcClientCodegen extends DefaultCodegen implements CodegenConfig { @Override public String toApiName(String name) { - return classPrefix + camelize(name) + "Api"; + return classPrefix + org.openapitools.codegen.utils.StringUtils.camelize(name) + "Api"; } @Override public String toApiFilename(String name) { - return classPrefix + camelize(name) + "Api"; + return classPrefix + org.openapitools.codegen.utils.StringUtils.camelize(name) + "Api"; } @Override @@ -556,7 +559,7 @@ public class ObjcClientCodegen extends DefaultCodegen implements CodegenConfig { // camelize (lower first character) the variable name // e.g. `pet_id` to `petId` - name = camelize(name, true); + name = org.openapitools.codegen.utils.StringUtils.camelize(name, true); // for reserved word or word starting with number, prepend `_` if (isReservedWord(name) || name.matches("^\\d.*")) { @@ -601,11 +604,11 @@ public class ObjcClientCodegen extends DefaultCodegen implements CodegenConfig { // method name cannot use reserved keyword, e.g. return if (isReservedWord(operationId)) { - LOGGER.warn(operationId + " (reserved word) cannot be used as method name. Renamed to " + camelize(sanitizeName("call_" + operationId), true)); + LOGGER.warn(operationId + " (reserved word) cannot be used as method name. Renamed to " + org.openapitools.codegen.utils.StringUtils.camelize(sanitizeName("call_" + operationId), true)); operationId = "call_" + operationId; } - return camelize(sanitizeName(operationId), true); + return org.openapitools.codegen.utils.StringUtils.camelize(sanitizeName(operationId), true); } public void setClassPrefix(String classPrefix) { @@ -644,7 +647,7 @@ public class ObjcClientCodegen extends DefaultCodegen implements CodegenConfig { for (CodegenOperation operation : ops) { if (!operation.allParams.isEmpty()) { String firstParamName = operation.allParams.get(0).paramName; - operation.vendorExtensions.put("firstParamAltName", camelize(firstParamName)); + operation.vendorExtensions.put("firstParamAltName", org.openapitools.codegen.utils.StringUtils.camelize(firstParamName)); } } } @@ -654,7 +657,7 @@ public class ObjcClientCodegen extends DefaultCodegen implements CodegenConfig { @Override public void postProcessModelProperty(CodegenModel model, CodegenProperty schema) { super.postProcessModelProperty(model, schema); - schema.vendorExtensions.put("x-uppercaseName", camelize(schema.name)); + schema.vendorExtensions.put("x-uppercaseName", org.openapitools.codegen.utils.StringUtils.camelize(schema.name)); } /** diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/PerlClientCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/PerlClientCodegen.java index 21ccb6aad0..1fcf07a9ed 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/PerlClientCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/PerlClientCodegen.java @@ -33,6 +33,7 @@ import java.util.regex.Matcher; import org.apache.commons.lang3.StringUtils; + public class PerlClientCodegen extends DefaultCodegen implements CodegenConfig { private static final Logger LOGGER = LoggerFactory.getLogger(PerlClientCodegen.class); @@ -276,7 +277,7 @@ public class PerlClientCodegen extends DefaultCodegen implements CodegenConfig { public String toVarName(String name) { // return the name in underscore style // PhoneNumber => phone_number - name = underscore(name); // FIXME: a parameter should not be assigned. Also declare the methods parameters as 'final'. + name = org.openapitools.codegen.utils.StringUtils.underscore(name); // FIXME: a parameter should not be assigned. Also declare the methods parameters as 'final'. // parameter name starting with number won't compile // need to escape it by appending _ at the beginning @@ -298,13 +299,13 @@ public class PerlClientCodegen extends DefaultCodegen implements CodegenConfig { // model name cannot use reserved keyword if (isReservedWord(name)) { - LOGGER.warn(name + " (reserved word) cannot be used as model name. Renamed to " + camelize("model_" + name)); + LOGGER.warn(name + " (reserved word) cannot be used as model name. Renamed to " + org.openapitools.codegen.utils.StringUtils.camelize("model_" + name)); name = "model_" + name; } // 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)); + LOGGER.warn(name + " (model name starts with number) cannot be used as model name. Renamed to " + org.openapitools.codegen.utils.StringUtils.camelize("model_" + name)); name = "model_" + name; // e.g. 200Response => Model200Response (after camelize) } @@ -319,7 +320,7 @@ public class PerlClientCodegen extends DefaultCodegen implements CodegenConfig { // camelize the model name // phone_number => PhoneNumber - return camelize(name); + return org.openapitools.codegen.utils.StringUtils.camelize(name); } @Override @@ -354,7 +355,7 @@ public class PerlClientCodegen extends DefaultCodegen implements CodegenConfig { name = name.replaceAll("-", "_"); // FIXME: a parameter should not be assigned. Also declare the methods parameters as 'final'. // e.g. phone_number_api.rb => PhoneNumberApi.rb - return camelize(name) + "Api"; + return org.openapitools.codegen.utils.StringUtils.camelize(name) + "Api"; } @Override @@ -363,32 +364,32 @@ public class PerlClientCodegen extends DefaultCodegen implements CodegenConfig { return "DefaultApi"; } // e.g. phone_number_api => PhoneNumberApi - return camelize(name) + "Api"; + return org.openapitools.codegen.utils.StringUtils.camelize(name) + "Api"; } @Override public String toOperationId(String operationId) { //rename to empty_function_name_1 (e.g.) if method name is empty if (StringUtils.isEmpty(operationId)) { - operationId = underscore("empty_function_name_" + emptyFunctionNameCounter++); + operationId = org.openapitools.codegen.utils.StringUtils.underscore("empty_function_name_" + emptyFunctionNameCounter++); LOGGER.warn("Empty method name (operationId) found. Renamed to " + operationId); return operationId; } // method name cannot use reserved keyword, e.g. return if (isReservedWord(operationId)) { - LOGGER.warn(operationId + " (reserved word) cannot be used as method name. Renamed to " + underscore(sanitizeName("call_" + operationId))); - return underscore(sanitizeName("call_" + operationId)); + LOGGER.warn(operationId + " (reserved word) cannot be used as method name. Renamed to " + org.openapitools.codegen.utils.StringUtils.underscore(sanitizeName("call_" + operationId))); + return org.openapitools.codegen.utils.StringUtils.underscore(sanitizeName("call_" + operationId)); } // operationId starts with a number if (operationId.matches("^\\d.*")) { - LOGGER.warn(operationId + " (starting with a number) cannot be used as method name. Renamed to " + underscore(sanitizeName("call_" + operationId))); + LOGGER.warn(operationId + " (starting with a number) cannot be used as method name. Renamed to " + org.openapitools.codegen.utils.StringUtils.underscore(sanitizeName("call_" + operationId))); operationId = "call_" + operationId; } - //return underscore(operationId).replaceAll("[^A-Za-z0-9_]", ""); - return underscore(sanitizeName(operationId)); + //return org.openapitools.codegen.utils.StringUtils.underscore(operationId).replaceAll("[^A-Za-z0-9_]", ""); + return org.openapitools.codegen.utils.StringUtils.underscore(sanitizeName(operationId)); } public void setModuleName(String moduleName) { diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/PhpLaravelServerCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/PhpLaravelServerCodegen.java index 85bd049767..5c67685d97 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/PhpLaravelServerCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/PhpLaravelServerCodegen.java @@ -22,6 +22,7 @@ import org.openapitools.codegen.*; import java.io.File; import java.util.*; + public class PhpLaravelServerCodegen extends AbstractPhpCodegen { protected String apiVersion = "1.0.0"; @@ -240,7 +241,7 @@ public class PhpLaravelServerCodegen extends AbstractPhpCodegen { return "DefaultController"; } - return camelize(name, false) + "Controller"; + return org.openapitools.codegen.utils.StringUtils.camelize(name, false) + "Controller"; } protected String controllerFileFolder() { @@ -262,6 +263,6 @@ public class PhpLaravelServerCodegen extends AbstractPhpCodegen { return "DefaultController"; } - return camelize(name, false) + "Controller"; + return org.openapitools.codegen.utils.StringUtils.camelize(name, false) + "Controller"; } } diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/PhpSilexServerCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/PhpSilexServerCodegen.java index 84cf10331c..e8866e0580 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/PhpSilexServerCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/PhpSilexServerCodegen.java @@ -36,6 +36,7 @@ import java.util.Map; import org.apache.commons.lang3.StringUtils; + public class PhpSilexServerCodegen extends DefaultCodegen implements CodegenConfig { protected String invokerPackage; protected String groupId = "org.openapitools"; @@ -45,7 +46,7 @@ public class PhpSilexServerCodegen extends DefaultCodegen implements CodegenConf public PhpSilexServerCodegen() { super(); - invokerPackage = camelize("OpenAPIServer"); + invokerPackage = org.openapitools.codegen.utils.StringUtils.camelize("OpenAPIServer"); String packageName = "OpenAPIServer"; modelPackage = "lib" + File.separator + "models"; apiPackage = "lib"; @@ -199,7 +200,7 @@ public class PhpSilexServerCodegen extends DefaultCodegen implements CodegenConf public String toVarName(String name) { // return the name in underscore style // PhoneNumber => phone_number - name = underscore(name); // FIXME: a parameter should not be assigned. Also declare the methods parameters as 'final'. + name = org.openapitools.codegen.utils.StringUtils.underscore(name); // FIXME: a parameter should not be assigned. Also declare the methods parameters as 'final'. // parameter name starting with number won't compile // need to escape it by appending _ at the beginning @@ -225,7 +226,7 @@ public class PhpSilexServerCodegen extends DefaultCodegen implements CodegenConf // camelize the model name // phone_number => PhoneNumber - return camelize(name); + return org.openapitools.codegen.utils.StringUtils.camelize(name); } @Override @@ -258,7 +259,7 @@ public class PhpSilexServerCodegen extends DefaultCodegen implements CodegenConf for (int i = 0; i < items.length; ++i) { if (items[i].matches("^\\{(.*)\\}$")) { // wrap in {} // camelize path variable - items[i] = "{" + camelize(items[i].substring(1, items[i].length() - 1), true) + "}"; + items[i] = "{" + org.openapitools.codegen.utils.StringUtils.camelize(items[i].substring(1, items[i].length() - 1), true) + "}"; } } diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/PhpSlimServerCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/PhpSlimServerCodegen.java index 69c6bc6d67..ea3549c7af 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/PhpSlimServerCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/PhpSlimServerCodegen.java @@ -35,8 +35,11 @@ import java.util.Map; public class PhpSlimServerCodegen extends AbstractPhpCodegen { private static final Logger LOGGER = LoggerFactory.getLogger(PhpSlimServerCodegen.class); + public static final String PHPCS_STANDARD = "phpcsStandard"; + protected String groupId = "org.openapitools"; protected String artifactId = "openapi-server"; + protected String phpcsStandard = "PSR12"; public PhpSlimServerCodegen() { super(); @@ -70,6 +73,9 @@ public class PhpSlimServerCodegen extends AbstractPhpCodegen { break; } } + + cliOptions.add(new CliOption(PHPCS_STANDARD, "PHP CodeSniffer option. Accepts name or path of the coding standard to use.") + .defaultValue("PSR12")); } @Override @@ -109,6 +115,12 @@ public class PhpSlimServerCodegen extends AbstractPhpCodegen { public void processOpts() { super.processOpts(); + if (additionalProperties.containsKey(PHPCS_STANDARD)) { + this.setPhpcsStandard((String) additionalProperties.get(PHPCS_STANDARD)); + } else { + additionalProperties.put(PHPCS_STANDARD, phpcsStandard); + } + supportingFiles.add(new SupportingFile("README.mustache", "", "README.md")); supportingFiles.add(new SupportingFile("composer.mustache", "", "composer.json")); supportingFiles.add(new SupportingFile("index.mustache", "", "index.php")); @@ -148,4 +160,8 @@ public class PhpSlimServerCodegen extends AbstractPhpCodegen { return objs; } + public void setPhpcsStandard(String phpcsStandard) { + this.phpcsStandard = phpcsStandard; + } + } 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 5baf8b5d73..0714247c8a 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 @@ -28,6 +28,7 @@ import org.slf4j.LoggerFactory; import java.io.File; import java.util.*; + public class PhpSymfonyServerCodegen extends AbstractPhpCodegen implements CodegenConfig { @SuppressWarnings("hiding") private static final Logger LOGGER = LoggerFactory.getLogger(PhpSymfonyServerCodegen.class); @@ -563,14 +564,14 @@ public class PhpSymfonyServerCodegen extends AbstractPhpCodegen implements Codeg if (name.isEmpty()) { return "DefaultApiInterface"; } - return camelize(name, false) + "ApiInterface"; + return org.openapitools.codegen.utils.StringUtils.camelize(name, false) + "ApiInterface"; } protected String toControllerName(String name) { if (name.isEmpty()) { return "DefaultController"; } - return camelize(name, false) + "Controller"; + return org.openapitools.codegen.utils.StringUtils.camelize(name, false) + "Controller"; } protected String toSymfonyService(String name) { diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/PowerShellClientCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/PowerShellClientCodegen.java index f16a7528fa..86536a3c15 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/PowerShellClientCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/PowerShellClientCodegen.java @@ -329,19 +329,19 @@ public class PowerShellClientCodegen extends DefaultCodegen implements CodegenCo // 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)); + LOGGER.warn(name + " (reserved word) cannot be used as model name. Renamed to " + org.openapitools.codegen.utils.StringUtils.camelize("model_" + name)); name = "model_" + name; // e.g. return => ModelReturn (after camelize) } // model name starts with number if (name.matches("^\\d.*")) { - LOGGER.warn(name + " (model name starts with number) cannot be used as model name. Renamed to " + camelize("model_" + name)); + LOGGER.warn(name + " (model name starts with number) cannot be used as model name. Renamed to " + org.openapitools.codegen.utils.StringUtils.camelize("model_" + name)); name = "model_" + name; // e.g. 200Response => Model200Response (after camelize) } // camelize the model name // phone_number => PhoneNumber - return camelize(name); + return org.openapitools.codegen.utils.StringUtils.camelize(name); } @Override @@ -406,11 +406,11 @@ public class PowerShellClientCodegen extends DefaultCodegen implements CodegenCo // method name cannot use reserved keyword, e.g. return if (isReservedWord(operationId)) { - LOGGER.warn(operationId + " (reserved word) cannot be used as method name. Renamed to " + camelize(sanitizeName("call_" + operationId))); + LOGGER.warn(operationId + " (reserved word) cannot be used as method name. Renamed to " + org.openapitools.codegen.utils.StringUtils.camelize(sanitizeName("call_" + operationId))); operationId = "call_" + operationId; } - return camelize(sanitizeName(operationId)); + return org.openapitools.codegen.utils.StringUtils.camelize(sanitizeName(operationId)); } @Override 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 0b8455108e..94db6594f1 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 @@ -42,6 +42,7 @@ import java.util.Locale; import java.util.Map; import java.util.regex.Pattern; + public class PythonClientCodegen extends DefaultCodegen implements CodegenConfig { private static final Logger LOGGER = LoggerFactory.getLogger(PythonClientCodegen.class); @@ -436,7 +437,7 @@ public class PythonClientCodegen extends DefaultCodegen implements CodegenConfig // underscore the variable name // petId => pet_id - name = underscore(name); + name = org.openapitools.codegen.utils.StringUtils.underscore(name); // remove leading underscore name = name.replaceAll("^_*", ""); @@ -468,13 +469,13 @@ public class PythonClientCodegen extends DefaultCodegen implements CodegenConfig // 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)); + LOGGER.warn(name + " (reserved word) cannot be used as model name. Renamed to " + org.openapitools.codegen.utils.StringUtils.camelize("model_" + name)); name = "model_" + name; // e.g. return => ModelReturn (after camelize) } // model name starts with number if (name.matches("^\\d.*")) { - LOGGER.warn(name + " (model name starts with number) cannot be used as model name. Renamed to " + camelize("model_" + name)); + LOGGER.warn(name + " (model name starts with number) cannot be used as model name. Renamed to " + org.openapitools.codegen.utils.StringUtils.camelize("model_" + name)); name = "model_" + name; // e.g. 200Response => Model200Response (after camelize) } @@ -488,14 +489,14 @@ public class PythonClientCodegen extends DefaultCodegen implements CodegenConfig // camelize the model name // phone_number => PhoneNumber - return camelize(name); + return org.openapitools.codegen.utils.StringUtils.camelize(name); } @Override public String toModelFilename(String name) { // underscore the model file name // PhoneNumber => phone_number - return underscore(dropDots(toModelName(name))); + return org.openapitools.codegen.utils.StringUtils.underscore(dropDots(toModelName(name))); } @Override @@ -509,7 +510,7 @@ public class PythonClientCodegen extends DefaultCodegen implements CodegenConfig name = name.replaceAll("-", "_"); // e.g. PhoneNumberApi.py => phone_number_api.py - return underscore(name) + "_api"; + return org.openapitools.codegen.utils.StringUtils.underscore(name) + "_api"; } @Override @@ -523,7 +524,7 @@ public class PythonClientCodegen extends DefaultCodegen implements CodegenConfig return "DefaultApi"; } // e.g. phone_number_api => PhoneNumberApi - return camelize(name) + "Api"; + return org.openapitools.codegen.utils.StringUtils.camelize(name) + "Api"; } @Override @@ -531,7 +532,7 @@ public class PythonClientCodegen extends DefaultCodegen implements CodegenConfig if (name.length() == 0) { return "default_api"; } - return underscore(name) + "_api"; + return org.openapitools.codegen.utils.StringUtils.underscore(name) + "_api"; } @Override @@ -543,17 +544,17 @@ public class PythonClientCodegen extends DefaultCodegen implements CodegenConfig // method name cannot use reserved keyword, e.g. return if (isReservedWord(operationId)) { - LOGGER.warn(operationId + " (reserved word) cannot be used as method name. Renamed to " + underscore(sanitizeName("call_" + operationId))); + LOGGER.warn(operationId + " (reserved word) cannot be used as method name. Renamed to " + org.openapitools.codegen.utils.StringUtils.underscore(sanitizeName("call_" + operationId))); operationId = "call_" + operationId; } // operationId starts with a number if (operationId.matches("^\\d.*")) { - LOGGER.warn(operationId + " (starting with a number) cannot be used as method name. Renamed to " + underscore(sanitizeName("call_" + operationId))); + LOGGER.warn(operationId + " (starting with a number) cannot be used as method name. Renamed to " + org.openapitools.codegen.utils.StringUtils.underscore(sanitizeName("call_" + operationId))); operationId = "call_" + operationId; } - return underscore(sanitizeName(operationId)); + return org.openapitools.codegen.utils.StringUtils.underscore(sanitizeName(operationId)); } public void setPackageName(String packageName) { @@ -583,7 +584,7 @@ public class PythonClientCodegen extends DefaultCodegen implements CodegenConfig */ @SuppressWarnings("static-method") public String generatePackageName(String packageName) { - return underscore(packageName.replaceAll("[^\\w]+", "")); + return org.openapitools.codegen.utils.StringUtils.underscore(packageName.replaceAll("[^\\w]+", "")); } /** diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/PythonFlaskConnexionServerCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/PythonFlaskConnexionServerCodegen.java index 009dfeff8b..a226d78616 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/PythonFlaskConnexionServerCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/PythonFlaskConnexionServerCodegen.java @@ -31,10 +31,10 @@ import org.openapitools.codegen.*; import org.openapitools.codegen.utils.ModelUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; - import java.io.File; import java.util.*; + public class PythonFlaskConnexionServerCodegen extends DefaultCodegen implements CodegenConfig { private static final Logger LOGGER = LoggerFactory.getLogger(PythonFlaskConnexionServerCodegen.class); @@ -246,12 +246,12 @@ public class PythonFlaskConnexionServerCodegen extends DefaultCodegen implements if (name == null || name.length() == 0) { return "DefaultController"; } - return camelize(name, false) + "Controller"; + return org.openapitools.codegen.utils.StringUtils.camelize(name, false) + "Controller"; } @Override public String toApiFilename(String name) { - return underscore(toApiName(name)); + return org.openapitools.codegen.utils.StringUtils.underscore(toApiName(name)); } @Override @@ -405,7 +405,7 @@ public class PythonFlaskConnexionServerCodegen extends DefaultCodegen implements // underscore the variable name // petId => pet_id - name = underscore(name); + name = org.openapitools.codegen.utils.StringUtils.underscore(name); // remove leading underscore name = name.replaceAll("^_*", ""); @@ -433,7 +433,7 @@ public class PythonFlaskConnexionServerCodegen extends DefaultCodegen implements public String toModelFilename(String name) { // underscore the model file name // PhoneNumber => phone_number - return underscore(dropDots(toModelName(name))); + return org.openapitools.codegen.utils.StringUtils.underscore(dropDots(toModelName(name))); } @Override @@ -444,13 +444,13 @@ public class PythonFlaskConnexionServerCodegen extends DefaultCodegen implements // 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)); + LOGGER.warn(name + " (reserved word) cannot be used as model name. Renamed to " + org.openapitools.codegen.utils.StringUtils.camelize("model_" + name)); name = "model_" + name; // e.g. return => ModelReturn (after camelize) } // model name starts with number if (name.matches("^\\d.*")) { - LOGGER.warn(name + " (model name starts with number) cannot be used as model name. Renamed to " + camelize("model_" + name)); + LOGGER.warn(name + " (model name starts with number) cannot be used as model name. Renamed to " + org.openapitools.codegen.utils.StringUtils.camelize("model_" + name)); name = "model_" + name; // e.g. 200Response => Model200Response (after camelize) } @@ -464,7 +464,7 @@ public class PythonFlaskConnexionServerCodegen extends DefaultCodegen implements // camelize the model name // phone_number => PhoneNumber - return camelize(name); + return org.openapitools.codegen.utils.StringUtils.camelize(name); } @Override @@ -476,11 +476,11 @@ public class PythonFlaskConnexionServerCodegen extends DefaultCodegen implements // method name cannot use reserved keyword, e.g. return if (isReservedWord(operationId)) { - LOGGER.warn(operationId + " (reserved word) cannot be used as method name. Renamed to " + underscore(sanitizeName("call_" + operationId))); + LOGGER.warn(operationId + " (reserved word) cannot be used as method name. Renamed to " + org.openapitools.codegen.utils.StringUtils.underscore(sanitizeName("call_" + operationId))); operationId = "call_" + operationId; } - return underscore(sanitizeName(operationId)); + return org.openapitools.codegen.utils.StringUtils.underscore(sanitizeName(operationId)); } /** diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/RClientCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/RClientCodegen.java index 6be3b9814d..49db39f487 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/RClientCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/RClientCodegen.java @@ -28,6 +28,7 @@ import org.slf4j.LoggerFactory; import java.io.File; import java.util.*; + public class RClientCodegen extends DefaultCodegen implements CodegenConfig { private static final Logger LOGGER = LoggerFactory.getLogger(RClientCodegen.class); @@ -172,7 +173,7 @@ public class RClientCodegen extends DefaultCodegen implements CodegenConfig { if (this.reservedWordsMappings().containsKey(name)) { return this.reservedWordsMappings().get(name); } - return camelize(name) + '_'; + return org.openapitools.codegen.utils.StringUtils.camelize(name) + '_'; } @Override @@ -195,7 +196,7 @@ public class RClientCodegen extends DefaultCodegen implements CodegenConfig { // convert variable name to snake case // PetId => pet_id - name = underscore(name); + name = org.openapitools.codegen.utils.StringUtils.underscore(name); // for reserved word or word starting with number, append _ if (isReservedWord(name)) @@ -232,17 +233,17 @@ public class RClientCodegen extends DefaultCodegen implements CodegenConfig { // 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)); + LOGGER.warn(name + " (reserved word) cannot be used as model name. Renamed to " + org.openapitools.codegen.utils.StringUtils.camelize("model_" + name)); name = "model_" + name; // e.g. return => ModelReturn (after camelize) } // model name starts with number if (name.matches("^\\d.*")) { - LOGGER.warn(name + " (model name starts with number) cannot be used as model name. Renamed to " + camelize("model_" + name)); + LOGGER.warn(name + " (model name starts with number) cannot be used as model name. Renamed to " + org.openapitools.codegen.utils.StringUtils.camelize("model_" + name)); name = "model_" + name; // e.g. 200Response => Model200Response (after camelize) } - return camelize(name); + return org.openapitools.codegen.utils.StringUtils.camelize(name); } @Override @@ -251,7 +252,7 @@ public class RClientCodegen extends DefaultCodegen implements CodegenConfig { name = name.replaceAll("-", "_"); // FIXME: a parameter should not be assigned. Also declare the methods parameters as 'final'. // e.g. PetApi.r => pet_api.r - return camelize(name + "_api"); + return org.openapitools.codegen.utils.StringUtils.camelize(name + "_api"); } @Override @@ -276,7 +277,7 @@ public class RClientCodegen extends DefaultCodegen implements CodegenConfig { @Override public String toApiName(String name) { - return camelize(super.toApiName(name)); + return org.openapitools.codegen.utils.StringUtils.camelize(super.toApiName(name)); } @Override @@ -328,11 +329,11 @@ public class RClientCodegen extends DefaultCodegen implements CodegenConfig { // method name cannot use reserved keyword, e.g. return if (isReservedWord(sanitizedOperationId)) { - LOGGER.warn(operationId + " (reserved word) cannot be used as method name. Renamed to " + underscore("call_" + operationId)); + LOGGER.warn(operationId + " (reserved word) cannot be used as method name. Renamed to " + org.openapitools.codegen.utils.StringUtils.underscore("call_" + operationId)); sanitizedOperationId = "call_" + sanitizedOperationId; } - return underscore(sanitizedOperationId); + return org.openapitools.codegen.utils.StringUtils.underscore(sanitizedOperationId); } @Override @@ -432,7 +433,7 @@ public class RClientCodegen extends DefaultCodegen implements CodegenConfig { } // string - String enumName = sanitizeName(underscore(name).toUpperCase(Locale.ROOT)); + String enumName = sanitizeName(org.openapitools.codegen.utils.StringUtils.underscore(name).toUpperCase(Locale.ROOT)); enumName = enumName.replaceFirst("^_", ""); enumName = enumName.replaceFirst("_$", ""); @@ -445,7 +446,7 @@ public class RClientCodegen extends DefaultCodegen implements CodegenConfig { @Override public String toEnumName(CodegenProperty property) { - String enumName = underscore(toModelName(property.name)).toUpperCase(Locale.ROOT); + String enumName = org.openapitools.codegen.utils.StringUtils.underscore(toModelName(property.name)).toUpperCase(Locale.ROOT); // remove [] for array or map of enum enumName = enumName.replace("[]", ""); diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/RubyClientCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/RubyClientCodegen.java index 539dda6d2a..995d21788c 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/RubyClientCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/RubyClientCodegen.java @@ -29,6 +29,7 @@ import java.util.Iterator; import java.util.Locale; import java.util.Map; + public class RubyClientCodegen extends AbstractRubyCodegen { private static final Logger LOGGER = LoggerFactory.getLogger(RubyClientCodegen.class); public static final String GEM_NAME = "gemName"; @@ -249,7 +250,7 @@ public class RubyClientCodegen extends AbstractRubyCodegen { */ @SuppressWarnings("static-method") public String generateModuleName(String gemName) { - return camelize(gemName.replaceAll("[^\\w]+", "_")); + return org.openapitools.codegen.utils.StringUtils.camelize(gemName.replaceAll("[^\\w]+", "_")); } /** @@ -260,7 +261,7 @@ public class RubyClientCodegen extends AbstractRubyCodegen { */ @SuppressWarnings("static-method") public String generateGemName(String moduleName) { - return underscore(moduleName.replaceAll("[^\\w]+", "")); + return org.openapitools.codegen.utils.StringUtils.underscore(moduleName.replaceAll("[^\\w]+", "")); } @Override @@ -327,25 +328,25 @@ public class RubyClientCodegen extends AbstractRubyCodegen { // model name cannot use reserved keyword, e.g. return if (isReservedWord(name)) { - String modelName = camelize("Model" + name); + String modelName = org.openapitools.codegen.utils.StringUtils.camelize("Model" + name); LOGGER.warn(name + " (reserved word) cannot be used as model name. Renamed to " + modelName); return modelName; } // 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)); + LOGGER.warn(name + " (model name starts with number) cannot be used as model name. Renamed to " + org.openapitools.codegen.utils.StringUtils.camelize("model_" + name)); name = "model_" + name; // e.g. 200Response => Model200Response (after camelize) } // camelize the model name // phone_number => PhoneNumber - return camelize(name); + return org.openapitools.codegen.utils.StringUtils.camelize(name); } @Override public String toModelFilename(String name) { - return underscore(toModelName(name)); + return org.openapitools.codegen.utils.StringUtils.underscore(toModelName(name)); } @Override @@ -359,7 +360,7 @@ public class RubyClientCodegen extends AbstractRubyCodegen { name = name.replaceAll("-", "_"); // FIXME: a parameter should not be assigned. Also declare the methods parameters as 'final'. // e.g. PhoneNumberApi.rb => phone_number_api.rb - return underscore(name) + "_api"; + return org.openapitools.codegen.utils.StringUtils.underscore(name) + "_api"; } @Override @@ -383,7 +384,7 @@ public class RubyClientCodegen extends AbstractRubyCodegen { return "DefaultApi"; } // e.g. phone_number_api => PhoneNumberApi - return camelize(name) + "Api"; + return org.openapitools.codegen.utils.StringUtils.camelize(name) + "Api"; } @Override @@ -411,7 +412,7 @@ public class RubyClientCodegen extends AbstractRubyCodegen { } // string - String enumName = sanitizeName(underscore(name).toUpperCase(Locale.ROOT)); + String enumName = sanitizeName(org.openapitools.codegen.utils.StringUtils.underscore(name).toUpperCase(Locale.ROOT)); enumName = enumName.replaceFirst("^_", ""); enumName = enumName.replaceFirst("_$", ""); @@ -424,7 +425,7 @@ public class RubyClientCodegen extends AbstractRubyCodegen { @Override public String toEnumName(CodegenProperty property) { - String enumName = underscore(toModelName(property.name)).toUpperCase(Locale.ROOT); + String enumName = org.openapitools.codegen.utils.StringUtils.underscore(toModelName(property.name)).toUpperCase(Locale.ROOT); enumName = enumName.replaceFirst("^_", ""); enumName = enumName.replaceFirst("_$", ""); @@ -445,25 +446,25 @@ public class RubyClientCodegen extends AbstractRubyCodegen { public String toOperationId(String operationId) { // rename to empty_method_name_1 (e.g.) if method name is empty if (StringUtils.isEmpty(operationId)) { - operationId = underscore("empty_method_name_" + emptyMethodNameCounter++); + operationId = org.openapitools.codegen.utils.StringUtils.underscore("empty_method_name_" + emptyMethodNameCounter++); LOGGER.warn("Empty method name (operationId) found. Renamed to " + operationId); return operationId; } // method name cannot use reserved keyword, e.g. return if (isReservedWord(operationId)) { - String newOperationId = underscore("call_" + operationId); + String newOperationId = org.openapitools.codegen.utils.StringUtils.underscore("call_" + operationId); LOGGER.warn(operationId + " (reserved word) cannot be used as method name. Renamed to " + newOperationId); return newOperationId; } // operationId starts with a number if (operationId.matches("^\\d.*")) { - LOGGER.warn(operationId + " (starting with a number) cannot be used as method name. Renamed to " + underscore(sanitizeName("call_" + operationId))); + LOGGER.warn(operationId + " (starting with a number) cannot be used as method name. Renamed to " + org.openapitools.codegen.utils.StringUtils.underscore(sanitizeName("call_" + operationId))); operationId = "call_" + operationId; } - return underscore(sanitizeName(operationId)); + return org.openapitools.codegen.utils.StringUtils.underscore(sanitizeName(operationId)); } @Override diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/RubyOnRailsServerCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/RubyOnRailsServerCodegen.java index fe929e0270..d67b1ad5ce 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/RubyOnRailsServerCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/RubyOnRailsServerCodegen.java @@ -34,6 +34,7 @@ import java.util.Map; import org.slf4j.Logger; import org.slf4j.LoggerFactory; + public class RubyOnRailsServerCodegen extends AbstractRubyCodegen { private static final Logger LOGGER = LoggerFactory.getLogger(RubyOnRailsServerCodegen.class); @@ -220,28 +221,28 @@ public class RubyOnRailsServerCodegen extends AbstractRubyCodegen { public String toModelName(String name) { // model name cannot use reserved keyword, e.g. return if (isReservedWord(name)) { - String modelName = camelize("Model" + name); + String modelName = org.openapitools.codegen.utils.StringUtils.camelize("Model" + name); LOGGER.warn(name + " (reserved word) cannot be used as model name. Renamed to " + modelName); return modelName; } // camelize the model name // phone_number => PhoneNumber - return camelize(name); + return org.openapitools.codegen.utils.StringUtils.camelize(name); } @Override public String toModelFilename(String name) { // model name cannot use reserved keyword, e.g. return if (isReservedWord(name)) { - String filename = underscore("model_" + name); + String filename = org.openapitools.codegen.utils.StringUtils.underscore("model_" + name); LOGGER.warn(name + " (reserved word) cannot be used as model filename. Renamed to " + filename); return filename; } // underscore the model file name // PhoneNumber.rb => phone_number.rb - return underscore(name); + return org.openapitools.codegen.utils.StringUtils.underscore(name); } @Override @@ -250,7 +251,7 @@ public class RubyOnRailsServerCodegen extends AbstractRubyCodegen { name = name.replaceAll("-", "_"); // FIXME: a parameter should not be assigned. Also declare the methods parameters as 'final'. // e.g. DefaultController => defaults_controller.rb - return underscore(name) + "_controller"; + return org.openapitools.codegen.utils.StringUtils.underscore(name) + "_controller"; } @Override @@ -260,7 +261,7 @@ public class RubyOnRailsServerCodegen extends AbstractRubyCodegen { } // e.g. PhoneNumber => phone_number - return underscore(sanitizeName(name)); + return org.openapitools.codegen.utils.StringUtils.underscore(sanitizeName(name)); } @Override @@ -269,7 +270,7 @@ public class RubyOnRailsServerCodegen extends AbstractRubyCodegen { return "ApiController"; } // e.g. phone_number_controller => PhoneNumberController - return camelize(name) + "Controller"; + return org.openapitools.codegen.utils.StringUtils.camelize(name) + "Controller"; } @Override diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/RubySinatraServerCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/RubySinatraServerCodegen.java index cfedccee55..05ecc9fa4e 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/RubySinatraServerCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/RubySinatraServerCodegen.java @@ -28,6 +28,7 @@ import java.util.Map; import org.slf4j.Logger; import org.slf4j.LoggerFactory; + public class RubySinatraServerCodegen extends AbstractRubyCodegen { private static final Logger LOGGER = LoggerFactory.getLogger(RubySinatraServerCodegen.class); @@ -109,26 +110,26 @@ public class RubySinatraServerCodegen extends AbstractRubyCodegen { public String toModelName(String name) { // model name cannot use reserved keyword, e.g. return if (isReservedWord(name)) { - LOGGER.warn(name + " (reserved word) cannot be used as model filename. Renamed to " + camelize("model_" + name)); + LOGGER.warn(name + " (reserved word) cannot be used as model filename. Renamed to " + org.openapitools.codegen.utils.StringUtils.camelize("model_" + name)); name = "model_" + name; // e.g. return => ModelReturn (after camelize) } // camelize the model name // phone_number => PhoneNumber - return camelize(name); + return org.openapitools.codegen.utils.StringUtils.camelize(name); } @Override public String toModelFilename(String name) { // model name cannot use reserved keyword, e.g. return if (isReservedWord(name)) { - LOGGER.warn(name + " (reserved word) cannot be used as model filename. Renamed to " + underscore("model_" + name)); + LOGGER.warn(name + " (reserved word) cannot be used as model filename. Renamed to " + org.openapitools.codegen.utils.StringUtils.underscore("model_" + name)); name = "model_" + name; // e.g. return => ModelReturn (after camelize) } // underscore the model file name // PhoneNumber.rb => phone_number.rb - return underscore(name); + return org.openapitools.codegen.utils.StringUtils.underscore(name); } @Override @@ -137,7 +138,7 @@ public class RubySinatraServerCodegen extends AbstractRubyCodegen { name = name.replaceAll("-", "_"); // FIXME: a parameter should not be assigned. Also declare the methods parameters as 'final'. // e.g. PhoneNumberApi.rb => phone_number_api.rb - return underscore(name) + "_api"; + return org.openapitools.codegen.utils.StringUtils.underscore(name) + "_api"; } @Override @@ -146,7 +147,7 @@ public class RubySinatraServerCodegen extends AbstractRubyCodegen { return "DefaultApi"; } // e.g. phone_number_api => PhoneNumberApi - return camelize(name) + "Api"; + return org.openapitools.codegen.utils.StringUtils.camelize(name) + "Api"; } @Override diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/RustClientCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/RustClientCodegen.java index 2625c37d06..da9763a281 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/RustClientCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/RustClientCodegen.java @@ -39,6 +39,7 @@ import java.util.List; import java.util.Locale; import java.util.Map; + public class RustClientCodegen extends DefaultCodegen implements CodegenConfig { private static final Logger LOGGER = LoggerFactory.getLogger(RustClientCodegen.class); public static final String PACKAGE_NAME = "packageName"; @@ -208,7 +209,7 @@ public class RustClientCodegen extends DefaultCodegen implements CodegenConfig { return name; // snake_case, e.g. PetId => pet_id - name = underscore(name); + name = org.openapitools.codegen.utils.StringUtils.underscore(name); // for reserved word or word starting with number, append _ if (isReservedWord(name)) @@ -230,7 +231,7 @@ public class RustClientCodegen extends DefaultCodegen implements CodegenConfig { public String toModelName(String name) { // camelize the model name // phone_number => PhoneNumber - return camelize(toModelFilename(name)); + return org.openapitools.codegen.utils.StringUtils.camelize(toModelFilename(name)); } @Override @@ -257,7 +258,7 @@ public class RustClientCodegen extends DefaultCodegen implements CodegenConfig { name = "model_" + name; // e.g. 200Response => Model200Response (after camelize) } - return underscore(name); + return org.openapitools.codegen.utils.StringUtils.underscore(name); } @Override @@ -266,7 +267,7 @@ public class RustClientCodegen extends DefaultCodegen implements CodegenConfig { name = name.replaceAll("-", "_"); // FIXME: a parameter should not be assigned. Also declare the methods parameters as 'final'. // e.g. PetApi.rs => pet_api.rs - return underscore(name) + "_api"; + return org.openapitools.codegen.utils.StringUtils.underscore(name) + "_api"; } @Override @@ -339,11 +340,11 @@ public class RustClientCodegen extends DefaultCodegen implements CodegenConfig { // method name cannot use reserved keyword, e.g. return if (isReservedWord(sanitizedOperationId)) { - LOGGER.warn(operationId + " (reserved word) cannot be used as method name. Renamed to " + underscore("call_" + operationId)); + LOGGER.warn(operationId + " (reserved word) cannot be used as method name. Renamed to " + org.openapitools.codegen.utils.StringUtils.underscore("call_" + operationId)); sanitizedOperationId = "call_" + sanitizedOperationId; } - return underscore(sanitizedOperationId); + return org.openapitools.codegen.utils.StringUtils.underscore(sanitizedOperationId); } @Override @@ -354,7 +355,7 @@ public class RustClientCodegen extends DefaultCodegen implements CodegenConfig { List operations = (List) objectMap.get("operation"); for (CodegenOperation operation : operations) { // http method verb conversion (e.g. PUT => Put) - operation.httpMethod = camelize(operation.httpMethod.toLowerCase(Locale.ROOT)); + operation.httpMethod = org.openapitools.codegen.utils.StringUtils.camelize(operation.httpMethod.toLowerCase(Locale.ROOT)); // update return type to conform to rust standard /* if (operation.returnType != null) { @@ -470,7 +471,7 @@ public class RustClientCodegen extends DefaultCodegen implements CodegenConfig { } // string - String enumName = sanitizeName(underscore(name).toUpperCase(Locale.ROOT)); + String enumName = sanitizeName(org.openapitools.codegen.utils.StringUtils.underscore(name).toUpperCase(Locale.ROOT)); enumName = enumName.replaceFirst("^_", ""); enumName = enumName.replaceFirst("_$", ""); @@ -483,7 +484,7 @@ public class RustClientCodegen extends DefaultCodegen implements CodegenConfig { @Override public String toEnumName(CodegenProperty property) { - String enumName = underscore(toModelName(property.name)).toUpperCase(Locale.ROOT); + String enumName = org.openapitools.codegen.utils.StringUtils.underscore(toModelName(property.name)).toUpperCase(Locale.ROOT); // remove [] for array or map of enum enumName = enumName.replace("[]", ""); diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/RustServerCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/RustServerCodegen.java index 0486327f3e..d45ce26f0e 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/RustServerCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/RustServerCodegen.java @@ -56,6 +56,7 @@ import java.util.Map; import java.util.Map.Entry; import java.util.Set; + public class RustServerCodegen extends DefaultCodegen implements CodegenConfig { private static final Logger LOGGER = LoggerFactory.getLogger(RustServerCodegen.class); @@ -303,7 +304,7 @@ public class RustServerCodegen extends DefaultCodegen implements CodegenConfig { if (name.length() == 0) { return "default"; } - return underscore(name); + return org.openapitools.codegen.utils.StringUtils.underscore(name); } /** @@ -333,7 +334,7 @@ public class RustServerCodegen extends DefaultCodegen implements CodegenConfig { public String toModelName(String name) { // camelize the model name // phone_number => PhoneNumber - String camelizedName = camelize(toModelFilename(name)); + String camelizedName = org.openapitools.codegen.utils.StringUtils.camelize(toModelFilename(name)); // model name cannot use reserved keyword, e.g. return if (isReservedWord(camelizedName)) { @@ -366,18 +367,18 @@ public class RustServerCodegen extends DefaultCodegen implements CodegenConfig { sanitizedName = escapeReservedWord(sanitizedName); } - return underscore(sanitizedName); + return org.openapitools.codegen.utils.StringUtils.underscore(sanitizedName); } @Override public String toOperationId(String operationId) { // method name cannot use reserved keyword, e.g. return if (isReservedWord(operationId)) { - LOGGER.warn(operationId + " (reserved word) cannot be used as method name. Renamed to " + camelize(sanitizeName("call_" + operationId))); + LOGGER.warn(operationId + " (reserved word) cannot be used as method name. Renamed to " + org.openapitools.codegen.utils.StringUtils.camelize(sanitizeName("call_" + operationId))); operationId = "call_" + operationId; } - return camelize(operationId); + return org.openapitools.codegen.utils.StringUtils.camelize(operationId); } @Override @@ -394,16 +395,16 @@ public class RustServerCodegen extends DefaultCodegen implements CodegenConfig { // 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)); + LOGGER.warn(name + " (reserved word) cannot be used as model name. Renamed to " + org.openapitools.codegen.utils.StringUtils.camelize("model_" + name)); name = "model_" + name; // e.g. return => ModelReturn (after camelize) } - return underscore(name); + return org.openapitools.codegen.utils.StringUtils.underscore(name); } @Override public String toEnumName(CodegenProperty property) { - return sanitizeName(camelize(property.name)) + "Enum"; + return sanitizeName(org.openapitools.codegen.utils.StringUtils.camelize(property.name)) + "Enum"; } @Override @@ -454,7 +455,7 @@ public class RustServerCodegen extends DefaultCodegen implements CodegenConfig { name = name.replaceAll("-", "_"); // FIXME: a parameter should not be assigned. Also declare the methods parameters as 'final'. // e.g. PetApi.go => pet_api.go - return underscore(name); + return org.openapitools.codegen.utils.StringUtils.underscore(name); } @Override @@ -520,8 +521,8 @@ public class RustServerCodegen extends DefaultCodegen implements CodegenConfig { pathSetMap.put(pathId, pathSetEntry); } - op.vendorExtensions.put("operation_id", underscore(op.operationId)); - op.vendorExtensions.put("uppercase_operation_id", underscore(op.operationId).toUpperCase(Locale.ROOT)); + op.vendorExtensions.put("operation_id", org.openapitools.codegen.utils.StringUtils.underscore(op.operationId)); + op.vendorExtensions.put("uppercase_operation_id", org.openapitools.codegen.utils.StringUtils.underscore(op.operationId).toUpperCase(Locale.ROOT)); op.vendorExtensions.put("path", op.path.replace("{", ":").replace("}", "")); op.vendorExtensions.put("PATH_ID", pathId); op.vendorExtensions.put("hasPathParams", !op.pathParams.isEmpty()); @@ -598,13 +599,13 @@ public class RustServerCodegen extends DefaultCodegen implements CodegenConfig { if (rsp.vendorExtensions.containsKey("x-responseId")) { responseId = (String) rsp.vendorExtensions.get("x-responseId"); } else if (words.length != 0) { - responseId = camelize(words[0].replace(" ", "_")); + responseId = org.openapitools.codegen.utils.StringUtils.camelize(words[0].replace(" ", "_")); } else { responseId = "Status" + rsp.code; } rsp.vendorExtensions.put("x-responseId", responseId); - rsp.vendorExtensions.put("x-uppercaseResponseId", underscore(responseId).toUpperCase(Locale.ROOT)); - rsp.vendorExtensions.put("uppercase_operation_id", underscore(op.operationId).toUpperCase(Locale.ROOT)); + rsp.vendorExtensions.put("x-uppercaseResponseId", org.openapitools.codegen.utils.StringUtils.underscore(responseId).toUpperCase(Locale.ROOT)); + rsp.vendorExtensions.put("uppercase_operation_id", org.openapitools.codegen.utils.StringUtils.underscore(op.operationId).toUpperCase(Locale.ROOT)); if (rsp.dataType != null) { rsp.vendorExtensions.put("uppercase_data_type", (rsp.dataType.replace("models::", "")).toUpperCase(Locale.ROOT)); @@ -675,7 +676,7 @@ public class RustServerCodegen extends DefaultCodegen implements CodegenConfig { if (op.bodyParam != null) { // Default to consuming json - op.bodyParam.vendorExtensions.put("uppercase_operation_id", underscore(op.operationId).toUpperCase(Locale.ROOT)); + op.bodyParam.vendorExtensions.put("uppercase_operation_id", org.openapitools.codegen.utils.StringUtils.underscore(op.operationId).toUpperCase(Locale.ROOT)); if (consumesXml) { op.bodyParam.vendorExtensions.put("consumesXml", true); } else if (consumesPlainText) { @@ -688,7 +689,7 @@ public class RustServerCodegen extends DefaultCodegen implements CodegenConfig { for (CodegenParameter param : op.bodyParams) { processParam(param, op); - param.vendorExtensions.put("uppercase_operation_id", underscore(op.operationId).toUpperCase(Locale.ROOT)); + param.vendorExtensions.put("uppercase_operation_id", org.openapitools.codegen.utils.StringUtils.underscore(op.operationId).toUpperCase(Locale.ROOT)); // Default to producing json if nothing else is specified if (consumesXml) { @@ -926,9 +927,9 @@ public class RustServerCodegen extends DefaultCodegen implements CodegenConfig { // If we use a more qualified model name, then only camelize the actual type, not the qualifier. if (property.dataType.contains(":")) { int position = property.dataType.lastIndexOf(":"); - property.dataType = property.dataType.substring(0, position) + camelize(property.dataType.substring(position)); + property.dataType = property.dataType.substring(0, position) + org.openapitools.codegen.utils.StringUtils.camelize(property.dataType.substring(position)); } else { - property.dataType = camelize(property.dataType, false); + property.dataType = org.openapitools.codegen.utils.StringUtils.camelize(property.dataType, false); } } @@ -976,7 +977,7 @@ public class RustServerCodegen extends DefaultCodegen implements CodegenConfig { } } - property.name = underscore(property.name); + property.name = org.openapitools.codegen.utils.StringUtils.underscore(property.name); if (!property.required) { property.defaultValue = (property.defaultValue != null) ? "Some(" + property.defaultValue + ")" : "None"; 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 d3a42542a8..ba8ea0062d 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,6 +35,7 @@ import java.io.StringWriter; import java.io.Writer; import java.util.*; + public class ScalaAkkaClientCodegen extends AbstractScalaCodegen implements CodegenConfig { protected String mainPackage = "org.openapitools.client"; protected String groupId = "org.openapitools"; @@ -335,7 +336,7 @@ public class ScalaAkkaClientCodegen extends AbstractScalaCodegen implements Code @Override public String formatFragment(String fragment) { - return camelize(fragment, !capitalizeFirst); + return org.openapitools.codegen.utils.StringUtils.camelize(fragment, !capitalizeFirst); } } diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/ScalaHttpClientCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/ScalaHttpClientCodegen.java index b23a7f75ce..f02d21d289 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/ScalaHttpClientCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/ScalaHttpClientCodegen.java @@ -26,6 +26,7 @@ import java.io.File; import java.util.Arrays; import java.util.HashMap; + public class ScalaHttpClientCodegen extends AbstractScalaCodegen implements CodegenConfig { private static final Logger LOGGER = LoggerFactory.getLogger(ScalaHttpClientCodegen.class); @@ -184,11 +185,11 @@ public class ScalaHttpClientCodegen extends AbstractScalaCodegen implements Code case original: return name; case camelCase: - return camelize(name, true); + return org.openapitools.codegen.utils.StringUtils.camelize(name, true); case PascalCase: - return camelize(name); + return org.openapitools.codegen.utils.StringUtils.camelize(name); case snake_case: - return underscore(name); + return org.openapitools.codegen.utils.StringUtils.underscore(name); default: throw new IllegalArgumentException("Invalid model property naming '" + name + "'. Must be 'original', 'camelCase', " + @@ -226,7 +227,7 @@ public class ScalaHttpClientCodegen extends AbstractScalaCodegen implements Code throw new RuntimeException(operationId + " (reserved word) cannot be used as method name"); } - return camelize(operationId, true); + return org.openapitools.codegen.utils.StringUtils.camelize(operationId, true); } @Override @@ -235,7 +236,7 @@ public class ScalaHttpClientCodegen extends AbstractScalaCodegen implements Code // camelize the model name // phone_number => PhoneNumber - final String camelizedName = camelize(sanitizedName); + final String camelizedName = org.openapitools.codegen.utils.StringUtils.camelize(sanitizedName); // model name cannot use reserved keyword, e.g. return if (isReservedWord(camelizedName)) { diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/ScalaLagomServerCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/ScalaLagomServerCodegen.java index e8f9be4d39..1b8272a262 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/ScalaLagomServerCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/ScalaLagomServerCodegen.java @@ -24,6 +24,7 @@ import java.util.*; import org.slf4j.Logger; import org.slf4j.LoggerFactory; + public class ScalaLagomServerCodegen extends AbstractScalaCodegen implements CodegenConfig { private static final Logger LOGGER = LoggerFactory.getLogger(ScalaLagomServerCodegen.class); @@ -166,11 +167,11 @@ public class ScalaLagomServerCodegen extends AbstractScalaCodegen implements Cod case original: return name; case camelCase: - return camelize(name, true); + return org.openapitools.codegen.utils.StringUtils.camelize(name, true); case PascalCase: - return camelize(name); + return org.openapitools.codegen.utils.StringUtils.camelize(name); case snake_case: - return underscore(name); + return org.openapitools.codegen.utils.StringUtils.underscore(name); default: throw new IllegalArgumentException("Invalid model property naming '" + name + "'. Must be 'original', 'camelCase', " + @@ -206,7 +207,7 @@ public class ScalaLagomServerCodegen extends AbstractScalaCodegen implements Cod throw new RuntimeException(operationId + " (reserved word) cannot be used as method name"); } - return camelize(operationId, true); + return org.openapitools.codegen.utils.StringUtils.camelize(operationId, true); } @Override @@ -215,7 +216,7 @@ public class ScalaLagomServerCodegen extends AbstractScalaCodegen implements Cod // camelize the model name // phone_number => PhoneNumber - final String camelizedName = camelize(sanitizedName); + final String camelizedName = org.openapitools.codegen.utils.StringUtils.camelize(sanitizedName); // model name cannot use reserved keyword, e.g. return if (isReservedWord(camelizedName)) { diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/ScalazClientCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/ScalazClientCodegen.java index 0e55600fa6..6936e6df86 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/ScalazClientCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/ScalazClientCodegen.java @@ -31,6 +31,7 @@ import java.io.Writer; import java.util.Arrays; import java.util.HashMap; + public class ScalazClientCodegen extends AbstractScalaCodegen implements CodegenConfig { private static final Logger LOGGER = LoggerFactory.getLogger(ScalazClientCodegen.class); @@ -163,11 +164,11 @@ public class ScalazClientCodegen extends AbstractScalaCodegen implements Codegen case original: return name; case camelCase: - return camelize(name, true); + return org.openapitools.codegen.utils.StringUtils.camelize(name, true); case PascalCase: - return camelize(name); + return org.openapitools.codegen.utils.StringUtils.camelize(name); case snake_case: - return underscore(name); + return org.openapitools.codegen.utils.StringUtils.underscore(name); default: throw new IllegalArgumentException("Invalid model property naming '" + name + "'. Must be 'original', 'camelCase', " + @@ -203,7 +204,7 @@ public class ScalazClientCodegen extends AbstractScalaCodegen implements Codegen throw new RuntimeException(operationId + " (reserved word) cannot be used as method name"); } - return camelize(operationId, true); + return org.openapitools.codegen.utils.StringUtils.camelize(operationId, true); } @Override @@ -212,7 +213,7 @@ public class ScalazClientCodegen extends AbstractScalaCodegen implements Codegen // camelize the model name // phone_number => PhoneNumber - final String camelizedName = camelize(sanitizedName); + final String camelizedName = org.openapitools.codegen.utils.StringUtils.camelize(sanitizedName); // model name cannot use reserved keyword, e.g. return if (isReservedWord(camelizedName)) { 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 5e6f269880..e88c976d90 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 @@ -49,6 +49,7 @@ import java.util.Map; import java.util.regex.Matcher; import java.util.stream.Collectors; + public class SpringCodegen extends AbstractJavaCodegen implements BeanValidationFeatures, OptionalFeatures { private static final Logger LOGGER = LoggerFactory.getLogger(SpringCodegen.class); @@ -441,7 +442,7 @@ public class SpringCodegen extends AbstractJavaCodegen title = title.substring(0, title.length() - 3); } - this.title = camelize(sanitizeName(title), true); + this.title = org.openapitools.codegen.utils.StringUtils.camelize(sanitizeName(title), true); } additionalProperties.put(TITLE, this.title); } @@ -591,7 +592,7 @@ public class SpringCodegen extends AbstractJavaCodegen List authMethods = (List) objs.get("authMethods"); if (authMethods != null) { for (CodegenSecurity authMethod : authMethods) { - authMethod.name = camelize(sanitizeName(authMethod.name), true); + authMethod.name = org.openapitools.codegen.utils.StringUtils.camelize(sanitizeName(authMethod.name), true); } } } @@ -604,7 +605,7 @@ public class SpringCodegen extends AbstractJavaCodegen return "DefaultApi"; } name = sanitizeName(name); - return camelize(name) + "Api"; + return org.openapitools.codegen.utils.StringUtils.camelize(name) + "Api"; } @Override diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/StaticHtml2Generator.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/StaticHtml2Generator.java index a975cf63bd..e220f90634 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/StaticHtml2Generator.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/StaticHtml2Generator.java @@ -45,6 +45,7 @@ import java.util.List; import java.util.Locale; import java.util.Map; + public class StaticHtml2Generator extends DefaultCodegen implements CodegenConfig { private static final Logger LOGGER = LoggerFactory.getLogger(StaticHtml2Generator.class); @@ -161,7 +162,7 @@ public class StaticHtml2Generator extends DefaultCodegen implements CodegenConfi Info info = openAPI.getInfo(); if (StringUtils.isBlank(jsProjectName) && info.getTitle() != null) { // when jsProjectName is not specified, generate it from info.title - jsProjectName = sanitizeName(dashize(info.getTitle())); + jsProjectName = sanitizeName(org.openapitools.codegen.utils.StringUtils.dashize(info.getTitle())); } } @@ -170,7 +171,7 @@ public class StaticHtml2Generator extends DefaultCodegen implements CodegenConfi jsProjectName = "openapi-js-client"; } if (StringUtils.isBlank(jsModuleName)) { - jsModuleName = camelize(underscore(jsProjectName)); + jsModuleName = org.openapitools.codegen.utils.StringUtils.camelize(org.openapitools.codegen.utils.StringUtils.underscore(jsProjectName)); } additionalProperties.put("jsProjectName", jsProjectName); diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/Swift3Codegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/Swift3Codegen.java index a8b3f0d64e..1140d25ecc 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/Swift3Codegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/Swift3Codegen.java @@ -32,6 +32,7 @@ import java.util.*; import java.util.regex.Matcher; import java.util.regex.Pattern; + public class Swift3Codegen extends DefaultCodegen implements CodegenConfig { private static final Logger LOGGER = LoggerFactory.getLogger(Swift3Codegen.class); @@ -382,7 +383,7 @@ public class Swift3Codegen extends DefaultCodegen implements CodegenConfig { // camelize the model name // phone_number => PhoneNumber - name = camelize(name); + name = org.openapitools.codegen.utils.StringUtils.camelize(name); // model name cannot use reserved keyword, e.g. return if (isReservedWord(name)) { @@ -440,7 +441,7 @@ public class Swift3Codegen extends DefaultCodegen implements CodegenConfig { @Override public String toOperationId(String operationId) { - operationId = camelize(sanitizeName(operationId), true); + operationId = org.openapitools.codegen.utils.StringUtils.camelize(sanitizeName(operationId), true); // throw exception if method name is empty. This should not happen but keep the check just in case if (StringUtils.isEmpty(operationId)) { @@ -449,15 +450,15 @@ public class Swift3Codegen extends DefaultCodegen implements CodegenConfig { // method name cannot use reserved keyword, e.g. return if (isReservedWord(operationId)) { - String newOperationId = camelize(("call_" + operationId), true); + String newOperationId = org.openapitools.codegen.utils.StringUtils.camelize(("call_" + operationId), true); LOGGER.warn(operationId + " (reserved word) cannot be used as method name. Renamed to " + newOperationId); return newOperationId; } // operationId starts with a number if (operationId.matches("^\\d.*")) { - LOGGER.warn(operationId + " (starting with a number) cannot be used as method name. Renamed to " + camelize(sanitizeName("call_" + operationId), true)); - operationId = camelize(sanitizeName("call_" + operationId), true); + LOGGER.warn(operationId + " (starting with a number) cannot be used as method name. Renamed to " + org.openapitools.codegen.utils.StringUtils.camelize(sanitizeName("call_" + operationId), true)); + operationId = org.openapitools.codegen.utils.StringUtils.camelize(sanitizeName("call_" + operationId), true); } return operationId; @@ -475,7 +476,7 @@ public class Swift3Codegen extends DefaultCodegen implements CodegenConfig { // camelize the variable name // pet_id => petId - name = camelize(name, true); + name = org.openapitools.codegen.utils.StringUtils.camelize(name, true); // for reserved word or word starting with number, append _ if (isReservedWord(name) || name.matches("^\\d.*")) { @@ -498,9 +499,9 @@ public class Swift3Codegen extends DefaultCodegen implements CodegenConfig { return name; } - // camelize(lower) the variable name + // org.openapitools.codegen.utils.StringUtils.camelize(lower) the variable name // pet_id => petId - name = camelize(name, true); + name = org.openapitools.codegen.utils.StringUtils.camelize(name, true); // for reserved word or word starting with number, append _ if (isReservedWord(name) || name.matches("^\\d.*")) { @@ -579,18 +580,18 @@ public class Swift3Codegen extends DefaultCodegen implements CodegenConfig { String startingNumbers = startWithNumberMatcher.group(0); String nameWithoutStartingNumbers = name.substring(startingNumbers.length()); - return "_" + startingNumbers + camelize(nameWithoutStartingNumbers, true); + return "_" + startingNumbers + org.openapitools.codegen.utils.StringUtils.camelize(nameWithoutStartingNumbers, true); } // for symbol, e.g. $, # if (getSymbolName(name) != null) { - return camelize(WordUtils.capitalizeFully(getSymbolName(name).toUpperCase(Locale.ROOT)), true); + return org.openapitools.codegen.utils.StringUtils.camelize(WordUtils.capitalizeFully(getSymbolName(name).toUpperCase(Locale.ROOT)), true); } // Camelize only when we have a structure defined below Boolean camelized = false; if (name.matches("[A-Z][a-z0-9]+[a-zA-Z0-9]*")) { - name = camelize(name, true); + name = org.openapitools.codegen.utils.StringUtils.camelize(name, true); camelized = true; } @@ -603,7 +604,7 @@ public class Swift3Codegen extends DefaultCodegen implements CodegenConfig { // Check for numerical conversions if ("Int".equals(datatype) || "Int32".equals(datatype) || "Int64".equals(datatype) || "Float".equals(datatype) || "Double".equals(datatype)) { - String varName = "number" + camelize(name); + String varName = "number" + org.openapitools.codegen.utils.StringUtils.camelize(name); varName = varName.replaceAll("-", "minus"); varName = varName.replaceAll("\\+", "plus"); varName = varName.replaceAll("\\.", "dot"); @@ -617,7 +618,7 @@ public class Swift3Codegen extends DefaultCodegen implements CodegenConfig { } char[] separators = {'-', '_', ' ', ':', '(', ')'}; - return camelize(WordUtils.capitalizeFully(StringUtils.lowerCase(name), separators).replaceAll("[-_ :\\(\\)]", ""), true); + return org.openapitools.codegen.utils.StringUtils.camelize(WordUtils.capitalizeFully(StringUtils.lowerCase(name), separators).replaceAll("[-_ :\\(\\)]", ""), true); } @Override diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/Swift4Codegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/Swift4Codegen.java index 76e2b0602b..99f2a83bd9 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/Swift4Codegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/Swift4Codegen.java @@ -32,6 +32,7 @@ import java.util.*; import java.util.regex.Matcher; import java.util.regex.Pattern; + public class Swift4Codegen extends DefaultCodegen implements CodegenConfig { private static final Logger LOGGER = LoggerFactory.getLogger(Swift4Codegen.class); @@ -472,7 +473,7 @@ public class Swift4Codegen extends DefaultCodegen implements CodegenConfig { // camelize the model name // phone_number => PhoneNumber - name = camelize(name); + name = org.openapitools.codegen.utils.StringUtils.camelize(name); // model name cannot use reserved keyword, e.g. return if (isReservedWord(name)) { @@ -543,7 +544,7 @@ public class Swift4Codegen extends DefaultCodegen implements CodegenConfig { @Override public String toOperationId(String operationId) { - operationId = camelize(sanitizeName(operationId), true); + operationId = org.openapitools.codegen.utils.StringUtils.camelize(sanitizeName(operationId), true); // Throw exception if method name is empty. // This should not happen but keep the check just in case @@ -553,7 +554,7 @@ public class Swift4Codegen extends DefaultCodegen implements CodegenConfig { // method name cannot use reserved keyword, e.g. return if (isReservedWord(operationId)) { - String newOperationId = camelize(("call_" + operationId), true); + String newOperationId = org.openapitools.codegen.utils.StringUtils.camelize(("call_" + operationId), true); LOGGER.warn(operationId + " (reserved word) cannot be used as method name." + " Renamed to " + newOperationId); return newOperationId; @@ -561,8 +562,8 @@ public class Swift4Codegen extends DefaultCodegen implements CodegenConfig { // operationId starts with a number if (operationId.matches("^\\d.*")) { - LOGGER.warn(operationId + " (starting with a number) cannot be used as method name. Renamed to " + camelize(sanitizeName("call_" + operationId), true)); - operationId = camelize(sanitizeName("call_" + operationId), true); + LOGGER.warn(operationId + " (starting with a number) cannot be used as method name. Renamed to " + org.openapitools.codegen.utils.StringUtils.camelize(sanitizeName("call_" + operationId), true)); + operationId = org.openapitools.codegen.utils.StringUtils.camelize(sanitizeName("call_" + operationId), true); } @@ -581,7 +582,7 @@ public class Swift4Codegen extends DefaultCodegen implements CodegenConfig { // camelize the variable name // pet_id => petId - name = camelize(name, true); + name = org.openapitools.codegen.utils.StringUtils.camelize(name, true); // for reserved word or word starting with number, append _ if (isReservedWord(name) || name.matches("^\\d.*")) { @@ -604,9 +605,9 @@ public class Swift4Codegen extends DefaultCodegen implements CodegenConfig { return name; } - // camelize(lower) the variable name + // org.openapitools.codegen.utils.StringUtils.camelize(lower) the variable name // pet_id => petId - name = camelize(name, true); + name = org.openapitools.codegen.utils.StringUtils.camelize(name, true); // for reserved word or word starting with number, append _ if (isReservedWord(name) || name.matches("^\\d.*")) { @@ -692,18 +693,18 @@ public class Swift4Codegen extends DefaultCodegen implements CodegenConfig { String startingNumbers = startWithNumberMatcher.group(0); String nameWithoutStartingNumbers = name.substring(startingNumbers.length()); - return "_" + startingNumbers + camelize(nameWithoutStartingNumbers, true); + return "_" + startingNumbers + org.openapitools.codegen.utils.StringUtils.camelize(nameWithoutStartingNumbers, true); } // for symbol, e.g. $, # if (getSymbolName(name) != null) { - return camelize(WordUtils.capitalizeFully(getSymbolName(name).toUpperCase(Locale.ROOT)), true); + return org.openapitools.codegen.utils.StringUtils.camelize(WordUtils.capitalizeFully(getSymbolName(name).toUpperCase(Locale.ROOT)), true); } // Camelize only when we have a structure defined below Boolean camelized = false; if (name.matches("[A-Z][a-z0-9]+[a-zA-Z0-9]*")) { - name = camelize(name, true); + name = org.openapitools.codegen.utils.StringUtils.camelize(name, true); camelized = true; } @@ -716,7 +717,7 @@ public class Swift4Codegen extends DefaultCodegen implements CodegenConfig { // Check for numerical conversions if ("Int".equals(datatype) || "Int32".equals(datatype) || "Int64".equals(datatype) || "Float".equals(datatype) || "Double".equals(datatype)) { - String varName = "number" + camelize(name); + String varName = "number" + org.openapitools.codegen.utils.StringUtils.camelize(name); varName = varName.replaceAll("-", "minus"); varName = varName.replaceAll("\\+", "plus"); varName = varName.replaceAll("\\.", "dot"); @@ -730,7 +731,7 @@ public class Swift4Codegen extends DefaultCodegen implements CodegenConfig { } char[] separators = {'-', '_', ' ', ':', '(', ')'}; - return camelize(WordUtils.capitalizeFully(StringUtils.lowerCase(name), separators) + return org.openapitools.codegen.utils.StringUtils.camelize(WordUtils.capitalizeFully(StringUtils.lowerCase(name), separators) .replaceAll("[-_ :\\(\\)]", ""), true); } diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/SwiftClientCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/SwiftClientCodegen.java index 97aeb0479b..775694c5e0 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/SwiftClientCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/SwiftClientCodegen.java @@ -34,6 +34,7 @@ import java.util.*; import java.util.regex.Matcher; import java.util.regex.Pattern; + /** * Swift (2.x) generator is no longer actively maintained. Please use * 'swift3' or 'swift4' generator instead. @@ -319,7 +320,7 @@ public class SwiftClientCodegen extends DefaultCodegen implements CodegenConfig // camelize the model name // phone_number => PhoneNumber - name = camelize(name); + name = org.openapitools.codegen.utils.StringUtils.camelize(name); // model name cannot use reserved keyword, e.g. return if (isReservedWord(name)) { @@ -436,7 +437,7 @@ public class SwiftClientCodegen extends DefaultCodegen implements CodegenConfig @Override public String toOperationId(String operationId) { - operationId = camelize(sanitizeName(operationId), true); + operationId = org.openapitools.codegen.utils.StringUtils.camelize(sanitizeName(operationId), true); // throw exception if method name is empty. This should not happen but keep the check just in case if (StringUtils.isEmpty(operationId)) { @@ -445,15 +446,15 @@ public class SwiftClientCodegen extends DefaultCodegen implements CodegenConfig // method name cannot use reserved keyword, e.g. return if (isReservedWord(operationId)) { - String newOperationId = camelize(("call_" + operationId), true); + String newOperationId = org.openapitools.codegen.utils.StringUtils.camelize(("call_" + operationId), true); LOGGER.warn(operationId + " (reserved word) cannot be used as method name. Renamed to " + newOperationId); return newOperationId; } // operationId starts with a number if (operationId.matches("^\\d.*")) { - LOGGER.warn(operationId + " (starting with a number) cannot be used as method name. Renamed to " + camelize(sanitizeName("call_" + operationId), true)); - operationId = camelize(sanitizeName("call_" + operationId), true); + LOGGER.warn(operationId + " (starting with a number) cannot be used as method name. Renamed to " + org.openapitools.codegen.utils.StringUtils.camelize(sanitizeName("call_" + operationId), true)); + operationId = org.openapitools.codegen.utils.StringUtils.camelize(sanitizeName("call_" + operationId), true); } return operationId; @@ -471,7 +472,7 @@ public class SwiftClientCodegen extends DefaultCodegen implements CodegenConfig // camelize the variable name // pet_id => petId - name = camelize(name, true); + name = org.openapitools.codegen.utils.StringUtils.camelize(name, true); // for reserved word or word starting with number, append _ if (isReservedWord(name) || name.matches("^\\d.*")) { @@ -494,9 +495,9 @@ public class SwiftClientCodegen extends DefaultCodegen implements CodegenConfig return name; } - // camelize(lower) the variable name + // org.openapitools.codegen.utils.StringUtils.camelize(lower) the variable name // pet_id => petId - name = camelize(name, true); + name = org.openapitools.codegen.utils.StringUtils.camelize(name, true); // for reserved word or word starting with number, append _ if (isReservedWord(name) || name.matches("^\\d.*")) { @@ -524,7 +525,7 @@ public class SwiftClientCodegen extends DefaultCodegen implements CodegenConfig builder.append(stringBeforeMatch); String group = matcher.group().substring(1, matcher.group().length() - 1); - group = camelize(group, true); + group = org.openapitools.codegen.utils.StringUtils.camelize(group, true); builder .append("{") .append(group) @@ -583,7 +584,7 @@ public class SwiftClientCodegen extends DefaultCodegen implements CodegenConfig } // string - String enumName = sanitizeName(underscore(name).toUpperCase(Locale.ROOT)); + String enumName = sanitizeName(org.openapitools.codegen.utils.StringUtils.underscore(name).toUpperCase(Locale.ROOT)); enumName = enumName.replaceFirst("^_", ""); enumName = enumName.replaceFirst("_$", ""); diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/TypeScriptAngularClientCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/TypeScriptAngularClientCodegen.java index c08a980a33..4ae97530cc 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/TypeScriptAngularClientCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/TypeScriptAngularClientCodegen.java @@ -29,6 +29,7 @@ import java.io.File; import java.text.SimpleDateFormat; import java.util.*; + public class TypeScriptAngularClientCodegen extends AbstractTypeScriptClientCodegen { private static final Logger LOGGER = LoggerFactory.getLogger(TypeScriptAngularClientCodegen.class); @@ -455,7 +456,7 @@ public class TypeScriptAngularClientCodegen extends AbstractTypeScriptClientCode if (name.length() == 0) { return "default.service"; } - return camelize(removeModelSuffixIfNecessary(name), true) + serviceFileSuffix; + return org.openapitools.codegen.utils.StringUtils.camelize(removeModelSuffixIfNecessary(name), true) + serviceFileSuffix; } @Override @@ -466,7 +467,7 @@ public class TypeScriptAngularClientCodegen extends AbstractTypeScriptClientCode @Override public String toModelFilename(String name) { String modelName = toModelName(name); - return camelize(removeModelSuffixIfNecessary(modelName), true) + modelFileSuffix; + return org.openapitools.codegen.utils.StringUtils.camelize(removeModelSuffixIfNecessary(modelName), true) + modelFileSuffix; } @Override @@ -511,7 +512,7 @@ public class TypeScriptAngularClientCodegen extends AbstractTypeScriptClientCode if (modelFileSuffix.length() > 0) { name = name.substring(0, name.length() - modelFileSuffix.length()); } - return camelize(name) + modelSuffix; + return org.openapitools.codegen.utils.StringUtils.camelize(name) + modelSuffix; } @Override diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/TypeScriptInversifyClientCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/TypeScriptInversifyClientCodegen.java index 28259a7dcd..9ca446c5a8 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/TypeScriptInversifyClientCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/TypeScriptInversifyClientCodegen.java @@ -29,6 +29,7 @@ import java.text.SimpleDateFormat; import java.util.*; + public class TypeScriptInversifyClientCodegen extends AbstractTypeScriptClientCodegen { private static final SimpleDateFormat SNAPSHOT_SUFFIX_FORMAT = new SimpleDateFormat("yyyyMMddHHmm", Locale.ROOT); private static final String X_DISCRIMINATOR_TYPE = "x-discriminator-value"; @@ -326,7 +327,7 @@ public class TypeScriptInversifyClientCodegen extends AbstractTypeScriptClientCo if (name.length() == 0) { return "default.service"; } - return camelize(name, true) + ".service"; + return org.openapitools.codegen.utils.StringUtils.camelize(name, true) + ".service"; } @Override @@ -336,7 +337,7 @@ public class TypeScriptInversifyClientCodegen extends AbstractTypeScriptClientCo @Override public String toModelFilename(String name) { - return camelize(toModelName(name), true); + return org.openapitools.codegen.utils.StringUtils.camelize(toModelName(name), true); } @Override @@ -375,7 +376,7 @@ public class TypeScriptInversifyClientCodegen extends AbstractTypeScriptClientCo private String getModelnameFromModelFilename(String filename) { String name = filename.substring((modelPackage() + "/").length()); - return camelize(name); + return org.openapitools.codegen.utils.StringUtils.camelize(name); } } diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/TypeScriptNodeClientCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/TypeScriptNodeClientCodegen.java index 3e6b1848f0..6021187cd0 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/TypeScriptNodeClientCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/TypeScriptNodeClientCodegen.java @@ -29,6 +29,7 @@ import java.io.File; import java.text.SimpleDateFormat; import java.util.*; + public class TypeScriptNodeClientCodegen extends AbstractTypeScriptClientCodegen { private static final Logger LOGGER = LoggerFactory.getLogger(TypeScriptNodeClientCodegen.class); private static final SimpleDateFormat SNAPSHOT_SUFFIX_FORMAT = new SimpleDateFormat("yyyyMMddHHmm", Locale.ROOT); @@ -106,7 +107,7 @@ public class TypeScriptNodeClientCodegen extends AbstractTypeScriptClientCodegen if (name.length() == 0) { return "default" + apiSuffix; } - return camelize(name, true) + apiSuffix; + return org.openapitools.codegen.utils.StringUtils.camelize(name, true) + apiSuffix; } @Override @@ -116,7 +117,7 @@ public class TypeScriptNodeClientCodegen extends AbstractTypeScriptClientCodegen @Override public String toModelFilename(String name) { - return camelize(toModelName(name), true); + return org.openapitools.codegen.utils.StringUtils.camelize(toModelName(name), true); } @Override @@ -295,6 +296,6 @@ public class TypeScriptNodeClientCodegen extends AbstractTypeScriptClientCodegen private String getModelnameFromModelFilename(String filename) { String name = filename.substring((modelPackage() + File.separator).length()); - return camelize(name); + return org.openapitools.codegen.utils.StringUtils.camelize(name); } } diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/mustache/CamelCaseLambda.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/mustache/CamelCaseLambda.java index 5dcfde31d8..f67b0e848a 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/mustache/CamelCaseLambda.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/mustache/CamelCaseLambda.java @@ -17,17 +17,16 @@ package org.openapitools.codegen.mustache; -import com.google.common.base.CaseFormat; import com.samskivert.mustache.Mustache; import com.samskivert.mustache.Template; import org.openapitools.codegen.CodegenConfig; -import org.openapitools.codegen.DefaultCodegen; -import org.apache.commons.lang3.StringUtils; -import org.apache.commons.lang3.text.WordUtils; import java.io.IOException; import java.io.Writer; +import static org.openapitools.codegen.utils.StringUtils.camelize; + + /** * Converts text in a fragment to camelCase. * @@ -61,7 +60,7 @@ public class CamelCaseLambda implements Mustache.Lambda { @Override public void execute(Template.Fragment fragment, Writer writer) throws IOException { - String text = DefaultCodegen.camelize(fragment.execute(), true); + String text = camelize(fragment.execute(), true); if (generator != null) { text = generator.sanitizeName(text); if (generator.reservedWords().contains(text)) { 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 new file mode 100644 index 0000000000..47679a6f8f --- /dev/null +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/utils/StringUtils.java @@ -0,0 +1,165 @@ +package org.openapitools.codegen.utils; + +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +public class StringUtils { + /** + * Underscore the given word. + * Copied from Twitter elephant bird + * https://github.com/twitter/elephant-bird/blob/master/core/src/main/java/com/twitter/elephantbird/util/Strings.java + * + * @param word The word + * @return The underscored version of the word + */ + public static String underscore(String word) { + String firstPattern = "([A-Z]+)([A-Z][a-z])"; + String secondPattern = "([a-z\\d])([A-Z])"; + String replacementPattern = "$1_$2"; + // Replace package separator with slash. + word = word.replaceAll("\\.", "/"); // FIXME: a parameter should not be assigned. Also declare the methods parameters as 'final'. + // Replace $ with two underscores for inner classes. + word = word.replaceAll("\\$", "__"); + // Replace capital letter with _ plus lowercase letter. + word = word.replaceAll(firstPattern, replacementPattern); + word = word.replaceAll(secondPattern, replacementPattern); + word = word.replace('-', '_'); + // replace space with underscore + word = word.replace(' ', '_'); + word = word.toLowerCase(Locale.ROOT); + return word; + } + + /** + * Dashize the given word. + * + * @param word The word + * @return The dashized version of the word, e.g. "my-name" + */ + public static String dashize(String word) { + return underscore(word).replaceAll("[_ ]", "-"); + } + + /** + * Camelize name (parameter, property, method, etc) with upper case for first letter + * copied from Twitter elephant bird + * https://github.com/twitter/elephant-bird/blob/master/core/src/main/java/com/twitter/elephantbird/util/Strings.java + * + * @param word string to be camelize + * @return camelized string + */ + public static String camelize(String word) { + return camelize(word, false); + } + + /** + * Camelize name (parameter, property, method, etc) + * + * @param word string to be camelize + * @param lowercaseFirstLetter lower case for first letter if set to true + * @return camelized string + */ + public static String camelize(String word, boolean lowercaseFirstLetter) { + // Replace all slashes with dots (package separator) + Pattern p = Pattern.compile("\\/(.?)"); + Matcher m = p.matcher(word); + while (m.find()) { + word = m.replaceFirst("." + m.group(1)/*.toUpperCase()*/); // FIXME: a parameter should not be assigned. Also declare the methods parameters as 'final'. + m = p.matcher(word); + } + + // case out dots + String[] parts = word.split("\\."); + StringBuilder f = new StringBuilder(); + for (String z : parts) { + if (z.length() > 0) { + f.append(Character.toUpperCase(z.charAt(0))).append(z.substring(1)); + } + } + word = f.toString(); + + m = p.matcher(word); + while (m.find()) { + word = m.replaceFirst("" + Character.toUpperCase(m.group(1).charAt(0)) + m.group(1).substring(1)/*.toUpperCase()*/); + m = p.matcher(word); + } + + // Uppercase the class name. + p = Pattern.compile("(\\.?)(\\w)([^\\.]*)$"); + m = p.matcher(word); + if (m.find()) { + String rep = m.group(1) + m.group(2).toUpperCase(Locale.ROOT) + m.group(3); + rep = rep.replaceAll("\\$", "\\\\\\$"); + word = m.replaceAll(rep); + } + + // Remove all underscores (underscore_case to camelCase) + p = Pattern.compile("(_)(.)"); + m = p.matcher(word); + while (m.find()) { + String original = m.group(2); + String upperCase = original.toUpperCase(Locale.ROOT); + if (original.equals(upperCase)) { + word = word.replaceFirst("_", ""); + } else { + word = m.replaceFirst(upperCase); + } + m = p.matcher(word); + } + + // Remove all hyphens (hyphen-case to camelCase) + p = Pattern.compile("(-)(.)"); + m = p.matcher(word); + while (m.find()) { + word = m.replaceFirst(m.group(2).toUpperCase(Locale.ROOT)); + m = p.matcher(word); + } + + if (lowercaseFirstLetter && word.length() > 0) { + int i = 0; + char charAt = word.charAt(i); + while (i + 1 < word.length() && !((charAt >= 'a' && charAt <= 'z') || (charAt >= 'A' && charAt <= 'Z'))) { + i = i + 1; + charAt = word.charAt(i); + } + i = i + 1; + word = word.substring(0, i).toLowerCase(Locale.ROOT) + word.substring(i); + } + + // remove all underscore + word = word.replaceAll("_", ""); + + return word; + } + + /** + * Return the name with escaped characters. + * + * @param name the name to be escaped + * @param replacementMap map of replacement characters for non-allowed characters + * @param charactersToAllow characters that are not escaped + * @param appendToReplacement String to append to replaced characters. + * @return the escaped word + *

+ * throws Runtime exception as word is not escaped properly. + */ + public static String escape(String name, Map replacementMap, + List charactersToAllow, String appendToReplacement) { + String result = name.chars().mapToObj(c -> { + String character = "" + (char) c; + if (charactersToAllow != null && charactersToAllow.contains(character)) { + return character; + } else if (replacementMap.containsKey(character)) { + return replacementMap.get(character) + (appendToReplacement != null ? appendToReplacement: ""); + } else { + return character; + } + }).reduce( (c1, c2) -> "" + c1 + c2).orElse(null); + + if (result != null) return result; + throw new RuntimeException("Word '" + name + "' could not be escaped."); + } +} 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 32254e5250..a4e5ea5a79 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 @@ -118,7 +118,7 @@ if(hasProperty('target') && target == 'android') { } ext { - swagger_annotations_version = "1.5.9" + swagger_annotations_version = "1.5.21" jackson_version = "2.8.7" {{#threetenbp}} threepane_version = "2.6.4" 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 d745ef7e86..a3dff94200 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,7 +9,7 @@ lazy val root = (project in file(".")). publishArtifact in (Compile, packageDoc) := false, resolvers += Resolver.mavenLocal, libraryDependencies ++= Seq( - "io.swagger" % "swagger-annotations" % "1.5.9" % "compile", + "io.swagger" % "swagger-annotations" % "1.5.21" % "compile", "io.github.openfeign" % "feign-core" % "9.4.0" % "compile", "io.github.openfeign" % "feign-jackson" % "9.4.0" % "compile", "io.github.openfeign" % "feign-slf4j" % "9.4.0" % "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 a616e68bcf..7a81b340af 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 @@ -114,8 +114,7 @@ - - src/main/java + src/main/java @@ -127,8 +126,7 @@ - - src/test/java + src/test/java @@ -191,7 +189,7 @@ io.swagger swagger-annotations - ${swagger-core-version} + ${swagger-annotations-version} @@ -294,12 +292,12 @@ {{#supportJava6}}1.6{{/supportJava6}}{{^supportJava6}}{{#java8}}1.8{{/java8}}{{^java8}}1.7{{/java8}}{{/supportJava6}} ${java.version} ${java.version} - 1.5.18 + 1.5.21 9.4.0 2.1.0 2.8.9 {{#threetenbp}} - 2.6.4 + 2.6.4 {{/threetenbp}} 4.12 1.0.0 diff --git a/modules/openapi-generator/src/main/resources/Java/libraries/google-api-client/build.gradle.mustache b/modules/openapi-generator/src/main/resources/Java/libraries/google-api-client/build.gradle.mustache index 1a2b2afc6c..acbe24a53f 100644 --- a/modules/openapi-generator/src/main/resources/Java/libraries/google-api-client/build.gradle.mustache +++ b/modules/openapi-generator/src/main/resources/Java/libraries/google-api-client/build.gradle.mustache @@ -118,7 +118,7 @@ if(hasProperty('target') && target == 'android') { } ext { - swagger_annotations_version = "1.5.17" + swagger_annotations_version = "1.5.21" jackson_version = "2.8.9" google_api_client_version = "1.23.0" jersey_common_version = "2.25.1" diff --git a/modules/openapi-generator/src/main/resources/Java/libraries/google-api-client/build.sbt.mustache b/modules/openapi-generator/src/main/resources/Java/libraries/google-api-client/build.sbt.mustache index d6b88c91d9..9f1aeaf157 100644 --- a/modules/openapi-generator/src/main/resources/Java/libraries/google-api-client/build.sbt.mustache +++ b/modules/openapi-generator/src/main/resources/Java/libraries/google-api-client/build.sbt.mustache @@ -9,7 +9,7 @@ lazy val root = (project in file(".")). publishArtifact in (Compile, packageDoc) := false, resolvers += Resolver.mavenLocal, libraryDependencies ++= Seq( - "io.swagger" % "swagger-annotations" % "1.5.17", + "io.swagger" % "swagger-annotations" % "1.5.21", "com.google.api-client" % "google-api-client" % "1.23.0", "org.glassfish.jersey.core" % "jersey-common" % "2.25.1", "com.fasterxml.jackson.core" % "jackson-core" % "2.8.9" % "compile", diff --git a/modules/openapi-generator/src/main/resources/Java/libraries/google-api-client/pom.mustache b/modules/openapi-generator/src/main/resources/Java/libraries/google-api-client/pom.mustache index 2fff29a15b..69aac87b27 100644 --- a/modules/openapi-generator/src/main/resources/Java/libraries/google-api-client/pom.mustache +++ b/modules/openapi-generator/src/main/resources/Java/libraries/google-api-client/pom.mustache @@ -114,8 +114,7 @@ - - src/main/java + src/main/java @@ -127,8 +126,7 @@ - - src/test/java + src/test/java @@ -287,15 +285,15 @@ UTF-8 - 1.5.17 + 1.5.21 1.23.0 2.25.1 2.8.9 {{#joda}} - 2.9.9 + 2.9.9 {{/joda}} {{#threetenbp}} - 2.6.4 + 2.6.4 {{/threetenbp}} 1.0.0 4.12 diff --git a/modules/openapi-generator/src/main/resources/Java/libraries/jersey2/build.gradle.mustache b/modules/openapi-generator/src/main/resources/Java/libraries/jersey2/build.gradle.mustache index 8f7c03adef..2a4a56b935 100644 --- a/modules/openapi-generator/src/main/resources/Java/libraries/jersey2/build.gradle.mustache +++ b/modules/openapi-generator/src/main/resources/Java/libraries/jersey2/build.gradle.mustache @@ -117,7 +117,7 @@ if(hasProperty('target') && target == 'android') { } ext { - swagger_annotations_version = "1.5.20" + swagger_annotations_version = "1.5.21" jackson_version = "2.9.6" {{#supportJava6}} jersey_version = "2.6" diff --git a/modules/openapi-generator/src/main/resources/Java/libraries/jersey2/build.sbt.mustache b/modules/openapi-generator/src/main/resources/Java/libraries/jersey2/build.sbt.mustache index 54902da798..cc2e9480b6 100644 --- a/modules/openapi-generator/src/main/resources/Java/libraries/jersey2/build.sbt.mustache +++ b/modules/openapi-generator/src/main/resources/Java/libraries/jersey2/build.sbt.mustache @@ -9,7 +9,7 @@ lazy val root = (project in file(".")). publishArtifact in (Compile, packageDoc) := false, resolvers += Resolver.mavenLocal, libraryDependencies ++= Seq( - "io.swagger" % "swagger-annotations" % "1.5.20", + "io.swagger" % "swagger-annotations" % "1.5.21", "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}}, 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 5c273fa147..93f2d9e2c9 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 @@ -114,8 +114,7 @@ - - src/main/java + src/main/java @@ -127,8 +126,7 @@ - - src/test/java + src/test/java @@ -212,7 +210,7 @@ io.swagger swagger-annotations - ${swagger-core-version} + ${swagger-annotations-version} @@ -318,7 +316,7 @@ UTF-8 - 1.5.20 + 1.5.21 {{^supportJava6}} 2.27 {{/supportJava6}} 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 54b90483f4..87608f2102 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 @@ -94,7 +94,7 @@ if(hasProperty('target') && target == 'android') { } ext { - swagger_annotations_version = "1.5.15" + swagger_annotations_version = "1.5.21" rest_assured_version = "3.1.0" junit_version = "4.12" gson_version = "2.6.1" 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 68f3eff08d..7a666ebace 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 @@ -9,7 +9,7 @@ lazy val root = (project in file(".")). publishArtifact in (Compile, packageDoc) := false, resolvers += Resolver.mavenLocal, libraryDependencies ++= Seq( - "io.swagger" % "swagger-annotations" % "1.5.15", + "io.swagger" % "swagger-annotations" % "1.5.21", "io.rest-assured" % "scala-support" % "3.1.0", "com.google.code.gson" % "gson" % "2.6.1", "io.gsonfire" % "gson-fire" % "1.8.2" % "compile", 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 1d0c171138..aa0c15d8b3 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 @@ -113,8 +113,7 @@ - - src/main/java + src/main/java @@ -126,8 +125,7 @@ - - src/test/java + src/test/java @@ -199,7 +197,7 @@ io.swagger swagger-annotations - ${swagger-core-version} + ${swagger-annotations-version} io.rest-assured @@ -245,7 +243,7 @@ UTF-8 - 1.5.15 + 1.5.21 3.1.0 2.6.1 1.8.2 diff --git a/modules/openapi-generator/src/main/resources/Java/libraries/resteasy/pom.mustache b/modules/openapi-generator/src/main/resources/Java/libraries/resteasy/pom.mustache index f2f7fa53a4..540c54c681 100644 --- a/modules/openapi-generator/src/main/resources/Java/libraries/resteasy/pom.mustache +++ b/modules/openapi-generator/src/main/resources/Java/libraries/resteasy/pom.mustache @@ -95,8 +95,7 @@ - - src/main/java + src/main/java @@ -108,8 +107,7 @@ - - src/test/java + src/test/java @@ -155,7 +153,7 @@ io.swagger swagger-annotations - ${swagger-core-version} + ${swagger-annotations-version} @@ -259,7 +257,7 @@ UTF-8 - 1.5.18 + 1.5.21 3.1.3.Final 2.8.6 2.6.4 diff --git a/modules/openapi-generator/src/main/resources/Java/libraries/resttemplate/build.gradle.mustache b/modules/openapi-generator/src/main/resources/Java/libraries/resttemplate/build.gradle.mustache index 9925cc43da..b50203a337 100644 --- a/modules/openapi-generator/src/main/resources/Java/libraries/resttemplate/build.gradle.mustache +++ b/modules/openapi-generator/src/main/resources/Java/libraries/resttemplate/build.gradle.mustache @@ -118,7 +118,7 @@ if(hasProperty('target') && target == 'android') { } ext { - swagger_annotations_version = "1.5.17" + swagger_annotations_version = "1.5.21" jackson_version = "2.8.9" spring_web_version = "4.3.9.RELEASE" jodatime_version = "2.9.9" diff --git a/modules/openapi-generator/src/main/resources/Java/libraries/resttemplate/pom.mustache b/modules/openapi-generator/src/main/resources/Java/libraries/resttemplate/pom.mustache index 0d371de6ea..10d84edafc 100644 --- a/modules/openapi-generator/src/main/resources/Java/libraries/resttemplate/pom.mustache +++ b/modules/openapi-generator/src/main/resources/Java/libraries/resttemplate/pom.mustache @@ -114,8 +114,7 @@ - - src/main/java + src/main/java @@ -127,8 +126,7 @@ - - src/test/java + src/test/java @@ -290,7 +288,7 @@ UTF-8 - 1.5.17 + 1.5.21 4.3.9.RELEASE 2.8.9 {{#joda}} diff --git a/modules/openapi-generator/src/main/resources/Java/libraries/retrofit/build.gradle.mustache b/modules/openapi-generator/src/main/resources/Java/libraries/retrofit/build.gradle.mustache index f0c1cbe4c8..45da8dd03b 100644 --- a/modules/openapi-generator/src/main/resources/Java/libraries/retrofit/build.gradle.mustache +++ b/modules/openapi-generator/src/main/resources/Java/libraries/retrofit/build.gradle.mustache @@ -109,7 +109,7 @@ ext { okhttp_version = "2.7.5" oltu_version = "1.0.1" retrofit_version = "1.9.0" - swagger_annotations_version = "1.5.8" + swagger_annotations_version = "1.5.21" junit_version = "4.12" jodatime_version = "2.9.3" {{#threetenbp}} diff --git a/modules/openapi-generator/src/main/resources/Java/libraries/retrofit/build.sbt.mustache b/modules/openapi-generator/src/main/resources/Java/libraries/retrofit/build.sbt.mustache index ffa308d528..9d5df5e223 100644 --- a/modules/openapi-generator/src/main/resources/Java/libraries/retrofit/build.sbt.mustache +++ b/modules/openapi-generator/src/main/resources/Java/libraries/retrofit/build.sbt.mustache @@ -11,7 +11,7 @@ lazy val root = (project in file(".")). libraryDependencies ++= Seq( "com.squareup.okhttp" % "okhttp" % "2.7.5" % "compile", "com.squareup.retrofit" % "retrofit" % "1.9.0" % "compile", - "io.swagger" % "swagger-annotations" % "1.5.8" % "compile", + "io.swagger" % "swagger-annotations" % "1.5.21" % "compile", "org.apache.oltu.oauth2" % "org.apache.oltu.oauth2.client" % "1.0.1" % "compile", "joda-time" % "joda-time" % "2.9.3" % "compile", {{#threetenbp}} diff --git a/modules/openapi-generator/src/main/resources/Java/libraries/retrofit/pom.mustache b/modules/openapi-generator/src/main/resources/Java/libraries/retrofit/pom.mustache index adbd6e99e5..155a8128e3 100644 --- a/modules/openapi-generator/src/main/resources/Java/libraries/retrofit/pom.mustache +++ b/modules/openapi-generator/src/main/resources/Java/libraries/retrofit/pom.mustache @@ -114,8 +114,7 @@ - - src/main/java + src/main/java @@ -127,8 +126,7 @@ - - src/test/java + src/test/java @@ -212,7 +210,7 @@ io.swagger swagger-annotations - ${swagger-core-version} + ${swagger-annotations-version} com.squareup.retrofit @@ -241,17 +239,15 @@ ${threetenbp-version} {{/threetenbp}} - {{#parcelableModel}} - - - com.google.android - android - 4.1.1.4 - provided - + + + com.google.android + android + 4.1.1.4 + provided + {{/parcelableModel}} - junit @@ -262,7 +258,7 @@ UTF-8 - 1.5.18 + 1.5.21 1.9.0 2.7.5 2.9.9 diff --git a/modules/openapi-generator/src/main/resources/Java/libraries/retrofit2/build.gradle.mustache b/modules/openapi-generator/src/main/resources/Java/libraries/retrofit2/build.gradle.mustache index 858b88971b..dfd1f6d940 100644 --- a/modules/openapi-generator/src/main/resources/Java/libraries/retrofit2/build.gradle.mustache +++ b/modules/openapi-generator/src/main/resources/Java/libraries/retrofit2/build.gradle.mustache @@ -129,8 +129,12 @@ ext { jackson_version = "2.7.8" play_version = "2.5.14" {{/play25}} + {{#play26}} + jackson_version = "2.8.10" + play_version = "2.6.7" + {{/play26}} {{/usePlayWS}} - swagger_annotations_version = "1.5.17" + swagger_annotations_version = "1.5.21" junit_version = "4.12" {{#useRxJava}} rx_java_version = "1.3.0" @@ -171,7 +175,13 @@ dependencies { compile "org.threeten:threetenbp:$threetenbp_version" {{/threetenbp}} {{#usePlayWS}} + {{#play26}} + compile "com.typesafe.play:play-ahc-ws_2.12:$play_version" + compile "javax.validation:validation-api:1.1.0.Final" + {{/play26}} + {{^play26}} compile "com.typesafe.play:play-java-ws_2.11:$play_version" + {{/play26}} compile "com.squareup.retrofit2:converter-jackson:$retrofit_version" compile "com.fasterxml.jackson.core:jackson-core:$jackson_version" compile "com.fasterxml.jackson.core:jackson-annotations:$jackson_version" diff --git a/modules/openapi-generator/src/main/resources/Java/libraries/retrofit2/build.sbt.mustache b/modules/openapi-generator/src/main/resources/Java/libraries/retrofit2/build.sbt.mustache index 66635daa97..e66ca78403 100644 --- a/modules/openapi-generator/src/main/resources/Java/libraries/retrofit2/build.sbt.mustache +++ b/modules/openapi-generator/src/main/resources/Java/libraries/retrofit2/build.sbt.mustache @@ -27,6 +27,13 @@ lazy val root = (project in file(".")). "com.fasterxml.jackson.core" % "jackson-annotations" % "2.7.8" % "compile", "com.fasterxml.jackson.core" % "jackson-databind" % "2.7.8" % "compile", {{/play25}} + {{#play26}} + "com.typesafe.play" % "play-ahc-ws_2.12" % "2.6.7" % "compile", + "javax.validation" % "validation-api" % "1.1.0.Final" % "compile", + "com.fasterxml.jackson.core" % "jackson-core" % "2.8.10" % "compile", + "com.fasterxml.jackson.core" % "jackson-annotations" % "2.8.10" % "compile", + "com.fasterxml.jackson.core" % "jackson-databind" % "2.8.10" % "compile", + {{/play26}} "com.squareup.retrofit2" % "converter-jackson" % "2.3.0" % "compile", {{/usePlayWS}} {{#useRxJava}} @@ -37,7 +44,7 @@ lazy val root = (project in file(".")). "com.squareup.retrofit2" % "adapter-rxjava2" % "2.3.0" % "compile", "io.reactivex.rxjava2" % "rxjava" % "2.1.1" % "compile", {{/useRxJava2}} - "io.swagger" % "swagger-annotations" % "1.5.17" % "compile", + "io.swagger" % "swagger-annotations" % "1.5.21" % "compile", "org.apache.oltu.oauth2" % "org.apache.oltu.oauth2.client" % "1.0.1" % "compile", {{#joda}} "joda-time" % "joda-time" % "2.9.9" % "compile", diff --git a/modules/openapi-generator/src/main/resources/Java/libraries/retrofit2/play26/ApiClient.mustache b/modules/openapi-generator/src/main/resources/Java/libraries/retrofit2/play26/ApiClient.mustache new file mode 100644 index 0000000000..d59912773c --- /dev/null +++ b/modules/openapi-generator/src/main/resources/Java/libraries/retrofit2/play26/ApiClient.mustache @@ -0,0 +1,205 @@ +package {{invokerPackage}}; + +import java.io.File; +import java.io.IOException; +import java.lang.annotation.Annotation; +import java.lang.reflect.Type; +import java.nio.file.Files; +import java.nio.file.Paths; +import java.util.*; + +import com.fasterxml.jackson.databind.ObjectMapper; +import retrofit2.Converter; +import retrofit2.Retrofit; +import retrofit2.converter.scalars.ScalarsConverterFactory; +import retrofit2.converter.jackson.JacksonConverterFactory; + +import play.libs.Json; +import play.libs.ws.WSClient; + +import {{invokerPackage}}.Play26CallAdapterFactory; +import {{invokerPackage}}.Play26CallFactory; + +import okhttp3.Interceptor; +import okhttp3.ResponseBody; +import {{invokerPackage}}.auth.ApiKeyAuth; +import {{invokerPackage}}.auth.Authentication; + +/** + * API client + */ +public class ApiClient { + + /** Underlying HTTP-client */ + private WSClient wsClient; + + /** Creates HTTP call instances */ + private Play26CallFactory callFactory; + + /** Create {@link java.util.concurrent.CompletionStage} instances from HTTP calls */ + private Play26CallAdapterFactory callAdapterFactory; + + /** Supported auths */ + private Map authentications; + + /** API base path */ + private String basePath = "{{{basePath}}}"; + + /** Default ObjectMapper */ + private ObjectMapper defaultMapper; + + public ApiClient(WSClient wsClient) { + this(); + this.wsClient = wsClient; + } + + public ApiClient() { + // Setup authentications (key: authentication name, value: authentication). + authentications = new HashMap<>();{{#authMethods}}{{#isBasic}} + // authentications.put("{{name}}", new HttpBasicAuth());{{/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); + } + + /** + * Creates a retrofit2 client for given API interface + */ + public S createService(Class serviceClass) { + if(!basePath.endsWith("/")) { + basePath = basePath + "/"; + } + + Map extraHeaders = new HashMap<>(); + List extraQueryParams = new ArrayList<>(); + + for (String authName : authentications.keySet()) { + Authentication auth = authentications.get(authName); + if (auth == null) throw new RuntimeException("Authentication undefined: " + authName); + + auth.applyToParams(extraQueryParams, extraHeaders); + } + + if (callFactory == null) { + callFactory = new Play26CallFactory(wsClient, extraHeaders, extraQueryParams); + } + if (callAdapterFactory == null) { + callAdapterFactory = new Play26CallAdapterFactory(); + } + if (defaultMapper == null) { + defaultMapper = Json.mapper(); + } + + return new Retrofit.Builder() + .baseUrl(basePath) + .addConverterFactory(new FileConverter()) + .addConverterFactory(ScalarsConverterFactory.create()) + .addConverterFactory(JacksonConverterFactory.create(defaultMapper)) + .callFactory(callFactory) + .addCallAdapterFactory(callAdapterFactory) + .build() + .create(serviceClass); + } + + /** + * Helper method to set API base path + */ + public ApiClient setBasePath(String basePath) { + this.basePath = basePath; + return this; + } + + /** + * Get authentications (key: authentication name, value: authentication). + */ + 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 API key value for the first API key authentication. + */ + public ApiClient setApiKey(String apiKey) { + for (Authentication auth : authentications.values()) { + if (auth instanceof ApiKeyAuth) { + ((ApiKeyAuth) auth).setApiKey(apiKey); + return this; + } + } + + throw new RuntimeException("No API key authentication configured!"); + } + + /** + * Helper method to set API key prefix for the first API key authentication. + */ + public ApiClient setApiKeyPrefix(String apiKeyPrefix) { + for (Authentication auth : authentications.values()) { + if (auth instanceof ApiKeyAuth) { + ((ApiKeyAuth) auth).setApiKeyPrefix(apiKeyPrefix); + return this; + } + } + + throw new RuntimeException("No API key authentication configured!"); + } + + /** + * Helper method to set HTTP call instances factory + */ + public ApiClient setCallFactory(Play26CallFactory callFactory) { + this.callFactory = callFactory; + return this; + } + + /** + * Helper method to set {@link java.util.concurrent.CompletionStage} instances factory + */ + public ApiClient setCallAdapterFactory(Play26CallAdapterFactory callAdapterFactory) { + this.callAdapterFactory = callAdapterFactory; + return this; + } + + /** + * Helper method to set Jackson's {@link ObjectMapper} + */ + public ApiClient setObjectMapper(ObjectMapper mapper) { + this.defaultMapper = mapper; + return this; + } + + static class FileConverter extends Converter.Factory { + + @Override + public Converter responseBodyConverter(Type type, + Annotation[] annotations, Retrofit retrofit) { + + if (!File.class.getTypeName().equals(type.getTypeName())) { + return null; + } + + return new Converter() { + + @Override + public File convert(ResponseBody value) throws IOException { + + File file = File.createTempFile("retrofit-file", ".tmp"); + Files.write(Paths.get(file.getPath()), value.bytes()); + return file; + } + }; + } + } + +} diff --git a/modules/openapi-generator/src/main/resources/Java/libraries/retrofit2/play26/Play26CallAdapterFactory.mustache b/modules/openapi-generator/src/main/resources/Java/libraries/retrofit2/play26/Play26CallAdapterFactory.mustache new file mode 100644 index 0000000000..efbc0ac298 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/Java/libraries/retrofit2/play26/Play26CallAdapterFactory.mustache @@ -0,0 +1,116 @@ +package {{invokerPackage}}; + +import java.util.concurrent.CompletionStage; +import retrofit2.*; + +import java.lang.annotation.Annotation; +import java.lang.reflect.ParameterizedType; +import java.lang.reflect.Type; +import java.lang.reflect.WildcardType; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.CompletionStage; +import java.util.function.Function; + +/** + * Creates {@link CallAdapter} instances that convert {@link Call} into {@link java.util.concurrent.CompletionStage} + */ +public class Play26CallAdapterFactory extends CallAdapter.Factory { + + private Function exceptionConverter = Function.identity(); + + public Play26CallAdapterFactory() { + } + + public Play26CallAdapterFactory( + Function exceptionConverter) { + this.exceptionConverter = exceptionConverter; + } + + @Override + public CallAdapter get(Type returnType, Annotation[] annotations, Retrofit retrofit) { + if (!(returnType instanceof ParameterizedType)) { + return null; + } + + ParameterizedType type = (ParameterizedType) returnType; + if (type.getRawType() != CompletionStage.class) { + return null; + } + + return createAdapter((ParameterizedType) returnType); + } + + private CallAdapter> createAdapter(ParameterizedType returnType) { + // Get CompletionStage type argument + Type[] types = returnType.getActualTypeArguments(); + if (types.length != 1) { + throw new IllegalStateException("Must be exactly one type parameter"); + } + + Type resultType = types[0]; + Class rawTypeParam = getRawType(resultType); + + boolean includeResponse = false; + if (rawTypeParam == Response.class) { + if (!(resultType instanceof ParameterizedType)) { + throw new IllegalStateException("Response must be parameterized" + + " as Response"); + } + resultType = ((ParameterizedType) resultType).getActualTypeArguments()[0]; + includeResponse = true; + } + + return new ValueAdapter(resultType, includeResponse, exceptionConverter); + } + + /** + * Adpater that coverts values returned by API interface into CompletionStage + */ + private static final class ValueAdapter implements CallAdapter> { + + private final Type responseType; + private final boolean includeResponse; + private Function exceptionConverter; + + ValueAdapter(Type responseType, boolean includeResponse, + Function exceptionConverter) { + this.responseType = responseType; + this.includeResponse = includeResponse; + this.exceptionConverter = exceptionConverter; + } + + @Override + public Type responseType() { + return responseType; + } + + @Override + public CompletionStage adapt(final Call call) { + final CompletableFuture promise = new CompletableFuture(); + + call.enqueue(new Callback() { + + @Override + public void onResponse(Call call, Response response) { + if (response.isSuccessful()) { + if (includeResponse) { + promise.complete((R) response); + } else { + promise.complete(response.body()); + } + } else { + promise.completeExceptionally(exceptionConverter.apply(new HttpException(response))); + } + } + + @Override + public void onFailure(Call call, Throwable t) { + promise.completeExceptionally(t); + } + + }); + + return promise; + } + } +} diff --git a/modules/openapi-generator/src/main/resources/Java/libraries/retrofit2/play26/Play26CallFactory.mustache b/modules/openapi-generator/src/main/resources/Java/libraries/retrofit2/play26/Play26CallFactory.mustache new file mode 100644 index 0000000000..6e4180341b --- /dev/null +++ b/modules/openapi-generator/src/main/resources/Java/libraries/retrofit2/play26/Play26CallFactory.mustache @@ -0,0 +1,245 @@ +package {{invokerPackage}}; + +import okhttp3.*; +import okio.Buffer; +import okio.BufferedSource; +import play.libs.ws.WSClient; +import play.libs.ws.WSRequest; +import play.libs.ws.WSResponse; +import play.libs.ws.WSRequestFilter; + +import java.io.IOException; +import java.net.MalformedURLException; +import java.net.URI; +import java.net.URISyntaxException; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.concurrent.CompletionStage; +import java.util.concurrent.Executor; + +/** + * Creates {@link Call} instances that invoke underlying {@link WSClient} + */ +public class Play26CallFactory implements okhttp3.Call.Factory { + + /** PlayWS http client */ + private final WSClient wsClient; + + /** Extra headers to add to request */ + private Map extraHeaders = new HashMap<>(); + + /** Extra query parameters to add to request */ + private List extraQueryParams = new ArrayList<>(); + + /** Filters (interceptors) */ + private List filters = new ArrayList<>(); + + /** Executor for WSClient */ + private Executor executor; + + public Play26CallFactory(WSClient wsClient) { + this.wsClient = wsClient; + } + + public Play26CallFactory(WSClient wsClient, List filters) { + this.wsClient = wsClient; + this.filters.addAll(filters); + } + + public Play26CallFactory(WSClient wsClient, Map extraHeaders, + List extraQueryParams) { + this.wsClient = wsClient; + + this.extraHeaders.putAll(extraHeaders); + this.extraQueryParams.addAll(extraQueryParams); + } + + public Play26CallFactory withExecutor(Executor executor) { + this.executor = executor; + return this; + } + + @Override + public Call newCall(Request request) { + // add extra headers + Request.Builder rb = request.newBuilder(); + for (Map.Entry header : this.extraHeaders.entrySet()) { + rb.addHeader(header.getKey(), header.getValue()); + } + + // add extra query params + if (!this.extraQueryParams.isEmpty()) { + String newQuery = request.url().uri().getQuery(); + for (Pair queryParam : this.extraQueryParams) { + String param = String.format("%s=%s", queryParam.getName(), queryParam.getValue()); + if (newQuery == null) { + newQuery = param; + } else { + newQuery += "&" + param; + } + } + + URI newUri; + try { + newUri = new URI(request.url().uri().getScheme(), request.url().uri().getAuthority(), + request.url().uri().getPath(), newQuery, request.url().uri().getFragment()); + rb.url(newUri.toURL()); + } catch (MalformedURLException | URISyntaxException e) { + throw new RuntimeException("Error while updating an url", e); + } + } + + return new PlayWSCall(wsClient, this.executor, this.filters, rb.build()); + } + + /** + * Call implementation that delegates to Play WS Client + */ + static class PlayWSCall implements Call { + + private final WSClient wsClient; + private WSRequest wsRequest; + private List filters; + private Executor executor = java.util.concurrent.ForkJoinPool.commonPool(); + + private final Request request; + + public PlayWSCall(WSClient wsClient, Executor executor, List filters, Request request) { + this.wsClient = wsClient; + this.request = request; + this.filters = filters; + + if (executor != null) { + this.executor = executor; + } + } + + @Override + public Request request() { + return request; + } + + @Override + public void enqueue(final okhttp3.Callback responseCallback) { + final Call call = this; + final CompletionStage promise = executeAsync(); + + promise.whenCompleteAsync((v, t) -> { + if (t != null) { + if (t instanceof IOException) { + responseCallback.onFailure(call, (IOException) t); + } else { + responseCallback.onFailure(call, new IOException(t)); + } + } else { + try { + responseCallback.onResponse(call, PlayWSCall.this.toWSResponse(v)); + } catch (Exception e) { + responseCallback.onFailure(call, new IOException(e)); + } + } + }, this.executor); + } + + CompletionStage executeAsync() { + try { + HttpUrl url = request.url(); + wsRequest = wsClient.url(url.scheme()+ "://" + url.host() + ":" + url.port() + url.encodedPath()); + url.queryParameterNames().forEach(queryParam -> { + wsRequest.addQueryParameter(queryParam, url.queryParameter(queryParam)); + }); + addHeaders(wsRequest); + if (request.body() != null) { + addBody(wsRequest); + } + filters.stream().forEach(f -> wsRequest.setRequestFilter(f)); + + return wsRequest.execute(request.method()); + } catch (Exception e) { + throw new RuntimeException(e.getMessage(), e); + } + } + + private void addHeaders(WSRequest wsRequest) { + for(Map.Entry> entry : request.headers().toMultimap().entrySet()) { + List values = entry.getValue(); + for (String value : values) { + wsRequest.setHeader(entry.getKey(), value); + } + } + } + + private void addBody(WSRequest wsRequest) throws IOException { + MediaType mediaType = request.body().contentType(); + if (mediaType != null) { + wsRequest.setContentType(mediaType.toString()); + } + + Buffer buffer = new Buffer(); + request.body().writeTo(buffer); + wsRequest.setBody(buffer.inputStream()); + } + + private Response toWSResponse(final WSResponse r) { + final Response.Builder builder = new Response.Builder(); + builder.request(request) + .code(r.getStatus()) + .body(new ResponseBody() { + + @Override + public MediaType contentType() { + return r.getSingleHeader("Content-Type") + .map(MediaType::parse) + .orElse(null); + } + + @Override + public long contentLength() { + return r.asByteArray().length; + } + + @Override + public BufferedSource source() { + return new Buffer().write(r.asByteArray()); + } + }); + + for (Map.Entry> entry : r.getAllHeaders().entrySet()) { + for (String value : entry.getValue()) { + builder.addHeader(entry.getKey(), value); + } + } + + builder.message(r.getStatusText()); + builder.protocol(Protocol.HTTP_1_1); + return builder.build(); + } + + @Override + public Response execute() throws IOException { + throw new UnsupportedOperationException("Not supported"); + } + + @Override + public void cancel() { + throw new UnsupportedOperationException("Not supported"); + } + + @Override + public PlayWSCall clone() { + throw new UnsupportedOperationException("Not supported"); + } + + @Override + public boolean isExecuted() { + return false; + } + + @Override + public boolean isCanceled() { + return false; + } + } +} diff --git a/modules/openapi-generator/src/main/resources/Java/libraries/retrofit2/play26/api.mustache b/modules/openapi-generator/src/main/resources/Java/libraries/retrofit2/play26/api.mustache new file mode 100644 index 0000000000..b435a16c05 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/Java/libraries/retrofit2/play26/api.mustache @@ -0,0 +1,59 @@ +package {{package}}; + +import {{invokerPackage}}.CollectionFormats.*; + +{{#useRxJava}}import rx.Observable;{{/useRxJava}} +{{#useRxJava2}}import io.reactivex.Observable;{{/useRxJava2}} +{{#doNotUseRx}}import retrofit2.Call;{{/doNotUseRx}} +import retrofit2.http.*; + +import okhttp3.RequestBody; +import okhttp3.ResponseBody; +import okhttp3.MultipartBody; + +{{#imports}}import {{import}}; +{{/imports}} + +{{^fullJavaUtil}} +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +{{/fullJavaUtil}} + +import java.util.concurrent.*; +import retrofit2.Response; + +{{#operations}} +public interface {{classname}} { + {{#operation}} + /** + * {{summary}} + * {{notes}} +{{#allParams}} + * @param {{paramName}} {{description}}{{#required}} (required){{/required}}{{^required}} (optional{{#defaultValue}}, default to {{.}}{{/defaultValue}}){{/required}} +{{/allParams}} + * @return Call<{{#returnType}}{{returnType}}{{/returnType}}{{^returnType}}Void{{/returnType}}> + */ + {{#formParams}} + {{#-first}} + {{#isMultipart}}@retrofit2.http.Multipart{{/isMultipart}}{{^isMultipart}}@retrofit2.http.FormUrlEncoded{{/isMultipart}} + {{/-first}} + {{/formParams}} + {{^formParams}} + {{#prioritizedContentTypes}} + {{#-first}} + @Headers({ + "Content-Type:{{{mediaType}}}" + }) + {{/-first}} + {{/prioritizedContentTypes}} + {{/formParams}} + @{{httpMethod}}("{{{path}}}") + CompletionStage> {{operationId}}({{^allParams}});{{/allParams}} + {{#allParams}}{{>libraries/retrofit2/queryParams}}{{>libraries/retrofit2/pathParams}}{{>libraries/retrofit2/headerParams}}{{>libraries/retrofit2/bodyParams}}{{>libraries/retrofit2/formParams}}{{#hasMore}}, {{/hasMore}}{{^hasMore}} + );{{/hasMore}}{{/allParams}} + + {{/operation}} +} +{{/operations}} diff --git a/modules/openapi-generator/src/main/resources/Java/libraries/retrofit2/pom.mustache b/modules/openapi-generator/src/main/resources/Java/libraries/retrofit2/pom.mustache index f23642e46b..3028604c36 100644 --- a/modules/openapi-generator/src/main/resources/Java/libraries/retrofit2/pom.mustache +++ b/modules/openapi-generator/src/main/resources/Java/libraries/retrofit2/pom.mustache @@ -114,8 +114,7 @@ - - src/main/java + src/main/java @@ -127,8 +126,7 @@ - - src/test/java + src/test/java @@ -191,7 +189,7 @@ io.swagger swagger-annotations - ${swagger-core-version} + ${swagger-annotations-version} com.squareup.retrofit2 @@ -262,7 +260,6 @@ ${retrofit-version} {{/useRxJava2}} - {{#usePlayWS}} @@ -291,22 +288,40 @@ ${jackson-version} {{#withXml}} - com.fasterxml.jackson.dataformat jackson-dataformat-xml ${jackson-version} - {{/withXml}} + {{#play24}} com.typesafe.play play-java-ws_2.11 ${play-version} + {{/play24}} + {{#play25}} + + com.typesafe.play + play-java-ws_2.11 + ${play-version} + + {{/play25}} + {{#play26}} + + com.typesafe.play + play-ahc-ws_2.12 + ${play-version} + + + javax.validation + validation-api + 1.1.0.Final + + {{/play26}} {{/usePlayWS}} - {{#parcelableModel}} @@ -316,7 +331,6 @@ provided {{/parcelableModel}} - junit @@ -331,29 +345,33 @@ ${java.version} ${java.version} 1.8.0 - 1.5.18 + 1.5.21 {{#usePlayWS}} - {{#play24}} - 2.6.6 - 2.4.11 - {{/play24}} - {{#play25}} - 2.7.8 - 2.5.15 - {{/play25}} + {{#play24}} + 2.6.6 + 2.4.11 + {{/play24}} + {{#play25}} + 2.7.8 + 2.5.15 + {{/play25}} + {{#play26}} + 2.8.10 + 2.6.7 + {{/play26}} {{/usePlayWS}} 2.3.0 {{#useRxJava}} - 1.3.0 + 1.3.0 {{/useRxJava}} {{#useRxJava2}} - 2.1.1 + 2.1.1 {{/useRxJava2}} {{#joda}} - 2.9.9 + 2.9.9 {{/joda}} {{#threetenbp}} - 1.3.5 + 1.3.5 {{/threetenbp}} 1.0.1 4.12 diff --git a/modules/openapi-generator/src/main/resources/Java/libraries/vertx/build.gradle.mustache b/modules/openapi-generator/src/main/resources/Java/libraries/vertx/build.gradle.mustache index e1c956d5f7..1f2ebac439 100644 --- a/modules/openapi-generator/src/main/resources/Java/libraries/vertx/build.gradle.mustache +++ b/modules/openapi-generator/src/main/resources/Java/libraries/vertx/build.gradle.mustache @@ -26,7 +26,7 @@ task execute(type:JavaExec) { } ext { - swagger_annotations_version = "1.5.17" + swagger_annotations_version = "1.5.21" jackson_version = "{{^threetenbp}}2.8.9{{/threetenbp}}{{#threetenbp}}2.6.4{{/threetenbp}}" vertx_version = "3.4.2" junit_version = "4.12" diff --git a/modules/openapi-generator/src/main/resources/Java/libraries/vertx/pom.mustache b/modules/openapi-generator/src/main/resources/Java/libraries/vertx/pom.mustache index 32f94b6263..b8d7e513d6 100644 --- a/modules/openapi-generator/src/main/resources/Java/libraries/vertx/pom.mustache +++ b/modules/openapi-generator/src/main/resources/Java/libraries/vertx/pom.mustache @@ -114,8 +114,7 @@ - - src/main/java + src/main/java @@ -127,8 +126,7 @@ - - src/test/java + src/test/java @@ -200,7 +198,7 @@ io.swagger swagger-annotations - ${swagger-core-version} + ${swagger-annotations-version} @@ -271,7 +269,7 @@ UTF-8 3.4.2 - 1.5.18 + 1.5.21 {{^threetenbp}}2.8.9{{/threetenbp}}{{#threetenbp}}2.6.4{{/threetenbp}} 4.12 diff --git a/modules/openapi-generator/src/main/resources/Java/libraries/webclient/ApiClient.mustache b/modules/openapi-generator/src/main/resources/Java/libraries/webclient/ApiClient.mustache index 28260368a9..41b81a004c 100644 --- a/modules/openapi-generator/src/main/resources/Java/libraries/webclient/ApiClient.mustache +++ b/modules/openapi-generator/src/main/resources/Java/libraries/webclient/ApiClient.mustache @@ -33,6 +33,7 @@ import org.springframework.web.reactive.function.BodyInserters; import org.springframework.web.reactive.function.client.ExchangeStrategies; import reactor.core.publisher.Mono; import reactor.core.publisher.Flux; +import java.util.Optional; import java.io.BufferedReader; import java.io.IOException; @@ -76,7 +77,7 @@ public class ApiClient { } private HttpHeaders defaultHeaders = new HttpHeaders(); - + private String basePath = "{{basePath}}"; private final WebClient webClient; @@ -87,16 +88,22 @@ public class ApiClient { public ApiClient() { this.dateFormat = createDefaultDateFormat(); - this.webClient = buildWebClient(new ObjectMapper(), this.dateFormat); + this.webClient = buildWebClient(new ObjectMapper(), dateFormat); + this.init(); } public ApiClient(ObjectMapper mapper, DateFormat format) { this(buildWebClient(mapper.copy(), format), format); } + public ApiClient(WebClient webClient, ObjectMapper mapper, DateFormat format) { + this(Optional.ofNullable(webClient).orElseGet(() ->buildWebClient(mapper.copy(), format)), format); + } + private ApiClient(WebClient webClient, DateFormat format) { this.webClient = webClient; this.dateFormat = format; + this.init(); } public DateFormat createDefaultDateFormat() { @@ -104,7 +111,7 @@ public class ApiClient { dateFormat.setTimeZone(TimeZone.getTimeZone("UTC")); return dateFormat; } - + protected void init() { // Setup authentications (key: authentication name, value: authentication). authentications = new HashMap();{{#authMethods}}{{#isBasic}} @@ -132,7 +139,7 @@ public class ApiClient { return webClient.build(); } - + /** * Get the current base path * @return String the base path @@ -585,7 +592,7 @@ public class ApiClient { auth.applyToParams(queryParams, headerParams); } } - + private class ApiClientHttpRequestInterceptor implements ClientHttpRequestInterceptor { private final Log log = LogFactory.getLog(ApiClientHttpRequestInterceptor.class); @@ -624,7 +631,7 @@ public class ApiClient { builder.setLength(builder.length() - 1); // Get rid of trailing comma return builder.toString(); } - + private String bodyToString(InputStream body) throws IOException { StringBuilder builder = new StringBuilder(); BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(body, StandardCharsets.UTF_8)); diff --git a/modules/openapi-generator/src/main/resources/Java/pom.mustache b/modules/openapi-generator/src/main/resources/Java/pom.mustache index 0c1501e115..275a5c869a 100644 --- a/modules/openapi-generator/src/main/resources/Java/pom.mustache +++ b/modules/openapi-generator/src/main/resources/Java/pom.mustache @@ -114,8 +114,7 @@ - - src/main/java + src/main/java @@ -127,8 +126,7 @@ - - src/test/java + src/test/java @@ -327,7 +325,7 @@ UTF-8 - 1.5.17 + 1.5.21 1.19.4 {{#supportJava6}} 2.5 diff --git a/modules/openapi-generator/src/main/resources/JavaJaxRS/README.mustache b/modules/openapi-generator/src/main/resources/JavaJaxRS/README.mustache index dcf00bfdcf..98a0fd8241 100644 --- a/modules/openapi-generator/src/main/resources/JavaJaxRS/README.mustache +++ b/modules/openapi-generator/src/main/resources/JavaJaxRS/README.mustache @@ -1,11 +1,12 @@ -# Swagger Jersey generated server +# JAX-RS/Jersey server with OpenAPI ## Overview -This server was generated by the [OpenAPI Generator](https://openapi-generator.tech) project. By using the -[OpenAPI-Spec](https://openapis.org) from a remote server, you can easily generate a server stub. This -is an example of building a OpenAPI-enabled JAX-RS server. +This server was generated by the [OpenAPI Generator](https://openapi-generator.tech) project. By using an +[OpenAPI-Spec](https://openapis.org), you can easily generate a server stub. +This is an example of building a OpenAPI-enabled JAX-RS server. This example uses the [JAX-RS](https://jax-rs-spec.java.net/) framework. +Jersey is used as JAX-RS implementation, `io.swagger:swagger-jersey2-jaxrs` is used to derive the OpenAPI Specification from the annotated code. To run the server, please execute the following: @@ -13,10 +14,10 @@ To run the server, please execute the following: mvn clean package jetty:run ``` -You can then view the swagger listing here: +You can then view the OpenAPI v2 specification here: ``` -http://localhost:{{serverPort}}{{contextPath}}/openapi.json +http://localhost:{{serverPort}}{{contextPath}}/swagger.json ``` Note that if you have configured the `host` to be something other than localhost, the calls through diff --git a/modules/openapi-generator/src/main/resources/JavaJaxRS/resteasy/README.mustache b/modules/openapi-generator/src/main/resources/JavaJaxRS/resteasy/README.mustache index 45f4438e36..647f45ff5a 100644 --- a/modules/openapi-generator/src/main/resources/JavaJaxRS/resteasy/README.mustache +++ b/modules/openapi-generator/src/main/resources/JavaJaxRS/resteasy/README.mustache @@ -1,22 +1,23 @@ -# OpenAPI generated server +# JAX-RS/RESTEasy server with OpenAPI ## Overview -This server was generated by the [OpenAPI Generator](https://openapi-generator.tech) project. By using the -[OpenAPI-Spec](https://openapis.org) from a remote server, you can easily generate a server stub. This -is an example of building a OpenAPI-enabled JAX-RS server. +This server was generated by the [OpenAPI Generator](https://openapi-generator.tech) project. By using an +[OpenAPI-Spec](https://openapis.org), you can easily generate a server stub. +This is an example of building a OpenAPI-enabled JAX-RS server. This example uses the [JAX-RS](https://jax-rs-spec.java.net/) framework. +RESTEasy is used as JAX-RS implementation library and is defined as dependency. To run the server, please execute the following: ``` -mvn clean package jetty:run +mvn -Djetty.http.port={{serverPort}} package org.eclipse.jetty:jetty-maven-plugin:run ``` -You can then view the swagger listing here: +You can then view the OpenAPI v2 specification here: ``` -http://localhost:{{serverPort}}{{contextPath}}/openapi.json +http://localhost:{{serverPort}}{{contextPath}}/swagger.json ``` Note that if you have configured the `host` to be something other than localhost, the calls through diff --git a/modules/openapi-generator/src/main/resources/JavaJaxRS/resteasy/eap/README.mustache b/modules/openapi-generator/src/main/resources/JavaJaxRS/resteasy/eap/README.mustache index 5e1dce9b0a..ed1aa06a3c 100644 --- a/modules/openapi-generator/src/main/resources/JavaJaxRS/resteasy/eap/README.mustache +++ b/modules/openapi-generator/src/main/resources/JavaJaxRS/resteasy/eap/README.mustache @@ -1,18 +1,18 @@ -# OpenAPI generated server +# JAX-RS/Resteasy server with OpenAPI for Jboss EAP ## Overview -This server was generated by the [OpenAPI Generator](https://openapi-generator.tech) project. By using the -[OpenAPI-Spec](https://openapis.org) from a remote server, you can easily generate a server stub. This -is an example of building a OpenAPI-enabled JAX-RS server. +This server was generated by the [OpenAPI Generator](https://openapi-generator.tech) project. By using an +[OpenAPI-Spec](https://openapis.org), you can easily generate a server stub. +This is an example of building a OpenAPI-enabled JAX-RS server. This example uses the [JAX-RS](https://jax-rs-spec.java.net/) framework for Jboss Resteasy. You can deploy the WAR file to Jboss EAP or any other JEE server supporting Jboss Resteasy. -You can then view the swagger listing here: +You can then view the OpenAPI v2 specification here: ``` -http://localhost:{{serverPort}}{{contextPath}}/openapi.json +http://localhost:{{serverPort}}{{contextPath}}/swagger.json ``` Note that if you have configured the `host` to be something other than localhost, the calls through diff --git a/modules/openapi-generator/src/main/resources/JavaJaxRS/spec/README.mustache b/modules/openapi-generator/src/main/resources/JavaJaxRS/spec/README.mustache new file mode 100644 index 0000000000..93c1ccb781 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/JavaJaxRS/spec/README.mustache @@ -0,0 +1,33 @@ +# JAX-RS server with OpenAPI + +## Overview +This server was generated by the [OpenAPI Generator](https://openapi-generator.tech) project. By using an +[OpenAPI-Spec](https://openapis.org), you can easily generate a server stub. + +This is an example of building a OpenAPI-enabled JAX-RS server. +This example uses the [JAX-RS](https://jax-rs-spec.java.net/) framework. + +{{#interfaceOnly}} +This project produces a jar that defines some interfaces. +The jar can be used in combination with an other project providing the implementation. +{{/interfaceOnly}} + +{{^interfaceOnly}} +The JAX-RS implementation needs to be provided by the application server you are deploying on. + +To run the server from the command line, you can use maven to provision an start a TomEE Server. +Please execute the following: + +``` +mvn -Dtomee-embedded-plugin.http={{serverPort}} package org.apache.tomee.maven:tomee-embedded-maven-plugin:7.0.5:run +``` + +You can then call your server endpoints under: + +``` +http://localhost:{{serverPort}}{{contextPath}}/ +``` + +Note that if you have configured the `host` to be something other than localhost, the calls through +swagger-ui will be directed to that host and not localhost! +{{/interfaceOnly}} 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 a5c3d07b08..b557cd203f 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 @@ -29,6 +29,7 @@ org.openapitools.codegen.languages.GoServerCodegen org.openapitools.codegen.languages.GroovyClientCodegen org.openapitools.codegen.languages.KotlinClientCodegen org.openapitools.codegen.languages.KotlinServerCodegen +org.openapitools.codegen.languages.KotlinSpringServerCodegen org.openapitools.codegen.languages.HaskellHttpClientCodegen org.openapitools.codegen.languages.HaskellServantCodegen org.openapitools.codegen.languages.JavaClientCodegen @@ -90,4 +91,4 @@ org.openapitools.codegen.languages.TypeScriptAureliaClientCodegen org.openapitools.codegen.languages.TypeScriptFetchClientCodegen org.openapitools.codegen.languages.TypeScriptInversifyClientCodegen org.openapitools.codegen.languages.TypeScriptJqueryClientCodegen -org.openapitools.codegen.languages.TypeScriptNodeClientCodegen +org.openapitools.codegen.languages.TypeScriptNodeClientCodegen \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/codegen/README.mustache b/modules/openapi-generator/src/main/resources/codegen/README.mustache index d8c6ab3ca3..7b27487183 100644 --- a/modules/openapi-generator/src/main/resources/codegen/README.mustache +++ b/modules/openapi-generator/src/main/resources/codegen/README.mustache @@ -1,15 +1,16 @@ # OpenAPI Generator for the {{name}} library ## Overview -This is a boiler-plate project to generate your own client library with Swagger. Its goal is -to get you started with the basic plumbing so you can put in your own logic. It won't work without -your changes applied. +This is a boiler-plate project to generate your own project derived from an OpenAPI specification. +Its goal is to get you started with the basic plumbing so you can put in your own logic. +It won't work without your changes applied. -## What's Swagger? -The goal of Swagger™ is to define a standard, language-agnostic interface to REST APIs which allows both humans and computers to discover and understand the capabilities of the service without access to source code, documentation, or through network traffic inspection. When properly defined via Swagger, a consumer can understand and interact with the remote service with a minimal amount of implementation logic. Similar to what interfaces have done for lower-level programming, Swagger removes the guesswork in calling the service. +## What's OpenAPI +The goal of OpenAPI is to define a standard, language-agnostic interface to REST APIs which allows both humans and computers to discover and understand the capabilities of the service without access to source code, documentation, or through network traffic inspection. +When properly described with OpenAPI, a consumer can understand and interact with the remote service with a minimal amount of implementation logic. +Similar to what interfaces have done for lower-level programming, OpenAPI removes the guesswork in calling the service. - -Check out [OpenAPI-Spec](https://github.com/OAI/OpenAPI-Specification) for additional information about the Swagger project, including additional libraries with support for other languages and more. +Check out [OpenAPI-Spec](https://github.com/OAI/OpenAPI-Specification) for additional information about the OpenAPI project, including additional libraries with support for other languages and more. ## How do I use this? At this point, you've likely generated a client setup. It will include something along these lines: @@ -43,10 +44,17 @@ Once modified, you can run this: mvn package ``` -In your generator project. A single jar file will be produced in `target`. You can now use that with codegen: +In your generator project. A single jar file will be produced in `target`. You can now use that with [OpenAPI Generator](https://openapi-generator.tech): +For mac/linux: ``` -java -cp /path/to/openapi-generator-cli.jar:/path/to/your.jar org.openapitools.codegen.Codegen -g {{name}} -i /path/to/openapi.yaml -o ./test +java -cp /path/to/openapi-generator-cli.jar:/path/to/your.jar org.openapitools.codegen.OpenAPIGenerator generate -g {{name}} -i /path/to/openapi.yaml -o ./test +``` +(Do not forget to replace the values `/path/to/openapi-generator-cli.jar`, `/path/to/your.jar` and `/path/to/openapi.yaml` in the previous command) + +For Windows users, you will need to use `;` instead of `:` in the classpath, e.g. +``` +java -cp /path/to/openapi-generator-cli.jar;/path/to/your.jar org.openapitools.codegen.OpenAPIGenerator generate -g {{name}} -i /path/to/openapi.yaml -o ./test ``` Now your templates are available to the client generator and you can write output values @@ -67,8 +75,8 @@ the object you have available during client generation: # -DdebugOperations prints operations passed to the template engine # -DdebugSupportingFiles prints additional data passed to the template engine -java -DdebugOperations -cp /path/to/openapi-generator-cli.jar:/path/to/your.jar org.openapitools.codegen.Codegen -g {{name}} -i /path/to/swagger.yaml -o ./test +java -DdebugOperations -cp /path/to/openapi-generator-cli.jar:/path/to/your.jar org.openapitools.codegen.OpenAPIGenerator generate -g {{name}} -i /path/to/openapi.yaml -o ./test ``` -Will, for example, output the debug info for operations. You can use this info -in the `api.mustache` file. \ No newline at end of file +Will, for example, output the debug info for operations. +You can use this info in the `api.mustache` file. \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/codegen/generatorClass.mustache b/modules/openapi-generator/src/main/resources/codegen/generatorClass.mustache index acdeeba6f4..cefd218cb5 100644 --- a/modules/openapi-generator/src/main/resources/codegen/generatorClass.mustache +++ b/modules/openapi-generator/src/main/resources/codegen/generatorClass.mustache @@ -19,7 +19,7 @@ public class {{generatorClass}} extends DefaultCodegen implements CodegenConfig * @see org.openapitools.codegen.CodegenType */ public CodegenType getTag() { - return CodegenType.CLIENT; + return CodegenType.{{generatorType}}; } /** diff --git a/modules/openapi-generator/src/main/resources/codegen/pom.mustache b/modules/openapi-generator/src/main/resources/codegen/pom.mustache index 2548456f81..cb3712e87a 100644 --- a/modules/openapi-generator/src/main/resources/codegen/pom.mustache +++ b/modules/openapi-generator/src/main/resources/codegen/pom.mustache @@ -100,8 +100,8 @@ maven-compiler-plugin 3.6.1 - 1.7 - 1.7 + 1.8 + 1.8 diff --git a/modules/openapi-generator/src/main/resources/cpp-qt5-qhttpengine-server/Dockerfile.mustache b/modules/openapi-generator/src/main/resources/cpp-qt5-qhttpengine-server/Dockerfile.mustache index b339548297..2cc6d3eba2 100644 --- a/modules/openapi-generator/src/main/resources/cpp-qt5-qhttpengine-server/Dockerfile.mustache +++ b/modules/openapi-generator/src/main/resources/cpp-qt5-qhttpengine-server/Dockerfile.mustache @@ -1,11 +1,11 @@ FROM alpine:latest AS build -RUN apk add --update \ +RUN apk add --update \ cmake \ alpine-sdk \ - openssl \ - qt5-qtbase-dev \ - qt5-qttools-dev + openssl \ + qt5-qtbase-dev \ + qt5-qttools-dev WORKDIR /usr/server ADD ./src ./src @@ -13,10 +13,10 @@ ADD ./CMakeLists.txt ./ RUN mkdir -p ./build WORKDIR /usr/server/build RUN cmake -DNODEBUG:STRING="ON" .. -RUN make +RUN make FROM alpine:latest AS runtime -RUN apk add --update \ +RUN apk add --update \ libgcc \ libstdc++ \ qt5-qtbase \ diff --git a/modules/openapi-generator/src/main/resources/cpp-qt5-qhttpengine-server/LICENSE.txt.mustache b/modules/openapi-generator/src/main/resources/cpp-qt5-qhttpengine-server/LICENSE.txt.mustache index 04938f840c..be59130f85 100644 --- a/modules/openapi-generator/src/main/resources/cpp-qt5-qhttpengine-server/LICENSE.txt.mustache +++ b/modules/openapi-generator/src/main/resources/cpp-qt5-qhttpengine-server/LICENSE.txt.mustache @@ -1,4 +1,4 @@ -QHttpEngine +QHttpEngine The MIT License (MIT) diff --git a/modules/openapi-generator/src/main/resources/cpp-qt5-qhttpengine-server/README.md.mustache b/modules/openapi-generator/src/main/resources/cpp-qt5-qhttpengine-server/README.md.mustache index 45f2f72467..df0570717b 100644 --- a/modules/openapi-generator/src/main/resources/cpp-qt5-qhttpengine-server/README.md.mustache +++ b/modules/openapi-generator/src/main/resources/cpp-qt5-qhttpengine-server/README.md.mustache @@ -1,8 +1,9 @@ +# C++ Qt5 Server + ## Qt5 HTTP Server based on the Qhttpengine -This server was generated by the [openapi-generator] -(https://openapi-generator.tech) project. -By using the [OpenAPI-Spec](https://github.com/OAI/OpenAPI-Specification) from a remote server, you can easily generate a server stub. -- + +This server was generated by the [openapi-generator](https://openapi-generator.tech) project. +By using the [OpenAPI-Spec](https://github.com/OAI/OpenAPI-Specification) from a remote server, you can easily generate a server stub. To see how to make this your own, look here: @@ -25,30 +26,36 @@ Simple set of classes for developing HTTP server applications in Qt. To learn more about building and using the library, please visit this page: -https://ci.quickmediasolutions.com/job/qhttpengine-documentation/doxygen/ - +[Link](https://ci.quickmediasolutions.com/job/qhttpengine-documentation/doxygen) ### Viewing the code -You can view the code using an editor like Microsoft Visual Studio Code or you can + +You can view the code using an editor like Microsoft Visual Studio Code or you can Use QtCreator and browse for the root CMakeLists.txt and load it as a project ### Build with make + Install the tools [Linux/Debian] -``` + +```shell sudo apt install cmake build-essential libssl-dev qtbase5-dev qtbase5-dev-tools git curl ``` To build, go to the `server` folder -``` -make + +```shell +make ``` To run the server -``` + +```shell ./build/src/cpp-qt5-server & ``` + #### Invoke an API -``` + +```shell curl -X GET http://localhost:8080/v2/store/inventory curl -X POST http://localhost:8080/v2/store/order -H "Content-Type: application/json" -d "{ \"id\": 22, \"petId\": 1541, \"quantity\": 5, \"shipDate\": \"2018-06-16T18:31:43.870Z\", \"status\": \"placed\", \"complete\": \"true\" }" curl -X GET http://localhost:8080/v2/pet/findByStatus @@ -56,38 +63,50 @@ curl -X GET http://localhost:8080/v2/store/inventory ``` ### Run and build with docker + Building with docker multistage If you dont have docker install [here](https://docs.docker.com/install) Add yourself to the docker group -``` +```shell docker build --network=host -t cpp-qt5-server . ``` -Running with docker -``` -docker run --rm -it --name=server-container cpp-qt5-server + +Running with docker + +```shell +docker run --rm -it --name=server-container cpp-qt5-server ``` #### Invoking an API + Mind the IP here -``` + +```shell curl -X GET http://172.17.0.2:8080/v2/store/inventory curl -X POST http://172.17.0.2:8080/v2/store/order -H "Content-Type: application/json" -d "{ \"id\": 22, \"petId\": 1541, \"quantity\": 5, \"shipDate\": \"2018-06-16T18:31:43.870Z\", \"status\": \"placed\", \"complete\": \"true\" }" ``` use this command to get the container IP -``` + +```shell docker inspect server-container | grep "IPAddress" ``` -To exit from the command line -``` + +To exit from the command line + +```shell Ctrl + p + q ``` + To stop container -``` + +```shell docker stop ``` + or to terminate and quit -``` + +```shell Ctrl+C ``` diff --git a/modules/openapi-generator/src/main/resources/cpp-qt5-qhttpengine-server/apirequest.cpp.mustache b/modules/openapi-generator/src/main/resources/cpp-qt5-qhttpengine-server/apirequest.cpp.mustache index 4fa84629c3..c191fbc3b9 100644 --- a/modules/openapi-generator/src/main/resources/cpp-qt5-qhttpengine-server/apirequest.cpp.mustache +++ b/modules/openapi-generator/src/main/resources/cpp-qt5-qhttpengine-server/apirequest.cpp.mustache @@ -16,7 +16,7 @@ namespace {{this}} { auto headers = s->headers(); for(auto itr = headers.begin(); itr != headers.end(); itr++) { requestHeaders.insert(QString(itr.key()), QString(itr.value())); - } + } } {{classname}}Request::~{{classname}}Request(){ @@ -24,7 +24,7 @@ namespace {{this}} { qDebug() << "{{classname}}Request::~{{classname}}Request()"; } -QMap +QMap {{classname}}Request::getRequestHeaders() const { return requestHeaders; } @@ -44,9 +44,9 @@ QHttpEngine::Socket* {{classname}}Request::getRawSocket(){ void {{classname}}Request::{{nickname}}Request({{#hasPathParams}}{{#pathParams}}const QString& {{{paramName}}}str{{#hasMore}}, {{/hasMore}}{{/pathParams}}{{/hasPathParams}}){ qDebug() << "{{{basePathWithoutHost}}}{{{path}}}"; connect(this, &{{classname}}Request::{{nickname}}, handler, &{{classname}}Handler::{{nickname}}); - + {{#queryParams}}{{queryParam}} - {{{dataType}}} {{paramName}}; + {{{dataType}}} {{paramName}}; if(socket->queryString().keys().contains("{{paramName}}")){ fromStringValue(socket->queryString().value{{#isListContainer}}s{{/isListContainer}}("{{paramName}}"), {{paramName}}); } @@ -63,7 +63,7 @@ void {{classname}}Request::{{nickname}}Request({{#hasPathParams}}{{#pathParams}} {{{dataType}}} {{paramName}};{{/formParams}}{{#bodyParams}} {{#bodyParam}} {{#isListContainer}} QJsonDocument doc; - {{{dataType}}} {{paramName}}; + {{{dataType}}} {{paramName}}; if(socket->readJson(doc)){ QJsonArray jsonArray = doc.array(); foreach(QJsonValue obj, jsonArray) { @@ -84,7 +84,7 @@ void {{classname}}Request::{{nickname}}Request({{#hasPathParams}}{{#pathParams}} QJsonDocument doc; socket->readJson(doc); QJsonObject obj = doc.object(); - {{{dataType}}} {{paramName}}; + {{{dataType}}} {{paramName}}; foreach(QString key, obj.keys()) { {{baseType}} val; ::{{cppNamespace}}::fromJsonValue(val, obj[key]); @@ -100,19 +100,21 @@ void {{classname}}Request::{{nickname}}Request({{#hasPathParams}}{{#pathParams}} ::{{cppNamespace}}::fromJsonValue({{paramName}}, obj); {{/isPrimitiveType}} {{/isMapContainer}} - {{/isListContainer}} + {{/isListContainer}} {{/bodyParam}}{{/bodyParams}} - emit {{nickname}}({{#allParams}}{{#isBodyParam}}{{/isBodyParam}} {{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}}); + emit {{nickname}}({{#allParams}}{{#isBodyParam}}{{/isBodyParam}}{{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}}); } -{{/operation}}{{/operations}} +{{/operation}}{{/operations}} {{#operations}}{{#operation}}void {{classname}}Request::{{nickname}}Response({{#returnType}}const {{{returnType}}}& res{{/returnType}}){ - writeResponseHeaders();{{#returnType}}{{^isPrimitiveType}} - QJsonDocument resDoc(::{{cppNamespace}}::toJsonValue(res).to{{^isListContainer}}Object{{/isListContainer}}{{#isListContainer}}Array{{/isListContainer}}());{{/isPrimitiveType}} - socket->writeJson(resDoc);{{#isPrimitiveType}} - socket->write({{#isListContainer}}QString("["+{{/isListContainer}}::{{cppNamespace}}::toStringValue(res){{#isListContainer}}+"]"){{/isListContainer}}.toUtf8());{{/isPrimitiveType}}{{/returnType}}{{^returnType}} + writeResponseHeaders();{{#returnType}}{{#isMapContainer}} + QJsonDocument resDoc(::{{cppNamespace}}::toJsonValue(res).toObject()); + socket->writeJson(resDoc);{{/isMapContainer}}{{^isMapContainer}}{{^returnTypeIsPrimitive}} + QJsonDocument resDoc(::{{cppNamespace}}::toJsonValue(res).to{{^isListContainer}}Object{{/isListContainer}}{{#isListContainer}}Array{{/isListContainer}}()); + socket->writeJson(resDoc);{{/returnTypeIsPrimitive}}{{#returnTypeIsPrimitive}} + socket->write({{#isListContainer}}QString("["+{{/isListContainer}}::{{cppNamespace}}::toStringValue(res){{#isListContainer}}+"]"){{/isListContainer}}.toUtf8());{{/returnTypeIsPrimitive}}{{/isMapContainer}}{{/returnType}}{{^returnType}} socket->setStatusCode(QHttpEngine::Socket::OK);{{/returnType}} if(socket->isOpen()){ socket->close(); @@ -123,10 +125,12 @@ void {{classname}}Request::{{nickname}}Request({{#hasPathParams}}{{#pathParams}} {{#operations}}{{#operation}}void {{classname}}Request::{{nickname}}Error({{#returnType}}const {{{returnType}}}& res, {{/returnType}}QNetworkReply::NetworkError error_type, QString& error_str){ Q_UNUSED(error_type); // TODO: Remap error_type to QHttpEngine::Socket errors writeResponseHeaders();{{#returnType}} - Q_UNUSED(error_str); // response will be used instead of error string{{^isPrimitiveType}} - QJsonDocument resDoc(::{{cppNamespace}}::toJsonValue(res).to{{^isListContainer}}Object{{/isListContainer}}{{#isListContainer}}Array{{/isListContainer}}());{{/isPrimitiveType}} - socket->writeJson(resDoc);{{#isPrimitiveType}} - socket->write({{#isListContainer}}QString("["+{{/isListContainer}}::{{cppNamespace}}::toStringValue(res){{#isListContainer}}+"]"){{/isListContainer}}.toUtf8());{{/isPrimitiveType}}{{/returnType}}{{^returnType}} + Q_UNUSED(error_str); // response will be used instead of error string{{#isMapContainer}} + QJsonDocument resDoc(::{{cppNamespace}}::toJsonValue(res).toObject()); + socket->writeJson(resDoc);{{/isMapContainer}}{{^isMapContainer}}{{^returnTypeIsPrimitive}} + QJsonDocument resDoc(::{{cppNamespace}}::toJsonValue(res).to{{^isListContainer}}Object{{/isListContainer}}{{#isListContainer}}Array{{/isListContainer}}()); + socket->writeJson(resDoc);{{/returnTypeIsPrimitive}}{{#returnTypeIsPrimitive}} + socket->write({{#isListContainer}}QString("["+{{/isListContainer}}::{{cppNamespace}}::toStringValue(res){{#isListContainer}}+"]"){{/isListContainer}}.toUtf8());{{/returnTypeIsPrimitive}}{{/isMapContainer}}{{/returnType}}{{^returnType}} socket->setStatusCode(QHttpEngine::Socket::NotFound); socket->write(error_str.toUtf8());{{/returnType}} if(socket->isOpen()){ @@ -139,7 +143,7 @@ void {{classname}}Request::sendCustomResponse(QByteArray & res, QNetworkReply::N Q_UNUSED(res); // TODO Q_UNUSED(error_type); // TODO } - + void {{classname}}Request::sendCustomResponse(QIODevice *res, QNetworkReply::NetworkError error_type){ Q_UNUSED(res); // TODO Q_UNUSED(error_type); // TODO diff --git a/modules/openapi-generator/src/main/resources/cpp-qt5-qhttpengine-server/apirequest.h.mustache b/modules/openapi-generator/src/main/resources/cpp-qt5-qhttpengine-server/apirequest.h.mustache index ed7339278a..c736195d74 100644 --- a/modules/openapi-generator/src/main/resources/cpp-qt5-qhttpengine-server/apirequest.h.mustache +++ b/modules/openapi-generator/src/main/resources/cpp-qt5-qhttpengine-server/apirequest.h.mustache @@ -20,7 +20,7 @@ namespace {{this}} { class {{classname}}Request : public QObject { Q_OBJECT - + public: {{classname}}Request(QHttpEngine::Socket *s, {{classname}}Handler* handler); virtual ~{{classname}}Request(); @@ -60,7 +60,7 @@ private: resHeaders.insert(itr.key().toUtf8(), itr.value().toUtf8()); } socket->setHeaders(resHeaders); - socket->writeHeaders(); + socket->writeHeaders(); } }; diff --git a/modules/openapi-generator/src/main/resources/cpp-qt5-qhttpengine-server/apirouter.cpp.mustache b/modules/openapi-generator/src/main/resources/cpp-qt5-qhttpengine-server/apirouter.cpp.mustache index be6c0bb072..e3ade84f9a 100644 --- a/modules/openapi-generator/src/main/resources/cpp-qt5-qhttpengine-server/apirouter.cpp.mustache +++ b/modules/openapi-generator/src/main/resources/cpp-qt5-qhttpengine-server/apirouter.cpp.mustache @@ -13,80 +13,73 @@ namespace {{this}} { {{/cppNamespaceDeclarations}} -inline QHttpEngine::Socket::Method toQHttpEngineMethod(QString method){ - - if( method == QString("OPTIONS")) - return QHttpEngine::Socket::Method::OPTIONS; - if( method == QString("GET")) - return QHttpEngine::Socket::Method::GET; - if( method == QString("HEAD")) - return QHttpEngine::Socket::Method::HEAD; - if( method == QString("POST")) - return QHttpEngine::Socket::Method::POST; - if( method == QString("PUT")) - return QHttpEngine::Socket::Method::PUT; - if( method == QString("DELETE")) - return QHttpEngine::Socket::Method::DELETE; - if( method == QString("TRACE")) - return QHttpEngine::Socket::Method::TRACE; - if( method == QString("CONNECT")) - return QHttpEngine::Socket::Method::CONNECT; - - return static_cast(-1); +{{prefix}}ApiRouter::{{prefix}}ApiRouter() { + createApiHandlers(); } -ApiRouter::ApiRouter() { - {{#apiInfo}}{{#apis}}{{classname}}ApiHandler = new {{classname}}Handler(); - {{/apis}}{{/apiInfo}} +{{prefix}}ApiRouter::~{{prefix}}ApiRouter(){ + qDebug() << "~ApiRouter()";{{#apiInfo}}{{#apis}} + delete {{classname}}ApiHandler;{{/apis}}{{/apiInfo}} } -ApiRouter::~ApiRouter(){ - qDebug() << "~ApiRouter()"; - {{#apiInfo}}{{#apis}}delete {{classname}}ApiHandler; - {{/apis}}{{/apiInfo}} +void {{prefix}}ApiRouter::createApiHandlers() { {{#apiInfo}}{{#apis}} + {{classname}}ApiHandler = new {{classname}}Handler();{{/apis}}{{/apiInfo}} } -void ApiRouter::setUpRoutes() { - {{#apiInfo}}{{#apis}}{{#operations}}{{#operation}}{{^pathParams}} - Routes.insert("{{{basePathWithoutHost}}}{{{path}}}",[this](QHttpEngine::Socket *socket) { - if(toQHttpEngineMethod("{{httpMethod}}") == socket->method()){ +void {{prefix}}ApiRouter::setUpRoutes() { + {{#apiInfo}}{{#apis}}{{#operations}}{{#operation}}{{^hasPathParams}} + Routes.insert(QString("%1 %2").arg("{{httpMethod}}").arg("{{{basePathWithoutHost}}}{{{path}}}").toLower(), [this](QHttpEngine::Socket *socket) { auto reqObj = new {{classname}}Request(socket, {{classname}}ApiHandler); reqObj->{{nickname}}Request(); - } - });{{/pathParams}}{{/operation}}{{/operations}}{{/apis}}{{/apiInfo}} + });{{/hasPathParams}}{{/operation}}{{/operations}}{{/apis}}{{/apiInfo}} } -void ApiRouter::processRequest(QHttpEngine::Socket *socket){ - if (Routes.contains(socket->path())) { - for(auto endpoints : Routes.values(socket->path())) { - endpoints.operator()(socket); - } - } else - { {{#apiInfo}}{{#apis}}{{#operations}}{{#operation}}{{#pathParams}} - { - QString completePath("{{{basePathWithoutHost}}}{{{path}}}"); - QString {{paramName}}PathParam("{"); - {{paramName}}PathParam.append("{{baseName}}").append("}"); - completePath.replace("/", "\\/"); // replace '/' with '\/' for regex - completePath.replace({{paramName}}PathParam, "([^\\/]*?)"); // match anything but '/'' - completePath.append("$"); // End of string - QRegularExpression re(completePath, QRegularExpression::CaseInsensitiveOption); - QRegularExpressionMatch match = re.match(socket->path()); - if ((toQHttpEngineMethod("{{httpMethod}}") == socket->method()) && match.hasMatch() ) { - QString pathparam = match.captured(1); - auto reqObj = new {{classname}}Request(socket, {{classname}}ApiHandler); - reqObj->{{nickname}}Request({{#hasPathParams}}{{#pathParams}}pathparam{{/pathParams}}{{/hasPathParams}}); - return; - } - }{{/pathParams}}{{/operation}}{{/operations}}{{/apis}}{{/apiInfo}} +void {{prefix}}ApiRouter::processRequest(QHttpEngine::Socket *socket){ + if( handleRequest(socket) ){ + return; + } + if( handleRequestAndExtractPathParam(socket) ){ + return; } socket->setStatusCode(QHttpEngine::Socket::NotFound); if(socket->isOpen()){ socket->writeHeaders(); socket->close(); } - return; } + +bool {{prefix}}ApiRouter::handleRequest(QHttpEngine::Socket *socket){ + auto reqPath = QString("%1 %2").arg(fromQHttpEngineMethod(socket->method())).arg(socket->path()).toLower(); + if ( Routes.contains(reqPath) ) { + Routes.value(reqPath).operator()(socket); + return true; + } + return false; +} + +bool {{prefix}}ApiRouter::handleRequestAndExtractPathParam(QHttpEngine::Socket *socket){ + auto reqPath = QString("%1 %2").arg(fromQHttpEngineMethod(socket->method())).arg(socket->path()).toLower();{{#apiInfo}}{{#apis}}{{#operations}}{{#operation}}{{#hasPathParams}} + { + auto completePath = QString("%1 %2").arg("{{httpMethod}}").arg("{{{basePathWithoutHost}}}{{{path}}}").toLower(); + if ( reqPath.startsWith(completePath.leftRef( completePath.indexOf(QString("/{")))) ) { + QRegularExpression parExpr( R"(\{([^\/\\s]+)\})" ); + completePath.replace( parExpr, R"((?<\1>[^\/\s]+))" ); + completePath.append("[\\/]?$"); + QRegularExpression pathExpr( completePath ); + QRegularExpressionMatch match = pathExpr.match( reqPath ); + if ( match.hasMatch() ){ + {{#pathParams}} + QString {{baseName}} = match.captured(QString("{{baseName}}").toLower()); + {{/pathParams}} + auto reqObj = new {{classname}}Request(socket, {{classname}}ApiHandler); + reqObj->{{nickname}}Request({{#pathParams}}{{baseName}}{{#hasMore}}, {{/hasMore}}{{/pathParams}}); + return true; + } + } + }{{/hasPathParams}}{{/operation}}{{/operations}}{{/apis}}{{/apiInfo}} + return false; +} + {{#cppNamespaceDeclarations}} } {{/cppNamespaceDeclarations}} diff --git a/modules/openapi-generator/src/main/resources/cpp-qt5-qhttpengine-server/apirouter.h.mustache b/modules/openapi-generator/src/main/resources/cpp-qt5-qhttpengine-server/apirouter.h.mustache index a55da19cc4..5634db060b 100644 --- a/modules/openapi-generator/src/main/resources/cpp-qt5-qhttpengine-server/apirouter.h.mustache +++ b/modules/openapi-generator/src/main/resources/cpp-qt5-qhttpengine-server/apirouter.h.mustache @@ -19,7 +19,7 @@ namespace {{this}} { {{/cppNamespaceDeclarations}} -class RequestHandler : public QHttpEngine::QObjectHandler +class {{prefix}}ApiRequestHandler : public QHttpEngine::QObjectHandler { Q_OBJECT signals: @@ -32,19 +32,51 @@ protected: } }; -class ApiRouter : public QObject +class {{prefix}}ApiRouter : public QObject { Q_OBJECT public: - ApiRouter(); - virtual ~ApiRouter(); + {{prefix}}ApiRouter(); + virtual ~{{prefix}}ApiRouter(); void setUpRoutes(); void processRequest(QHttpEngine::Socket *socket); private: - QMultiMap> Routes; + QMap> Routes; + QMultiMap> RoutesWithPathParam; + + bool handleRequest(QHttpEngine::Socket *socket); + bool handleRequestAndExtractPathParam(QHttpEngine::Socket *socket); + {{#apiInfo}}{{#apis}} - {{classname}}Handler *{{classname}}ApiHandler;{{/apis}}{{/apiInfo}} + {{classname}}Handler *{{classname}}ApiHandler;{{/apis}}{{/apiInfo}} +protected: + // override this method to provide custom class derived from ApiHandler classes + virtual void createApiHandlers(); + +private : + inline QString fromQHttpEngineMethod(QHttpEngine::Socket::Method method){ + switch( method ){ + case QHttpEngine::Socket::Method::OPTIONS: + return QStringLiteral("OPTIONS"); + case QHttpEngine::Socket::Method::GET: + return QStringLiteral("GET"); + case QHttpEngine::Socket::Method::HEAD: + return QStringLiteral("HEAD"); + case QHttpEngine::Socket::Method::POST: + return QStringLiteral("POST"); + case QHttpEngine::Socket::Method::PUT: + return QStringLiteral("PUT"); + case QHttpEngine::Socket::Method::DELETE: + return QStringLiteral("DELETE"); + case QHttpEngine::Socket::Method::TRACE: + return QStringLiteral("TRACE"); + case QHttpEngine::Socket::Method::CONNECT: + return QStringLiteral("CONNECT"); + } + return QStringLiteral(""); + } + }; 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 167676df65..78a0094eb0 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 @@ -125,7 +125,7 @@ namespace {{this}} { for(auto itemkey : varmap.keys() ){ T itemVal; fromJsonValue(itemVal, QJsonValue::fromVariant(varmap.value(itemkey))); - val.insert(itemkey, val); + val.insert(itemkey, itemVal); } } return; diff --git a/modules/openapi-generator/src/main/resources/cpp-qt5-qhttpengine-server/main.cpp.mustache b/modules/openapi-generator/src/main/resources/cpp-qt5-qhttpengine-server/main.cpp.mustache index c030bcb47f..b477093516 100644 --- a/modules/openapi-generator/src/main/resources/cpp-qt5-qhttpengine-server/main.cpp.mustache +++ b/modules/openapi-generator/src/main/resources/cpp-qt5-qhttpengine-server/main.cpp.mustache @@ -8,43 +8,43 @@ #include #include #include -#ifdef __linux__ +#ifdef __linux__ #include #include -#endif +#endif #include #include "{{prefix}}ApiRouter.h" -#ifdef __linux__ +#ifdef __linux__ void catchUnixSignals(QList quitSignals) { auto handler = [](int sig) -> void { // blocking and not aysnc-signal-safe func are valid qDebug() << "\nquit the application by signal " << sig; QCoreApplication::quit(); }; - - sigset_t blocking_mask; - sigemptyset(&blocking_mask); - for (auto sig : quitSignals) - sigaddset(&blocking_mask, sig); - - struct sigaction sa; - sa.sa_handler = handler; - sa.sa_mask = blocking_mask; - sa.sa_flags = 0; - - for (auto sig : quitSignals) + + sigset_t blocking_mask; + sigemptyset(&blocking_mask); + for (auto sig : quitSignals) + sigaddset(&blocking_mask, sig); + + struct sigaction sa; + sa.sa_handler = handler; + sa.sa_mask = blocking_mask; + sa.sa_flags = 0; + + for (auto sig : quitSignals) sigaction(sig, &sa, nullptr); } -#endif +#endif int main(int argc, char * argv[]) { QCoreApplication a(argc, argv); -#ifdef __linux__ +#ifdef __linux__ QList sigs({SIGQUIT, SIGINT, SIGTERM, SIGHUP}); catchUnixSignals(sigs); -#endif +#endif // Build the command-line options QCommandLineParser parser; QCommandLineOption addressOption( @@ -69,11 +69,11 @@ int main(int argc, char * argv[]) // Obtain the values QHostAddress address = QHostAddress(parser.value(addressOption)); quint16 port = static_cast(parser.value(portOption).toInt()); - - QSharedPointer<{{cppNamespace}}::RequestHandler> handler(new {{cppNamespace}}::RequestHandler()); - {{cppNamespace}}::ApiRouter router; + + QSharedPointer<{{cppNamespace}}::{{prefix}}ApiRequestHandler> handler(new {{cppNamespace}}::{{prefix}}ApiRequestHandler()); + {{cppNamespace}}::{{prefix}}ApiRouter router; router.setUpRoutes(); - QObject::connect(handler.data(), &{{cppNamespace}}::RequestHandler::requestReceived, [&](QHttpEngine::Socket *socket) { + QObject::connect(handler.data(), &{{cppNamespace}}::{{prefix}}ApiRequestHandler::requestReceived, [&](QHttpEngine::Socket *socket) { router.processRequest(socket); }); @@ -84,6 +84,6 @@ int main(int argc, char * argv[]) qCritical("Unable to listen on the specified port."); return 1; } - + return a.exec(); } 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 b83b21a012..1e298f57b0 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 @@ -22,7 +22,7 @@ namespace {{this}} { } {{classname}}::~{{classname}}() { - + } void @@ -77,7 +77,7 @@ QJsonObject {{classname}}::asJsonObject() const { QJsonObject obj; {{#vars}} - {{^isContainer}}{{#complexType}}{{^isString}}{{^isDateTime}}{{^isByteArray}}{{^isDate}}if({{name}}.isSet()){{/isDate}}{{/isByteArray}}{{/isDateTime}}{{/isString}}{{/complexType}}{{^complexType}}if(m_{{name}}_isSet){{/complexType}}{{#isString}}if(m_{{name}}_isSet){{/isString}}{{#isDateTime}}if(m_{{name}}_isSet){{/isDateTime}}{{#isByteArray}}if(m_{{name}}_isSet){{/isByteArray}}{{#isDate}}if(m_{{name}}_isSet){{/isDate}}{ + {{^isContainer}}{{#complexType}}if({{name}}.isSet()){{/complexType}}{{^complexType}}if(m_{{name}}_isSet){{/complexType}}{ obj.insert(QString("{{baseName}}"), ::{{cppNamespace}}::toJsonValue({{name}})); }{{/isContainer}}{{#isContainer}} if({{name}}.size() > 0){ @@ -105,7 +105,7 @@ bool {{classname}}::isSet() const { bool isObjectUpdated = false; do{ {{#vars}} - {{#isContainer}}if({{name}}.size() > 0){{/isContainer}}{{^isContainer}}{{#complexType}}{{^isString}}{{^isDateTime}}{{^isByteArray}}{{^isDate}}if({{name}}.isSet()){{/isDate}}{{/isByteArray}}{{/isDateTime}}{{/isString}}{{/complexType}}{{^complexType}}if(m_{{name}}_isSet){{/complexType}}{{#isString}}if(m_{{name}}_isSet){{/isString}}{{#isDateTime}}if(m_{{name}}_isSet){{/isDateTime}}{{#isByteArray}}if(m_{{name}}_isSet){{/isByteArray}}{{#isDate}}if(m_{{name}}_isSet){{/isDate}}{{/isContainer}}{ isObjectUpdated = true; break;} + {{#isContainer}}if({{name}}.size() > 0){{/isContainer}}{{^isContainer}}{{#complexType}}if({{name}}.isSet()){{/complexType}}{{^complexType}}if(m_{{name}}_isSet){{/complexType}}{{/isContainer}}{ isObjectUpdated = true; break;} {{/vars}}}while(false); return isObjectUpdated; } diff --git a/modules/openapi-generator/src/main/resources/cpp-qt5-qhttpengine-server/object.mustache b/modules/openapi-generator/src/main/resources/cpp-qt5-qhttpengine-server/object.mustache index a3ed43c95f..26621c747e 100644 --- a/modules/openapi-generator/src/main/resources/cpp-qt5-qhttpengine-server/object.mustache +++ b/modules/openapi-generator/src/main/resources/cpp-qt5-qhttpengine-server/object.mustache @@ -12,9 +12,9 @@ namespace {{this}} { class {{prefix}}Object { public: virtual ~{{prefix}}Object(){ - + } - + virtual QJsonObject asJsonObject() const { return jObj; } diff --git a/modules/openapi-generator/src/main/resources/cpp-qt5-qhttpengine-server/src-CMakeLists.txt.mustache b/modules/openapi-generator/src/main/resources/cpp-qt5-qhttpengine-server/src-CMakeLists.txt.mustache index 9faf5db60e..0311ec2020 100644 --- a/modules/openapi-generator/src/main/resources/cpp-qt5-qhttpengine-server/src-CMakeLists.txt.mustache +++ b/modules/openapi-generator/src/main/resources/cpp-qt5-qhttpengine-server/src-CMakeLists.txt.mustache @@ -12,7 +12,7 @@ set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -fPIC -std=c++14 -Wall -Wno-unused-varia if(${NODEBUG} STREQUAL "OFF") set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -pg -g3") set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -pg -g3") -else (${NODEBUG} STREQUAL "OFF") +else (${NODEBUG} STREQUAL "OFF") set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -s -O3") set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -s -O3") endif(${NODEBUG} STREQUAL "OFF") diff --git a/modules/openapi-generator/src/main/resources/elm/aliasDecoder.mustache b/modules/openapi-generator/src/main/resources/elm/aliasDecoder.mustache index 8a37eef108..48154f0d4f 100644 --- a/modules/openapi-generator/src/main/resources/elm/aliasDecoder.mustache +++ b/modules/openapi-generator/src/main/resources/elm/aliasDecoder.mustache @@ -4,4 +4,4 @@ {{#allVars}} {{^discriminatorValue}} |> {{>fieldDecoder}} {{/discriminatorValue}} -{{/allVars}} +{{/allVars}} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/elm/aliasEncoder.mustache b/modules/openapi-generator/src/main/resources/elm/aliasEncoder.mustache index 662453c3ce..7889f1f035 100644 --- a/modules/openapi-generator/src/main/resources/elm/aliasEncoder.mustache +++ b/modules/openapi-generator/src/main/resources/elm/aliasEncoder.mustache @@ -4,4 +4,4 @@ {{#allVars}} {{#-first}}[{{/-first}}{{^-first}},{{/-first}} {{>fieldEncoder}} {{/allVars}} - ] + ] \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/kotlin-spring/api.mustache b/modules/openapi-generator/src/main/resources/kotlin-spring/api.mustache new file mode 100644 index 0000000000..0ab788eea1 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/kotlin-spring/api.mustache @@ -0,0 +1,70 @@ +package {{package}} + +{{#imports}}import {{import}} +{{/imports}} +{{#swaggerAnnotations}} +import io.swagger.annotations.* +{{/swaggerAnnotations}} +import org.springframework.http.HttpStatus +import org.springframework.http.MediaType +import org.springframework.http.ResponseEntity +import org.springframework.stereotype.Controller +import org.springframework.web.bind.annotation.RequestBody +import org.springframework.web.bind.annotation.RequestPart +import org.springframework.web.bind.annotation.RequestParam +import org.springframework.web.bind.annotation.PathVariable +import org.springframework.web.bind.annotation.RequestHeader +import org.springframework.web.bind.annotation.RequestMethod +import org.springframework.web.bind.annotation.RequestMapping +{{#useBeanValidation}} +import org.springframework.validation.annotation.Validated +{{/useBeanValidation}} +import org.springframework.web.context.request.NativeWebRequest +import org.springframework.web.multipart.MultipartFile +import org.springframework.beans.factory.annotation.Autowired + +{{#useBeanValidation}} +import javax.validation.Valid +import javax.validation.constraints.* +{{/useBeanValidation}} + +import kotlin.collections.List +import kotlin.collections.Map + +@Controller +{{#useBeanValidation}} +@Validated +{{/useBeanValidation}} +{{#swaggerAnnotations}} +@Api(value = "{{{baseName}}}", description = "The {{{baseName}}} API") +{{/swaggerAnnotations}} +{{=<% %>=}} +@RequestMapping("\${openapi.<%title%>.base-path:<%contextPath%>}") +<%={{ }}=%> +{{#operations}} +class {{classname}}Controller({{#serviceInterface}}@Autowired(required = true) val service: {{classname}}Service{{/serviceInterface}}) { +{{#operation}} + + {{#swaggerAnnotations}} + @ApiOperation( + value = "{{{summary}}}", + nickname = "{{{operationId}}}", + notes = "{{{notes}}}"{{#returnBaseType}}, + response = {{{returnBaseType}}}::class{{/returnBaseType}}{{#returnContainer}}, + responseContainer = "{{{returnContainer}}}"{{/returnContainer}}{{#hasAuthMethods}}, + authorizations = [{{#authMethods}}Authorization(value = "{{name}}"{{#isOAuth}}, scopes = [{{#scopes}}AuthorizationScope(scope = "{{scope}}", description = "{{description}}"){{#hasMore}}, {{/hasMore}}{{/scopes}}]{{/isOAuth}}){{#hasMore}}, {{/hasMore}}{{/authMethods}}]{{/hasAuthMethods}}) + @ApiResponses( + value = [{{#responses}}ApiResponse(code = {{{code}}}, message = "{{{message}}}"{{#baseType}}, response = {{{baseType}}}::class{{/baseType}}{{#containerType}}, responseContainer = "{{{containerType}}}"{{/containerType}}){{#hasMore}},{{/hasMore}}{{/responses}}]){{/swaggerAnnotations}} + @RequestMapping( + value = ["{{#lambda.escapeDoubleQuote}}{{path}}{{/lambda.escapeDoubleQuote}}"],{{#singleContentTypes}}{{#hasProduces}} + produces = "{{{vendorExtensions.x-accepts}}}", {{/hasProduces}}{{#hasConsumes}} + consumes = "{{{vendorExtensions.x-contentType}}}",{{/hasConsumes}}{{/singleContentTypes}}{{^singleContentTypes}}{{#hasProduces}} + produces = [{{#produces}}"{{{mediaType}}}"{{#hasMore}}, {{/hasMore}}{{/produces}}], {{/hasProduces}}{{#hasConsumes}} + consumes = [{{#consumes}}"{{{mediaType}}}"{{#hasMore}}, {{/hasMore}}{{/consumes}}],{{/hasConsumes}}{{/singleContentTypes}} + method = [RequestMethod.{{httpMethod}}]) + fun {{operationId}}({{#allParams}}{{>queryParams}}{{>pathParams}}{{>headerParams}}{{>bodyParams}}{{>formParams}}{{#hasMore}},{{/hasMore}}{{/allParams}}): ResponseEntity<{{>returnTypes}}> { + return {{>returnValue}} + } +{{/operation}} +} +{{/operations}} diff --git a/modules/openapi-generator/src/main/resources/kotlin-spring/beanValidationModel.mustache b/modules/openapi-generator/src/main/resources/kotlin-spring/beanValidationModel.mustache new file mode 100644 index 0000000000..0564f1e363 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/kotlin-spring/beanValidationModel.mustache @@ -0,0 +1,20 @@ +{{#pattern}}@get:Pattern(regexp="{{{pattern}}}") {{/pattern}}{{! +minLength && maxLength set +}}{{#minLength}}{{#maxLength}}@get:Size(min={{minLength}},max={{maxLength}}) {{/maxLength}}{{/minLength}}{{! +minLength set, maxLength not +}}{{#minLength}}{{^maxLength}}@get:Size(min={{minLength}}) {{/maxLength}}{{/minLength}}{{! +minLength not set, maxLength set +}}{{^minLength}}{{#maxLength}}@get:Size(max={{maxLength}}) {{/maxLength}}{{/minLength}}{{! +@Size: minItems && maxItems set +}}{{#minItems}}{{#maxItems}}@get:Size(min={{minItems}},max={{maxItems}}) {{/maxItems}}{{/minItems}}{{! +@Size: minItems set, maxItems not +}}{{#minItems}}{{^maxItems}}@get:Size(min={{minItems}}) {{/maxItems}}{{/minItems}}{{! +@Size: minItems not set && maxItems set +}}{{^minItems}}{{#maxItems}}@get:Size(max={{maxItems}}) {{/maxItems}}{{/minItems}}{{! +check for integer or long / all others=decimal type with @Decimal* +isInteger set +}}{{#isInteger}}{{#minimum}}@get:Min({{minimum}}){{/minimum}}{{#maximum}} @get:Max({{maximum}}) {{/maximum}}{{/isInteger}}{{! +isLong set +}}{{#isLong}}{{#minimum}}@get:Min({{minimum}}L){{/minimum}}{{#maximum}} @get:Max({{maximum}}L) {{/maximum}}{{/isLong}}{{! +Not Integer, not Long => we have a decimal value! +}}{{^isInteger}}{{^isLong}}{{#minimum}}@get:DecimalMin("{{minimum}}"){{/minimum}}{{#maximum}} @get:DecimalMax("{{maximum}}") {{/maximum}}{{/isLong}}{{/isInteger}} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/kotlin-spring/beanValidationPath.mustache b/modules/openapi-generator/src/main/resources/kotlin-spring/beanValidationPath.mustache new file mode 100644 index 0000000000..4b7b561ce7 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/kotlin-spring/beanValidationPath.mustache @@ -0,0 +1,20 @@ +{{#pattern}}@Pattern(regexp="{{{pattern}}}") {{/pattern}}{{! +minLength && maxLength set +}}{{#minLength}}{{#maxLength}}@Size(min={{minLength}},max={{maxLength}}) {{/maxLength}}{{/minLength}}{{! +minLength set, maxLength not +}}{{#minLength}}{{^maxLength}}@Size(min={{minLength}}) {{/maxLength}}{{/minLength}}{{! +minLength not set, maxLength set +}}{{^minLength}}{{#maxLength}}@Size(max={{maxLength}}) {{/maxLength}}{{/minLength}}{{! +@Size: minItems && maxItems set +}}{{#minItems}}{{#maxItems}}@Size(min={{minItems}},max={{maxItems}}) {{/maxItems}}{{/minItems}}{{! +@Size: minItems set, maxItems not +}}{{#minItems}}{{^maxItems}}@Size(min={{minItems}}) {{/maxItems}}{{/minItems}}{{! +@Size: minItems not set && maxItems set +}}{{^minItems}}{{#maxItems}}@Size(max={{maxItems}}) {{/maxItems}}{{/minItems}}{{! +check for integer or long / all others=decimal type with @Decimal* +isInteger set +}}{{#isInteger}}{{#minimum}}@Min({{minimum}}){{/minimum}}{{#maximum}} @Max({{maximum}}) {{/maximum}}{{/isInteger}}{{! +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("{{minimum}}"){{/minimum}}{{#maximum}} @DecimalMax("{{maximum}}") {{/maximum}}{{/isLong}}{{/isInteger}} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/kotlin-spring/beanValidationPathParams.mustache b/modules/openapi-generator/src/main/resources/kotlin-spring/beanValidationPathParams.mustache new file mode 100644 index 0000000000..3c57e76be1 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/kotlin-spring/beanValidationPathParams.mustache @@ -0,0 +1 @@ +{{! PathParam is always required, no @NotNull necessary }}{{>beanValidationPath}} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/kotlin-spring/beanValidationQueryParams.mustache b/modules/openapi-generator/src/main/resources/kotlin-spring/beanValidationQueryParams.mustache new file mode 100644 index 0000000000..cc53bc9623 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/kotlin-spring/beanValidationQueryParams.mustache @@ -0,0 +1 @@ +{{#required}}@NotNull {{/required}}{{>beanValidationPath}} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/kotlin-spring/bodyParams.mustache b/modules/openapi-generator/src/main/resources/kotlin-spring/bodyParams.mustache new file mode 100644 index 0000000000..041fcb4cca --- /dev/null +++ b/modules/openapi-generator/src/main/resources/kotlin-spring/bodyParams.mustache @@ -0,0 +1 @@ +{{#isBodyParam}}{{#swaggerAnnotations}}@ApiParam(value = "{{{description}}}" {{#required}},required=true{{/required}} {{^isContainer}}{{#allowableValues}}, allowableValues="{{{allowableValues}}}"{{/allowableValues}}{{/isContainer}}{{#defaultValue}}, defaultValue="{{{defaultValue}}}"{{/defaultValue}}){{/swaggerAnnotations}} {{#useBeanValidation}}@Valid{{/useBeanValidation}} @RequestBody {{paramName}}: {{^reactive}}{{{dataType}}}{{/reactive}}{{#reactive}}{{^isListContainer}}Mono{{/isListContainer}}{{#isListContainer}}Flux{{/isListContainer}}<{{{baseType}}}>{{/reactive}}{{/isBodyParam}} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/kotlin-spring/dataClass.mustache b/modules/openapi-generator/src/main/resources/kotlin-spring/dataClass.mustache new file mode 100644 index 0000000000..aead297880 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/kotlin-spring/dataClass.mustache @@ -0,0 +1,25 @@ +/** + * {{{description}}} +{{#vars}} + * @param {{name}} {{{description}}} +{{/vars}} + */ +data class {{classname}} ( +{{#requiredVars}} +{{>dataClassReqVar}}{{^-last}}, +{{/-last}}{{/requiredVars}}{{#hasRequired}}{{#hasOptional}}, +{{/hasOptional}}{{/hasRequired}}{{#optionalVars}}{{>dataClassOptVar}}{{^-last}}, +{{/-last}}{{/optionalVars}} +) { +{{#hasEnums}}{{#vars}}{{#isEnum}} + /** + * {{{description}}} + * Values: {{#allowableValues}}{{#enumVars}}{{&name}}{{^-last}},{{/-last}}{{/enumVars}}{{/allowableValues}} + */ + enum class {{nameInCamelCase}}(val value: {{{dataType}}}) { + {{#allowableValues}}{{#enumVars}} + @JsonProperty({{{value}}}) {{{name}}}({{{value}}}){{^-last}},{{/-last}}{{#-last}};{{/-last}} + {{/enumVars}}{{/allowableValues}} + } +{{/isEnum}}{{/vars}}{{/hasEnums}} +} diff --git a/modules/openapi-generator/src/main/resources/kotlin-spring/dataClassOptVar.mustache b/modules/openapi-generator/src/main/resources/kotlin-spring/dataClassOptVar.mustache new file mode 100644 index 0000000000..52b6ae1157 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/kotlin-spring/dataClassOptVar.mustache @@ -0,0 +1,4 @@ +{{#useBeanValidation}}{{#required}} + @get:NotNull {{/required}}{{>beanValidationModel}}{{/useBeanValidation}}{{#swaggerAnnotations}} + @ApiModelProperty({{#example}}example = "{{{example}}}", {{/example}}{{#required}}required = {{required}}, {{/required}}{{#isReadOnly}}readOnly = {{{isReadOnly}}}, {{/isReadOnly}}value = "{{{description}}}"){{/swaggerAnnotations}} + @JsonProperty("{{{baseName}}}") val {{{name}}}: {{#isEnum}}{{classname}}.{{nameInCamelCase}}{{/isEnum}}{{^isEnum}}{{{dataType}}}{{/isEnum}}? = {{#defaultvalue}}{{defaultvalue}}{{/defaultvalue}}{{^defaultvalue}}null{{/defaultvalue}} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/kotlin-spring/dataClassReqVar.mustache b/modules/openapi-generator/src/main/resources/kotlin-spring/dataClassReqVar.mustache new file mode 100644 index 0000000000..e09ea971be --- /dev/null +++ b/modules/openapi-generator/src/main/resources/kotlin-spring/dataClassReqVar.mustache @@ -0,0 +1,4 @@ +{{#useBeanValidation}}{{#required}} + @get:NotNull {{/required}}{{>beanValidationModel}}{{/useBeanValidation}}{{#swaggerAnnotations}} + @ApiModelProperty({{#example}}example = "{{{example}}}", {{/example}}{{#required}}required = {{required}}, {{/required}}{{#isReadOnly}}readOnly = {{{isReadOnly}}}, {{/isReadOnly}}value = "{{{description}}}"){{/swaggerAnnotations}} + @JsonProperty("{{{baseName}}}") val {{{name}}}: {{#isEnum}}{{classname}}.{{nameInCamelCase}}{{/isEnum}}{{^isEnum}}{{{dataType}}}{{/isEnum}} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/kotlin-spring/enumClass.mustache b/modules/openapi-generator/src/main/resources/kotlin-spring/enumClass.mustache new file mode 100644 index 0000000000..2f24a1de76 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/kotlin-spring/enumClass.mustache @@ -0,0 +1,9 @@ +/** +* {{{description}}} +* Values: {{#allowableValues}}{{#enumVars}}{{&name}}{{^-last}},{{/-last}}{{/enumVars}}{{/allowableValues}} +*/ +enum class {{classname}}(val value: {{dataType}}) { +{{#allowableValues}}{{#enumVars}} + {{&name}}({{{value}}}){{^-last}},{{/-last}}{{#-last}};{{/-last}} +{{/enumVars}}{{/allowableValues}} +} diff --git a/modules/openapi-generator/src/main/resources/kotlin-spring/exceptions.mustache b/modules/openapi-generator/src/main/resources/kotlin-spring/exceptions.mustache new file mode 100644 index 0000000000..d85b8396fa --- /dev/null +++ b/modules/openapi-generator/src/main/resources/kotlin-spring/exceptions.mustache @@ -0,0 +1,29 @@ +package {{apiPackage}} + +import org.springframework.http.HttpStatus +import org.springframework.web.bind.annotation.ControllerAdvice +import org.springframework.web.bind.annotation.ExceptionHandler +import javax.servlet.http.HttpServletResponse +import javax.validation.ConstraintViolationException + +// TODO Extend ApiException for custom exception handling, e.g. the below NotFound exception +sealed class ApiException(msg: String, val code: Int) : Exception(msg) + +class NotFoundException(msg: String, code: Int = HttpStatus.NOT_FOUND.value()) : ApiException(msg, code) + + +@ControllerAdvice +class DefaultExceptionHandler { + + @ExceptionHandler(value = [ApiException::class]) + fun onApiException(ex: ApiException, response: HttpServletResponse): Unit = + response.sendError(ex.code, ex.message) + + @ExceptionHandler(value = [NotImplementedError::class]) + fun onNotImplemented(ex: NotImplementedError, response: HttpServletResponse): Unit = + response.sendError(HttpStatus.NOT_IMPLEMENTED.value()) + + @ExceptionHandler(value = [ConstraintViolationException::class]) + fun onConstraintViolation(ex: ConstraintViolationException, response: HttpServletResponse): Unit = + response.sendError(HttpStatus.BAD_REQUEST.value(), ex.constraintViolations.joinToString(", ") { it.message }) +} diff --git a/modules/openapi-generator/src/main/resources/kotlin-spring/formParams.mustache b/modules/openapi-generator/src/main/resources/kotlin-spring/formParams.mustache new file mode 100644 index 0000000000..0b6649b894 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/kotlin-spring/formParams.mustache @@ -0,0 +1 @@ +{{#isFormParam}}{{^isFile}}{{#swaggerAnnotations}}@ApiParam(value = "{{{description}}}"{{#required}}, required=true{{/required}}{{#allowableValues}}, allowableValues="{{#values}}{{{.}}}{{^-last}}, {{/-last}}{{#-last}}{{/-last}}{{/values}}"{{/allowableValues}}{{#defaultValue}}, defaultValue="{{{defaultValue}}}"{{/defaultValue}}){{/swaggerAnnotations}} @RequestParam(value="{{baseName}}"{{#required}}, required=true{{/required}}{{^required}}, required=false{{/required}}) {{paramName}}: {{{dataType}}} {{/isFile}}{{#isFile}}{{#swaggerAnnotations}}@ApiParam(value = "file detail"){{/swaggerAnnotations}} {{#useBeanValidation}}@Valid{{/useBeanValidation}} @RequestPart("file") {{baseName}}: MultipartFile{{/isFile}}{{/isFormParam}} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/kotlin-spring/headerParams.mustache b/modules/openapi-generator/src/main/resources/kotlin-spring/headerParams.mustache new file mode 100644 index 0000000000..aa702dc454 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/kotlin-spring/headerParams.mustache @@ -0,0 +1 @@ +{{#isHeaderParam}}{{#swaggerAnnotations}}@ApiParam(value = "{{{description}}}" {{#required}},required=true{{/required}}{{#allowableValues}}, allowableValues="{{#values}}{{{.}}}{{^-last}}, {{/-last}}{{#-last}}{{/-last}}{{/values}}"{{/allowableValues}}{{#defaultValue}}, defaultValue="{{{defaultValue}}}"{{/defaultValue}}){{/swaggerAnnotations}} @RequestHeader(value="{{baseName}}", required={{#required}}true{{/required}}{{^required}}false{{/required}}) {{paramName}}: {{>optionalDataType}}{{/isHeaderParam}} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/kotlin-spring/libraries/spring-boot/README.mustache b/modules/openapi-generator/src/main/resources/kotlin-spring/libraries/spring-boot/README.mustache new file mode 100644 index 0000000000..c25481e376 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/kotlin-spring/libraries/spring-boot/README.mustache @@ -0,0 +1,21 @@ +# {{#title}}{{title}}{{/title}}{{^title}}Generated Kotlin Spring Boot App{{/title}} + +This Kotlin based [Spring Boot](https://spring.io/projects/spring-boot) application has been generated using the [OpenAPI Generator](https://github.com/OpenAPITools/openapi-generator). + +## Getting Started + +This document assumes you have either maven or gradle available, either via the wrapper or otherwise. This does not come with a gradle / maven wrapper checked in. + +By default a [`pom.xml`](pom.xml) file will be generated. If you specified `gradleBuildFile=true` when generating this project, a `build.gradle.kts` will also be generated. Note this uses [Gradle Kotlin DSL](https://github.com/gradle/kotlin-dsl). + +To build the project using maven, run: +```bash +mvn package && java -jar target/{{artifactId}}-{{artifactVersion}}.jar +``` + +To build the project using gradle, run: +```bash +gradle build && java -jar build/libs/{{artifactId}}-{{artifactVersion}}.jar +``` + +If all builds successfully, the server should run on [http://localhost:8080/](http://localhost:{{serverPort}}/) diff --git a/modules/openapi-generator/src/main/resources/kotlin-spring/libraries/spring-boot/application.mustache b/modules/openapi-generator/src/main/resources/kotlin-spring/libraries/spring-boot/application.mustache new file mode 100644 index 0000000000..b3245b7748 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/kotlin-spring/libraries/spring-boot/application.mustache @@ -0,0 +1,3 @@ +spring.application.name={{title}} +server.port={{serverPort}} +spring.jackson.serialization.WRITE_DATES_AS_TIMESTAMPS=false \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/kotlin-spring/libraries/spring-boot/buildGradleKts.mustache b/modules/openapi-generator/src/main/resources/kotlin-spring/libraries/spring-boot/buildGradleKts.mustache new file mode 100644 index 0000000000..d8c488429f --- /dev/null +++ b/modules/openapi-generator/src/main/resources/kotlin-spring/libraries/spring-boot/buildGradleKts.mustache @@ -0,0 +1,47 @@ +import org.jetbrains.kotlin.gradle.tasks.KotlinCompile + +buildscript { + repositories { + jcenter() + mavenCentral() + } + dependencies { + classpath("org.springframework.boot:spring-boot-gradle-plugin:2.0.3.RELEASE") + } +} + +group = "{{groupId}}" +version = "{{artifactVersion}}" + +repositories { + jcenter() + mavenCentral() +} + +tasks.withType { + kotlinOptions.jvmTarget = "1.8" +} + +plugins { + val kotlinVersion = "1.2.60" + id("org.jetbrains.kotlin.jvm") version kotlinVersion + id("org.jetbrains.kotlin.plugin.jpa") version kotlinVersion + id("org.jetbrains.kotlin.plugin.spring") version kotlinVersion + id("org.springframework.boot") version "2.0.3.RELEASE" + id("io.spring.dependency-management") version "1.0.5.RELEASE" +} + +dependencies { + compile("org.jetbrains.kotlin:kotlin-stdlib-jdk8") + compile("org.jetbrains.kotlin:kotlin-reflect") + compile("org.springframework.boot:spring-boot-starter-web") +{{#swaggerAnnotations}} + compile("io.swagger:swagger-annotations:1.5.21") +{{/swaggerAnnotations}} + compile("com.fasterxml.jackson.dataformat:jackson-dataformat-yaml") + compile("com.fasterxml.jackson.dataformat:jackson-dataformat-xml") + + testCompile("org.springframework.boot:spring-boot-starter-test") { + exclude(module = "junit") + } +} diff --git a/modules/openapi-generator/src/main/resources/kotlin-spring/libraries/spring-boot/pom.mustache b/modules/openapi-generator/src/main/resources/kotlin-spring/libraries/spring-boot/pom.mustache new file mode 100644 index 0000000000..fe2c87baae --- /dev/null +++ b/modules/openapi-generator/src/main/resources/kotlin-spring/libraries/spring-boot/pom.mustache @@ -0,0 +1,109 @@ + + 4.0.0 + {{groupId}} + {{artifactId}} + jar + {{artifactId}} + {{artifactVersion}} + + 1.2.60 + + + org.springframework.boot + spring-boot-starter-parent + 2.0.3.RELEASE + + + ${project.basedir}/src/main/kotlin + ${project.basedir}/src/test/kotlin + + + org.springframework.boot + spring-boot-maven-plugin + + + + repackage + + + + + + kotlin-maven-plugin + org.jetbrains.kotlin + ${kotlin.version} + + + spring + + 1.8 + + + + compile + compile + + compile + + + + test-compile + test-compile + + test-compile + + + + + + org.jetbrains.kotlin + kotlin-maven-allopen + ${kotlin.version} + + + + + + + + org.jetbrains.kotlin + kotlin-stdlib-jdk8 + ${kotlin.version} + + + org.jetbrains.kotlin + kotlin-reflect + ${kotlin.version} + + + org.springframework.boot + spring-boot-starter-web + + {{#swaggerAnnotations}} + + io.swagger + swagger-annotations + 1.5.21 + + {{/swaggerAnnotations}} + + com.fasterxml.jackson.dataformat + jackson-dataformat-yaml + + + com.fasterxml.jackson.dataformat + jackson-dataformat-xml + + + com.fasterxml.jackson.datatype + jackson-datatype-jsr310 + + {{#useBeanValidation}} + + + javax.validation + validation-api + + {{/useBeanValidation}} + + diff --git a/modules/openapi-generator/src/main/resources/kotlin-spring/libraries/spring-boot/settingsGradle.mustache b/modules/openapi-generator/src/main/resources/kotlin-spring/libraries/spring-boot/settingsGradle.mustache new file mode 100644 index 0000000000..b8fd6c4c41 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/kotlin-spring/libraries/spring-boot/settingsGradle.mustache @@ -0,0 +1 @@ +rootProject.name = "{{artifactId}}" \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/kotlin-spring/libraries/spring-boot/springBootApplication.mustache b/modules/openapi-generator/src/main/resources/kotlin-spring/libraries/spring-boot/springBootApplication.mustache new file mode 100644 index 0000000000..5b0d62ebf0 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/kotlin-spring/libraries/spring-boot/springBootApplication.mustache @@ -0,0 +1,14 @@ +package {{basePackage}} + +import org.springframework.boot.runApplication +import org.springframework.context.annotation.ComponentScan +import org.springframework.boot.autoconfigure.SpringBootApplication + + +@SpringBootApplication +@ComponentScan(basePackages = ["{{basePackage}}", "{{apiPackage}}", "{{modelPackage}}"]) +class Application + +fun main(args: Array) { + runApplication(*args) +} diff --git a/modules/openapi-generator/src/main/resources/kotlin-spring/model.mustache b/modules/openapi-generator/src/main/resources/kotlin-spring/model.mustache new file mode 100644 index 0000000000..37e21201cf --- /dev/null +++ b/modules/openapi-generator/src/main/resources/kotlin-spring/model.mustache @@ -0,0 +1,18 @@ +package {{package}} + +import java.util.Objects +{{#imports}}import {{import}} +{{/imports}} +{{#useBeanValidation}} +import javax.validation.Valid +import javax.validation.constraints.* +{{/useBeanValidation}} +{{#swaggerAnnotations}} +import io.swagger.annotations.ApiModelProperty +{{/swaggerAnnotations}} + +{{#models}} +{{#model}} +{{#isEnum}}{{>enumClass}}{{/isEnum}}{{^isEnum}}{{>dataClass}}{{/isEnum}} +{{/model}} +{{/models}} diff --git a/modules/openapi-generator/src/main/resources/kotlin-spring/optionalDataType.mustache b/modules/openapi-generator/src/main/resources/kotlin-spring/optionalDataType.mustache new file mode 100644 index 0000000000..976950e27e --- /dev/null +++ b/modules/openapi-generator/src/main/resources/kotlin-spring/optionalDataType.mustache @@ -0,0 +1 @@ +{{#useOptional}}{{#required}}{{{dataType}}}{{/required}}{{^required}}Optional<{{{dataType}}}>{{/required}}{{/useOptional}}{{^useOptional}}{{{dataType}}}{{/useOptional}} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/kotlin-spring/pathParams.mustache b/modules/openapi-generator/src/main/resources/kotlin-spring/pathParams.mustache new file mode 100644 index 0000000000..d83b2d0469 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/kotlin-spring/pathParams.mustache @@ -0,0 +1 @@ +{{#isPathParam}}{{#useBeanValidation}}{{>beanValidationPathParams}}{{/useBeanValidation}}{{#swaggerAnnotations}}@ApiParam(value = "{{{description}}}"{{#required}}, required=true{{/required}}{{#allowableValues}}, allowableValues = "{{#enumVars}}{{#lambda.escapeDoubleQuote}}{{{value}}}{{/lambda.escapeDoubleQuote}}{{^-last}}, {{/-last}}{{#-last}}{{/-last}}{{/enumVars}}"{{/allowableValues}}{{#defaultValue}}, defaultValue="{{{defaultValue}}}"{{/defaultValue}}){{/swaggerAnnotations}} @PathVariable("{{baseName}}") {{paramName}}: {{>optionalDataType}}{{/isPathParam}} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/kotlin-spring/queryParams.mustache b/modules/openapi-generator/src/main/resources/kotlin-spring/queryParams.mustache new file mode 100644 index 0000000000..ecceefb085 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/kotlin-spring/queryParams.mustache @@ -0,0 +1 @@ +{{#isQueryParam}}{{#useBeanValidation}}{{>beanValidationQueryParams}}{{/useBeanValidation}}{{#swaggerAnnotations}}@ApiParam(value = "{{{description}}}"{{#required}}, required = true{{/required}}{{#allowableValues}}, allowableValues = "{{#values}}{{{.}}}{{^-last}}, {{/-last}}{{#-last}}{{/-last}}{{/values}}"{{/allowableValues}}{{#defaultValue}}, defaultValue = "{{{defaultValue}}}"{{/defaultValue}}) {{#useBeanValidation}}@Valid{{/useBeanValidation}}{{/swaggerAnnotations}} @RequestParam(value = "{{baseName}}"{{#required}}, required = true{{/required}}{{^required}}, required = false{{/required}}{{#defaultValue}}, defaultValue="{{{defaultValue}}}"{{/defaultValue}}) {{paramName}}: {{>optionalDataType}}{{/isQueryParam}} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/kotlin-spring/returnTypes.mustache b/modules/openapi-generator/src/main/resources/kotlin-spring/returnTypes.mustache new file mode 100644 index 0000000000..67d79cc198 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/kotlin-spring/returnTypes.mustache @@ -0,0 +1 @@ +{{#isMapContainer}}{{#reactive}}Mono<{{/reactive}}Map{{/reactive}}>{{/isMapContainer}}{{#isListContainer}}{{#reactive}}Flux{{/reactive}}{{^reactive}}List{{/reactive}}<{{{returnType}}}>{{/isListContainer}}{{^returnContainer}}{{#reactive}}Mono<{{{returnType}}}>{{/reactive}}{{^reactive}}{{{returnType}}}{{/reactive}}{{/returnContainer}} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/kotlin-spring/returnValue.mustache b/modules/openapi-generator/src/main/resources/kotlin-spring/returnValue.mustache new file mode 100644 index 0000000000..4973c83431 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/kotlin-spring/returnValue.mustache @@ -0,0 +1 @@ +{{#serviceInterface}}ResponseEntity(service.{{operationId}}({{#allParams}}{{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}}), HttpStatus.OK){{/serviceInterface}}{{^serviceInterface}}ResponseEntity(HttpStatus.NOT_IMPLEMENTED){{/serviceInterface}} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/kotlin-spring/service.mustache b/modules/openapi-generator/src/main/resources/kotlin-spring/service.mustache new file mode 100644 index 0000000000..32bb190ea6 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/kotlin-spring/service.mustache @@ -0,0 +1,13 @@ +package {{package}} + +{{#imports}}import {{import}} +{{/imports}} + +{{#operations}} +interface {{classname}}Service { +{{#operation}} + + fun {{operationId}}({{#allParams}}{{paramName}}: {{^isFile}}{{>optionalDataType}}{{/isFile}}{{#isFile}}org.springframework.web.multipart.MultipartFile{{/isFile}}{{#hasMore}},{{/hasMore}}{{/allParams}}): {{>returnTypes}} +{{/operation}} +} +{{/operations}} diff --git a/modules/openapi-generator/src/main/resources/kotlin-spring/serviceImpl.mustache b/modules/openapi-generator/src/main/resources/kotlin-spring/serviceImpl.mustache new file mode 100644 index 0000000000..d3dcedb061 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/kotlin-spring/serviceImpl.mustache @@ -0,0 +1,17 @@ +package {{package}} + +{{#imports}}import {{import}} +{{/imports}} +import org.springframework.stereotype.Service + +@Service +{{#operations}} +class {{classname}}ServiceImpl : {{classname}}Service { +{{#operation}} + + override fun {{operationId}}({{#allParams}}{{paramName}}: {{^isFile}}{{>optionalDataType}}{{/isFile}}{{#isFile}}org.springframework.web.multipart.MultipartFile{{/isFile}}{{#hasMore}},{{/hasMore}}{{/allParams}}): {{>returnTypes}} { + TODO("Implement me") + } +{{/operation}} +} +{{/operations}} diff --git a/modules/openapi-generator/src/main/resources/php-slim-server/AbstractApiController.mustache b/modules/openapi-generator/src/main/resources/php-slim-server/AbstractApiController.mustache index c058491dd4..4ba2ef121c 100644 --- a/modules/openapi-generator/src/main/resources/php-slim-server/AbstractApiController.mustache +++ b/modules/openapi-generator/src/main/resources/php-slim-server/AbstractApiController.mustache @@ -44,7 +44,8 @@ namespace {{invokerPackage}}; * @author OpenAPI Generator team * @link https://github.com/openapitools/openapi-generator */ -abstract class AbstractApiController { +abstract class AbstractApiController +{ /** * @var \Interop\Container\ContainerInterface Slim app container instance @@ -56,8 +57,8 @@ abstract class AbstractApiController { * * @param \Interop\Container\ContainerInterface $container Slim app container instance */ - public function __construct($container) { + public function __construct($container) + { $this->container = $container; } - } diff --git a/modules/openapi-generator/src/main/resources/php-slim-server/README.mustache b/modules/openapi-generator/src/main/resources/php-slim-server/README.mustache index c837523158..4dde7f075d 100644 --- a/modules/openapi-generator/src/main/resources/php-slim-server/README.mustache +++ b/modules/openapi-generator/src/main/resources/php-slim-server/README.mustache @@ -30,15 +30,17 @@ $ php -S localhost:8888 -t php-slim-server ## Run tests -This package uses PHPUnit 4.8 for unit testing. +This package uses PHPUnit 4.8 for unit testing and PHP Codesniffer to check source code against user defined coding standard(`phpcsStandard` generator config option). [Test folder]({{testBasePath}}) contains templates which you can fill with real test assertions. How to write tests read at [PHPUnit Manual - Chapter 2. Writing Tests for PHPUnit](https://phpunit.de/manual/4.8/en/writing-tests-for-phpunit.html). +How to configure PHP CodeSniffer read at [PHP CodeSniffer Documentation](https://github.com/squizlabs/PHP_CodeSniffer/wiki). Command | Tool | Target ---- | ---- | ---- `$ composer test` | PHPUnit | All tests `$ composer run test-apis` | PHPUnit | Apis tests `$ composer run test-models` | PHPUnit | Models tests +`$ composer run phpcs` | PHP CodeSniffer | All files {{#generateApiDocs}} ## API Endpoints diff --git a/modules/openapi-generator/src/main/resources/php-slim-server/SlimRouter.mustache b/modules/openapi-generator/src/main/resources/php-slim-server/SlimRouter.mustache index 11eb61d5ac..18ee144e6d 100644 --- a/modules/openapi-generator/src/main/resources/php-slim-server/SlimRouter.mustache +++ b/modules/openapi-generator/src/main/resources/php-slim-server/SlimRouter.mustache @@ -10,7 +10,7 @@ * @link https://github.com/openapitools/openapi-generator */ -/**{{#apiInfo}}{{#appName}} +/**{{#apiInfo}}{{#appName}} * {{{appName}}} * {{/appName}} @@ -51,7 +51,8 @@ use Tuupola\Middleware\HttpBasicAuthentication; * @author OpenAPI Generator team * @link https://github.com/openapitools/openapi-generator */ -class SlimRouter { +class SlimRouter +{ /** * @var $slimApp Slim\App instance @@ -64,7 +65,8 @@ class SlimRouter { * @param ContainerInterface|array $container Either a ContainerInterface or an associative array of app settings * @throws InvalidArgumentException when no container is provided that implements ContainerInterface */ - public function __construct($container = []) { + public function __construct($container = []) + { $app = new App($container); $basicAuth = new HttpBasicAuthentication([ @@ -80,7 +82,8 @@ class SlimRouter { {{#operations}} {{#operation}} $app->{{httpMethod}}( - '{{{basePathWithoutHost}}}{{{path}}}', {{classname}}::class . ':{{operationId}}' + '{{{basePathWithoutHost}}}{{{path}}}', + {{classname}}::class . ':{{operationId}}' {{#hasAuthMethods}} {{#authMethods}} {{#isBasic}} @@ -101,7 +104,8 @@ class SlimRouter { * Returns Slim Framework instance * @return App */ - public function getSlimApp() { + public function getSlimApp() + { return $this->slimApp; } } diff --git a/modules/openapi-generator/src/main/resources/php-slim-server/api.mustache b/modules/openapi-generator/src/main/resources/php-slim-server/api.mustache index 84e2b6a1ac..1bc94ad3cd 100644 --- a/modules/openapi-generator/src/main/resources/php-slim-server/api.mustache +++ b/modules/openapi-generator/src/main/resources/php-slim-server/api.mustache @@ -46,14 +46,19 @@ use {{invokerPackage}}\AbstractApiController; * @author OpenAPI Generator team * @link https://github.com/openapitools/openapi-generator */ -class {{classname}} extends AbstractApiController { - +class {{classname}} extends AbstractApiController +{ {{#operations}} {{#operation}} + /** * {{httpMethod}} {{operationId}} + {{#summary}} * Summary: {{summary}} + {{/summary}} + {{#notes}} * Notes: {{notes}} + {{/notes}} {{#hasProduces}} * Output-Formats: [{{#produces}}{{{mediaType}}}{{#hasMore}}, {{/hasMore}}{{/produces}}] {{/hasProduces}} @@ -62,7 +67,8 @@ class {{classname}} extends AbstractApiController { * @param \Psr\Http\Message\ResponseInterface $response Response * @param array|null $args Path arguments */ - public function {{operationId}}($request, $response, $args) { + public function {{operationId}}($request, $response, $args) + { {{#hasHeaderParams}} $headers = $request->getHeaders(); {{#headerParams}} @@ -96,7 +102,6 @@ class {{classname}} extends AbstractApiController { $response->write('How about implementing {{nickname}} as a {{httpMethod}} method ?'); return $response; } - {{#hasMore}}{{/hasMore}} {{/operation}} {{/operations}} } diff --git a/modules/openapi-generator/src/main/resources/php-slim-server/api_test.mustache b/modules/openapi-generator/src/main/resources/php-slim-server/api_test.mustache index ecc80a622c..234cbb5a63 100644 --- a/modules/openapi-generator/src/main/resources/php-slim-server/api_test.mustache +++ b/modules/openapi-generator/src/main/resources/php-slim-server/api_test.mustache @@ -45,34 +45,35 @@ use {{apiPackage}}\{{classname}}; * @link https://github.com/openapitools/openapi-generator * @coversDefaultClass \{{modelPackage}}\{{classname}} */ -{{#operations}}class {{classname}}Test extends \PHPUnit_Framework_TestCase { +{{#operations}}class {{classname}}Test extends \PHPUnit_Framework_TestCase +{ /** * Setup before running any test cases */ - public static function setUpBeforeClass() { - + public static function setUpBeforeClass() + { } /** * Setup before running each test case */ - public function setUp() { - + public function setUp() + { } /** * Clean up after running each test case */ - public function tearDown() { - + public function tearDown() + { } /** * Clean up after running all test cases */ - public static function tearDownAfterClass() { - + public static function tearDownAfterClass() + { } {{#operation}} @@ -82,8 +83,8 @@ use {{apiPackage}}\{{classname}}; * {{{summary}}}. * @covers ::{{{operationId}}} */ - public function test{{operationIdCamelCase}}() { - + public function test{{operationIdCamelCase}}() + { } {{/operation}} } diff --git a/modules/openapi-generator/src/main/resources/php-slim-server/composer.mustache b/modules/openapi-generator/src/main/resources/php-slim-server/composer.mustache index a27e79ec42..a260f3cb8a 100644 --- a/modules/openapi-generator/src/main/resources/php-slim-server/composer.mustache +++ b/modules/openapi-generator/src/main/resources/php-slim-server/composer.mustache @@ -6,7 +6,8 @@ "tuupola/slim-basic-auth": "^3.0.0" }, "require-dev": { - "phpunit/phpunit": "^4.8" + "phpunit/phpunit": "^4.8", + "squizlabs/php_codesniffer": "^3.0" }, "autoload": { "psr-4": { "{{escapedInvokerPackage}}\\": "{{srcBasePath}}/" } @@ -20,6 +21,7 @@ "@test-models" ], "test-apis": "phpunit --testsuite Apis", - "test-models": "phpunit --testsuite Models" + "test-models": "phpunit --testsuite Models", + "phpcs": "phpcs ./ --ignore=vendor --warning-severity=0 --standard={{phpcsStandard}}" } } \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/php-slim-server/model.mustache b/modules/openapi-generator/src/main/resources/php-slim-server/model.mustache index 94fd28ef53..a1f40f818f 100644 --- a/modules/openapi-generator/src/main/resources/php-slim-server/model.mustache +++ b/modules/openapi-generator/src/main/resources/php-slim-server/model.mustache @@ -7,12 +7,12 @@ namespace {{modelPackage}}; /** * {{classname}} */ -class {{classname}} { - +class {{classname}} +{ {{#vars}} + /** @var {{dataType}} ${{name}} {{#description}}{{description}}{{/description}}*/ private ${{name}}; - {{/vars}} } {{/model}}{{/models}} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/php-slim-server/model_test.mustache b/modules/openapi-generator/src/main/resources/php-slim-server/model_test.mustache index cc559bd1c6..ea2518ef74 100644 --- a/modules/openapi-generator/src/main/resources/php-slim-server/model_test.mustache +++ b/modules/openapi-generator/src/main/resources/php-slim-server/model_test.mustache @@ -47,40 +47,42 @@ use {{modelPackage}}\{{classname}}; * @link https://github.com/openapitools/openapi-generator * @coversDefaultClass \{{modelPackage}}\{{classname}} */ -class {{classname}}Test extends \PHPUnit_Framework_TestCase { +class {{classname}}Test extends \PHPUnit_Framework_TestCase +{ /** * Setup before running any test cases */ - public static function setUpBeforeClass() { - + public static function setUpBeforeClass() + { } /** * Setup before running each test case */ - public function setUp() { - + public function setUp() + { } /** * Clean up after running each test case */ - public function tearDown() { - + public function tearDown() + { } /** * Clean up after running all test cases */ - public static function tearDownAfterClass() { - + public static function tearDownAfterClass() + { } /** * Test "{{classname}}" */ - public function test{{classname}}() { + public function test{{classname}}() + { $test{{classname}} = new {{classname}}(); } {{#vars}} @@ -88,9 +90,9 @@ class {{classname}}Test extends \PHPUnit_Framework_TestCase { /** * Test attribute "{{name}}" */ - public function testProperty{{nameInCamelCase}}() { - + public function testProperty{{nameInCamelCase}}() + { } {{/vars}} } -{{/model}}{{/models}} +{{/model}}{{/models}} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/php-symfony/api_controller.mustache b/modules/openapi-generator/src/main/resources/php-symfony/api_controller.mustache index 6da34c82b6..3ab32095ec 100644 --- a/modules/openapi-generator/src/main/resources/php-symfony/api_controller.mustache +++ b/modules/openapi-generator/src/main/resources/php-symfony/api_controller.mustache @@ -87,6 +87,10 @@ class {{controllerName}} extends Controller // Set key with prefix in query string $security{{name}} = $request->query->get('{{keyParamName}}'); {{/isKeyInQuery}} + {{#isKeyInCookie}} + // Set key with prefix in cookies + $security{{name}} = $request->cookies->get('{{keyParamName}}'); + {{/isKeyInCookie}} {{/isApiKey}} {{#isBasic}} // HTTP basic authentication required diff --git a/modules/openapi-generator/src/main/resources/python/asyncio/rest.mustache b/modules/openapi-generator/src/main/resources/python/asyncio/rest.mustache index 8c9d49dc14..528e550d74 100644 --- a/modules/openapi-generator/src/main/resources/python/asyncio/rest.mustache +++ b/modules/openapi-generator/src/main/resources/python/asyncio/rest.mustache @@ -38,21 +38,24 @@ class RESTClientObject(object): def __init__(self, configuration, pools_size=4, maxsize=4): # maxsize is number of requests to host that are allowed in parallel - # ca_certs vs cert_file vs key_file - # http://stackoverflow.com/a/23957365/2985775 - # ca_certs - if configuration.ssl_ca_cert: - ca_certs = configuration.ssl_ca_cert + if configuration.verify_ssl: + + # ca_certs + if configuration.ssl_ca_cert: + ca_certs = configuration.ssl_ca_cert + else: + # if not set certificate file, use Mozilla's root certificates. + ca_certs = certifi.where() + + ssl_context = ssl.create_default_context(cafile=ca_certs) + + if configuration.cert_file: + ssl_context.load_cert_chain( + configuration.cert_file, keyfile=configuration.key_file + ) else: - # if not set certificate file, use Mozilla's root certificates. - ca_certs = certifi.where() - - ssl_context = ssl.create_default_context(cafile=ca_certs) - if configuration.cert_file: - ssl_context.load_cert_chain( - configuration.cert_file, keyfile=configuration.key_file - ) + ssl_context = None connector = aiohttp.TCPConnector( limit=maxsize, diff --git a/modules/openapi-generator/src/test/java/org/openapitools/codegen/DefaultCodegenTest.java b/modules/openapi-generator/src/test/java/org/openapitools/codegen/DefaultCodegenTest.java index 2666cc2c6d..672dd0be08 100644 --- a/modules/openapi-generator/src/test/java/org/openapitools/codegen/DefaultCodegenTest.java +++ b/modules/openapi-generator/src/test/java/org/openapitools/codegen/DefaultCodegenTest.java @@ -38,33 +38,12 @@ import org.testng.Assert; import org.testng.annotations.Test; import java.lang.reflect.Method; -import java.util.Collections; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; +import java.util.*; import java.util.stream.Collectors; + public class DefaultCodegenTest { - @Test - public void testCamelize() throws Exception { - Assert.assertEquals(DefaultCodegen.camelize("abcd"), "Abcd"); - Assert.assertEquals(DefaultCodegen.camelize("some-value"), "SomeValue"); - Assert.assertEquals(DefaultCodegen.camelize("some_value"), "SomeValue"); - Assert.assertEquals(DefaultCodegen.camelize("$type"), "$Type"); - - Assert.assertEquals(DefaultCodegen.camelize("abcd", true), "abcd"); - Assert.assertEquals(DefaultCodegen.camelize("some-value", true), "someValue"); - Assert.assertEquals(DefaultCodegen.camelize("some_value", true), "someValue"); - Assert.assertEquals(DefaultCodegen.camelize("Abcd", true), "abcd"); - Assert.assertEquals(DefaultCodegen.camelize("$type", true), "$type"); - - Assert.assertEquals(DefaultCodegen.camelize("123", true), "123"); - Assert.assertEquals(DefaultCodegen.camelize("$123", true), "$123"); - } - @Test public void testHasBodyParameter() throws Exception { final Schema refSchema = new Schema<>().$ref("#/components/schemas/Pet"); @@ -311,6 +290,66 @@ public class DefaultCodegenTest { Assert.assertEquals(testedEnumVar.getOrDefault("isString", ""), false); } + @Test + public void updateCodegenPropertyEnumWithExtention() { + { + CodegenProperty enumProperty = codegenPropertyWithXEnumVarName(Arrays.asList("dog", "cat"), Arrays.asList("DOGVAR", "CATVAR")); + (new DefaultCodegen()).updateCodegenPropertyEnum(enumProperty); + List> enumVars = (List>) enumProperty.getAllowableValues().get("enumVars"); + Assert.assertNotNull(enumVars); + Assert.assertNotNull(enumVars.get(0)); + Assert.assertEquals(enumVars.get(0).getOrDefault("name", ""), "DOGVAR"); + Assert.assertEquals(enumVars.get(0).getOrDefault("value", ""), "\"dog\""); + Assert.assertNotNull(enumVars.get(1)); + Assert.assertEquals(enumVars.get(1).getOrDefault("name", ""), "CATVAR"); + Assert.assertEquals(enumVars.get(1).getOrDefault("value", ""), "\"cat\""); + } + { + CodegenProperty enumProperty = codegenPropertyWithXEnumVarName(Arrays.asList("1", "2"), Arrays.asList("ONE", "TWO")); + (new DefaultCodegen()).updateCodegenPropertyEnum(enumProperty); + List> enumVars = (List>) enumProperty.getAllowableValues().get("enumVars"); + Assert.assertEquals(enumVars.get(0).getOrDefault("name", ""), "ONE"); + Assert.assertEquals(enumVars.get(0).getOrDefault("value", ""), "\"1\""); + Assert.assertEquals(enumVars.get(1).getOrDefault("name", ""), "TWO"); + Assert.assertEquals(enumVars.get(1).getOrDefault("value", ""), "\"2\""); + } + { + CodegenProperty enumProperty = codegenPropertyWithXEnumVarName(Arrays.asList("a", "b", "c", "d"), Arrays.asList("FOO", "BAR")); + (new DefaultCodegen()).updateCodegenPropertyEnum(enumProperty); + List> enumVars = (List>) enumProperty.getAllowableValues().get("enumVars"); + Assert.assertEquals(enumVars.get(0).getOrDefault("name", ""), "FOO"); + Assert.assertEquals(enumVars.get(1).getOrDefault("name", ""), "BAR"); + Assert.assertEquals(enumVars.get(2).getOrDefault("name", ""), "C"); + Assert.assertEquals(enumVars.get(3).getOrDefault("name", ""), "D"); + } + { + CodegenProperty enumProperty = codegenPropertyWithXEnumVarName(Arrays.asList("a", "b"), Arrays.asList("FOO", "BAR", "BAZ")); + (new DefaultCodegen()).updateCodegenPropertyEnum(enumProperty); + List> enumVars = (List>) enumProperty.getAllowableValues().get("enumVars"); + Assert.assertEquals(enumVars.get(0).getOrDefault("name", ""), "FOO"); + Assert.assertEquals(enumVars.get(1).getOrDefault("name", ""), "BAR"); + Assert.assertEquals(enumVars.size(), 2); + } + } + + @Test + public void postProcessModelsEnumWithExtention() { + final DefaultCodegen codegen = new DefaultCodegen(); + Map objs = codegenModelWithXEnumVarName(); + CodegenModel cm = (CodegenModel) ((Map) ((List) objs.get("models")).get(0)).get("model"); + + codegen.postProcessModelsEnum(objs); + + List> enumVars = (List>) cm.getAllowableValues().get("enumVars"); + Assert.assertNotNull(enumVars); + Assert.assertNotNull(enumVars.get(0)); + Assert.assertEquals(enumVars.get(0).getOrDefault("name", ""), "DOGVAR"); + Assert.assertEquals(enumVars.get(0).getOrDefault("value", ""), "\"dog\""); + Assert.assertNotNull(enumVars.get(1)); + Assert.assertEquals(enumVars.get(1).getOrDefault("name", ""), "CATVAR"); + Assert.assertEquals(enumVars.get(1).getOrDefault("value", ""), "\"cat\""); + } + @Test public void testExample1() { final OpenAPI openAPI = new OpenAPIParser().readLocation("src/test/resources/3_0/examples.yaml", null, new ParseOptions()).getOpenAPI(); @@ -407,6 +446,60 @@ public class DefaultCodegenTest { verifyPersonDiscriminator(personModel.discriminator); } + @Test + public void testCallbacks() { + final OpenAPI openAPI = new OpenAPIParser().readLocation("src/test/resources/3_0/callbacks.yaml", null, new ParseOptions()).getOpenAPI(); + final CodegenConfig codegen = new DefaultCodegen(); + + final String path = "/streams"; + Operation subscriptionOperation = openAPI.getPaths().get("/streams").getPost(); + CodegenOperation op = codegen.fromOperation(path, "post", subscriptionOperation, openAPI.getComponents().getSchemas(), openAPI); + + Assert.assertFalse(op.isCallbackRequest); + Assert.assertNotNull(op.operationId); + Assert.assertEquals(op.callbacks.size(), 2); + + CodegenCallback cbB = op.callbacks.get(1); + Assert.assertEquals(cbB.name, "dummy"); + Assert.assertFalse(cbB.hasMore); + Assert.assertEquals(cbB.urls.size(), 0); + + CodegenCallback cbA = op.callbacks.get(0); + Assert.assertEquals(cbA.name, "onData"); + Assert.assertTrue(cbA.hasMore); + + Assert.assertEquals(cbA.urls.size(), 2); + + CodegenCallback.Url urlB = cbA.urls.get(1); + Assert.assertEquals(urlB.expression, "{$request.query.callbackUrl}/test"); + Assert.assertFalse(urlB.hasMore); + Assert.assertEquals(urlB.requests.size(), 0); + + CodegenCallback.Url urlA = cbA.urls.get(0); + Assert.assertEquals(urlA.expression, "{$request.query.callbackUrl}/data"); + Assert.assertTrue(urlA.hasMore); + Assert.assertEquals(urlA.requests.size(), 2); + + urlA.requests.forEach(req -> { + Assert.assertTrue(req.isCallbackRequest); + Assert.assertNotNull(req.bodyParam); + Assert.assertEquals(req.responses.size(), 2); + + switch (req.httpMethod.toLowerCase(Locale.getDefault())) { + case "post": + Assert.assertEquals(req.operationId, "onDataDataPost"); + Assert.assertEquals(req.bodyParam.dataType, "NewNotificationData"); + break; + case "delete": + Assert.assertEquals(req.operationId, "onDataDataDelete"); + Assert.assertEquals(req.bodyParam.dataType, "DeleteNotificationData"); + break; + default: + Assert.fail(String.format(Locale.getDefault(), "invalid callback request http method '%s'", req.httpMethod)); + } + }); + } + private void verifyPersonDiscriminator(CodegenDiscriminator discriminator) { CodegenDiscriminator test = new CodegenDiscriminator(); test.setPropertyName("$_type"); @@ -429,4 +522,30 @@ public class DefaultCodegenTest { array.dataType = "Array"; return array; } + + private CodegenProperty codegenPropertyWithXEnumVarName(List values, List aliases) { + final CodegenProperty var = new CodegenProperty(); + final HashMap allowableValues = new HashMap<>(); + allowableValues.put("values", values); + var.setAllowableValues(allowableValues); + var.dataType = "String"; + Map extentions = Collections.singletonMap("x-enum-varnames", aliases); + var.setVendorExtensions(extentions); + return var; + } + + private Map codegenModelWithXEnumVarName() { + final CodegenModel cm = new CodegenModel(); + cm.isEnum = true; + final HashMap allowableValues = new HashMap<>(); + allowableValues.put("values", Arrays.asList("dog", "cat")); + cm.setAllowableValues(allowableValues); + cm.dataType = "String"; + final List aliases = Arrays.asList("DOGVAR", "CATVAR"); + Map extentions = Collections.singletonMap("x-enum-varnames", aliases); + cm.setVendorExtensions(extentions); + cm.setVars(Collections.emptyList()); + Map objs = Collections.singletonMap("models", Collections.singletonList(Collections.singletonMap("model", cm))); + return objs; + } } diff --git a/modules/openapi-generator/src/test/java/org/openapitools/codegen/kotlin/spring/KotlinSpringServerCodegenTest.java b/modules/openapi-generator/src/test/java/org/openapitools/codegen/kotlin/spring/KotlinSpringServerCodegenTest.java new file mode 100644 index 0000000000..17ec8e74c2 --- /dev/null +++ b/modules/openapi-generator/src/test/java/org/openapitools/codegen/kotlin/spring/KotlinSpringServerCodegenTest.java @@ -0,0 +1,115 @@ +package org.openapitools.codegen.kotlin.spring; + +import io.swagger.v3.oas.models.OpenAPI; +import io.swagger.v3.oas.models.info.Info; +import io.swagger.v3.oas.models.servers.Server; +import org.openapitools.codegen.CodegenConstants; +import org.openapitools.codegen.languages.KotlinSpringServerCodegen; +import org.testng.Assert; +import org.testng.annotations.Test; + +public class KotlinSpringServerCodegenTest { + + @Test + public void testInitialConfigValues() throws Exception { + final KotlinSpringServerCodegen codegen = new KotlinSpringServerCodegen(); + codegen.processOpts(); + + final OpenAPI openAPI = new OpenAPI(); + openAPI.addServersItem(new Server().url("https://api.abcde.xy:8082/v2")); + openAPI.setInfo(new Info()); + codegen.preprocessOpenAPI(openAPI); + + Assert.assertEquals(codegen.getLibrary(), KotlinSpringServerCodegen.SPRING_BOOT); + Assert.assertTrue(codegen.supportedLibraries().containsKey(KotlinSpringServerCodegen.SPRING_BOOT)); + + Assert.assertEquals(codegen.modelPackage(), "org.openapitools.model"); + Assert.assertEquals(codegen.additionalProperties().get(CodegenConstants.MODEL_PACKAGE), "org.openapitools.model"); + Assert.assertEquals(codegen.apiPackage(), "org.openapitools.api"); + Assert.assertEquals(codegen.additionalProperties().get(CodegenConstants.API_PACKAGE), "org.openapitools.api"); + Assert.assertEquals(codegen.getBasePackage(), "org.openapitools"); + Assert.assertEquals(codegen.additionalProperties().get(KotlinSpringServerCodegen.BASE_PACKAGE), "org.openapitools"); + Assert.assertEquals(codegen.getServerPort(), "8080"); + Assert.assertEquals(codegen.additionalProperties().get(KotlinSpringServerCodegen.SERVER_PORT), "8080"); + } + + @Test + public void testSettersForConfigValues() throws Exception { + final KotlinSpringServerCodegen codegen = new KotlinSpringServerCodegen(); + codegen.setModelPackage("xx.yyyyyyyy.model"); + codegen.setApiPackage("xx.yyyyyyyy.api"); + codegen.setBasePackage("xx.yyyyyyyy.base"); + codegen.setServerPort("8181"); + codegen.setExceptionHandler(false); + codegen.setGradleBuildFile(false); + codegen.setSwaggerAnnotations(true); + codegen.setServiceInterface(true); + codegen.setServiceImplementation(true); + codegen.setUseBeanValidation(false); + codegen.processOpts(); + + Assert.assertEquals(codegen.modelPackage(), "xx.yyyyyyyy.model"); + Assert.assertEquals(codegen.additionalProperties().get(CodegenConstants.MODEL_PACKAGE), "xx.yyyyyyyy.model"); + Assert.assertEquals(codegen.apiPackage(), "xx.yyyyyyyy.api"); + Assert.assertEquals(codegen.additionalProperties().get(CodegenConstants.API_PACKAGE), "xx.yyyyyyyy.api"); + Assert.assertEquals(codegen.getBasePackage(), "xx.yyyyyyyy.base"); + Assert.assertEquals(codegen.additionalProperties().get(KotlinSpringServerCodegen.BASE_PACKAGE), "xx.yyyyyyyy.base"); + Assert.assertEquals(codegen.getServerPort(), "8181"); + Assert.assertEquals(codegen.additionalProperties().get(KotlinSpringServerCodegen.SERVER_PORT), "8181"); + Assert.assertFalse(codegen.getExceptionHandler()); + Assert.assertEquals(codegen.additionalProperties().get(KotlinSpringServerCodegen.EXCEPTION_HANDLER), false); + Assert.assertFalse(codegen.getGradleBuildFile()); + Assert.assertEquals(codegen.additionalProperties().get(KotlinSpringServerCodegen.GRADLE_BUILD_FILE), false); + Assert.assertTrue(codegen.getSwaggerAnnotations()); + Assert.assertEquals(codegen.additionalProperties().get(KotlinSpringServerCodegen.SWAGGER_ANNOTATIONS), true); + Assert.assertTrue(codegen.getServiceInterface()); + Assert.assertEquals(codegen.additionalProperties().get(KotlinSpringServerCodegen.SERVICE_INTERFACE), true); + Assert.assertTrue(codegen.getServiceImplementation()); + Assert.assertEquals(codegen.additionalProperties().get(KotlinSpringServerCodegen.SERVICE_IMPLEMENTATION), true); + Assert.assertFalse(codegen.getUseBeanValidation()); + Assert.assertEquals(codegen.additionalProperties().get(KotlinSpringServerCodegen.USE_BEANVALIDATION), false); + } + + @Test + public void testAdditionalPropertiesPutForConfigValues() throws Exception { + final KotlinSpringServerCodegen codegen = new KotlinSpringServerCodegen(); + codegen.additionalProperties().put(CodegenConstants.MODEL_PACKAGE, "xyz.yyyyy.mmmmm.model"); + codegen.additionalProperties().put(CodegenConstants.API_PACKAGE, "xyz.yyyyy.aaaaa.api"); + codegen.additionalProperties().put(KotlinSpringServerCodegen.BASE_PACKAGE, "xyz.yyyyy.bbbb.base"); + codegen.additionalProperties().put(KotlinSpringServerCodegen.SERVER_PORT, "8088"); + codegen.additionalProperties().put(KotlinSpringServerCodegen.EXCEPTION_HANDLER, false); + codegen.additionalProperties().put(KotlinSpringServerCodegen.GRADLE_BUILD_FILE, false); + codegen.additionalProperties().put(KotlinSpringServerCodegen.SWAGGER_ANNOTATIONS, true); + codegen.additionalProperties().put(KotlinSpringServerCodegen.SERVICE_INTERFACE, true); + codegen.additionalProperties().put(KotlinSpringServerCodegen.SERVICE_IMPLEMENTATION, true); + codegen.additionalProperties().put(KotlinSpringServerCodegen.USE_BEANVALIDATION, false); + codegen.processOpts(); + + final OpenAPI openAPI = new OpenAPI(); + openAPI.addServersItem(new Server().url("https://api.abcde.xy:8082/v2")); + openAPI.setInfo(new Info()); + openAPI.getInfo().setTitle("Some test API"); + codegen.preprocessOpenAPI(openAPI); + + Assert.assertEquals(codegen.modelPackage(), "xyz.yyyyy.mmmmm.model"); + Assert.assertEquals(codegen.additionalProperties().get(CodegenConstants.MODEL_PACKAGE), "xyz.yyyyy.mmmmm.model"); + Assert.assertEquals(codegen.apiPackage(), "xyz.yyyyy.aaaaa.api"); + Assert.assertEquals(codegen.additionalProperties().get(CodegenConstants.API_PACKAGE), "xyz.yyyyy.aaaaa.api"); + Assert.assertEquals(codegen.getBasePackage(), "xyz.yyyyy.bbbb.base"); + Assert.assertEquals(codegen.additionalProperties().get(KotlinSpringServerCodegen.BASE_PACKAGE), "xyz.yyyyy.bbbb.base"); + Assert.assertEquals(codegen.additionalProperties().get(KotlinSpringServerCodegen.TITLE), "someTest"); + Assert.assertEquals(codegen.additionalProperties().get(KotlinSpringServerCodegen.SERVER_PORT), "8088"); + Assert.assertFalse(codegen.getExceptionHandler()); + Assert.assertEquals(codegen.additionalProperties().get(KotlinSpringServerCodegen.EXCEPTION_HANDLER), false); + Assert.assertFalse(codegen.getGradleBuildFile()); + Assert.assertEquals(codegen.additionalProperties().get(KotlinSpringServerCodegen.GRADLE_BUILD_FILE), false); + Assert.assertTrue(codegen.getSwaggerAnnotations()); + Assert.assertEquals(codegen.additionalProperties().get(KotlinSpringServerCodegen.SWAGGER_ANNOTATIONS), true); + Assert.assertTrue(codegen.getServiceInterface()); + Assert.assertEquals(codegen.additionalProperties().get(KotlinSpringServerCodegen.SERVICE_INTERFACE), true); + Assert.assertTrue(codegen.getServiceImplementation()); + Assert.assertEquals(codegen.additionalProperties().get(KotlinSpringServerCodegen.SERVICE_IMPLEMENTATION), true); + Assert.assertFalse(codegen.getUseBeanValidation()); + Assert.assertEquals(codegen.additionalProperties().get(KotlinSpringServerCodegen.USE_BEANVALIDATION), false); + } +} diff --git a/modules/openapi-generator/src/test/java/org/openapitools/codegen/options/PhpSlimServerOptionsProvider.java b/modules/openapi-generator/src/test/java/org/openapitools/codegen/options/PhpSlimServerOptionsProvider.java index c170e2ff57..39186e7b05 100644 --- a/modules/openapi-generator/src/test/java/org/openapitools/codegen/options/PhpSlimServerOptionsProvider.java +++ b/modules/openapi-generator/src/test/java/org/openapitools/codegen/options/PhpSlimServerOptionsProvider.java @@ -19,6 +19,7 @@ package org.openapitools.codegen.options; import org.openapitools.codegen.CodegenConstants; import org.openapitools.codegen.languages.AbstractPhpCodegen; +import org.openapitools.codegen.languages.PhpSlimServerCodegen; import com.google.common.collect.ImmutableMap; @@ -38,6 +39,7 @@ public class PhpSlimServerOptionsProvider implements OptionsProvider { public static final String ENSURE_UNIQUE_PARAMS_VALUE = "true"; public static final String ALLOW_UNICODE_IDENTIFIERS_VALUE = "false"; public static final String PREPEND_FORM_OR_BODY_PARAMETERS_VALUE = "true"; + public static final String PHPCS_STANDARD_VALUE = "PSR12"; @Override public String getLanguage() { @@ -60,6 +62,7 @@ public class PhpSlimServerOptionsProvider implements OptionsProvider { .put(CodegenConstants.ENSURE_UNIQUE_PARAMS, ENSURE_UNIQUE_PARAMS_VALUE) .put(CodegenConstants.ALLOW_UNICODE_IDENTIFIERS, ALLOW_UNICODE_IDENTIFIERS_VALUE) .put(CodegenConstants.PREPEND_FORM_OR_BODY_PARAMETERS, PREPEND_FORM_OR_BODY_PARAMETERS_VALUE) + .put(PhpSlimServerCodegen.PHPCS_STANDARD, PHPCS_STANDARD_VALUE) .build(); } diff --git a/modules/openapi-generator/src/test/java/org/openapitools/codegen/ruby/RubyClientCodegenTest.java b/modules/openapi-generator/src/test/java/org/openapitools/codegen/ruby/RubyClientCodegenTest.java index a0c5a326ea..2d89be08cf 100644 --- a/modules/openapi-generator/src/test/java/org/openapitools/codegen/ruby/RubyClientCodegenTest.java +++ b/modules/openapi-generator/src/test/java/org/openapitools/codegen/ruby/RubyClientCodegenTest.java @@ -172,7 +172,7 @@ public class RubyClientCodegenTest { @Test(description = "test nullable for properties") - public void nullableTest() { + public void nullablePropertyTest() { final OpenAPI openAPI = new OpenAPIParser().readLocation("src/test/resources/3_0/petstore_oas3_test.yaml", null, new ParseOptions()).getOpenAPI(); final RubyClientCodegen codegen = new RubyClientCodegen(); codegen.setModuleName("OnlinePetstore"); @@ -227,4 +227,48 @@ public class RubyClientCodegenTest { Assert.assertFalse(cp5.isNullable); } + @Test(description = "test nullable for parameters (OAS3)") + public void nullableParameterOAS3Test() { + final OpenAPI openAPI = new OpenAPIParser().readLocation("src/test/resources/3_0/petstore_oas3_test.yaml", null, new ParseOptions()).getOpenAPI(); + final RubyClientCodegen codegen = new RubyClientCodegen(); + codegen.setModuleName("OnlinePetstore"); + final String path = "/pet/{petId}"; + + final Operation p = openAPI.getPaths().get(path).getPost(); + final CodegenOperation op = codegen.fromOperation(path, "post", p, openAPI.getComponents().getSchemas()); + + Assert.assertEquals(op.pathParams.size(), 1); + CodegenParameter pp = op.pathParams.get(0); + Assert.assertTrue(pp.isNullable); + + Assert.assertEquals(op.formParams.size(), 2); + CodegenParameter name = op.formParams.get(0); + Assert.assertFalse(name.isNullable); + CodegenParameter status = op.formParams.get(1); + Assert.assertTrue(status.isNullable); + } + + @Test(description = "test nullable for parameters (OAS2)") + public void nullableParameterOAS2Test() { + final OpenAPI openAPI = new OpenAPIParser().readLocation("src/test/resources/2_0/petstore-nullable.yaml", null, new ParseOptions()).getOpenAPI(); + final RubyClientCodegen codegen = new RubyClientCodegen(); + codegen.setModuleName("OnlinePetstore"); + final String path = "/pet/{petId}"; + + final Operation p = openAPI.getPaths().get(path).getPost(); + final CodegenOperation op = codegen.fromOperation(path, "post", p, openAPI.getComponents().getSchemas()); + + // path parameter x-nullable test + Assert.assertEquals(op.pathParams.size(), 1); + CodegenParameter pp = op.pathParams.get(0); + Assert.assertTrue(pp.isNullable); + + // form parameter x-nullable test + Assert.assertEquals(op.formParams.size(), 2); + CodegenParameter name = op.formParams.get(0); + Assert.assertFalse(name.isNullable); + CodegenParameter status = op.formParams.get(1); + // TODO comment out the following until https://github.com/swagger-api/swagger-parser/issues/820 is solved + //Assert.assertTrue(status.isNullable); + } } diff --git a/modules/openapi-generator/src/test/java/org/openapitools/codegen/slim/PhpSlimServerOptionsTest.java b/modules/openapi-generator/src/test/java/org/openapitools/codegen/slim/PhpSlimServerOptionsTest.java index 25cd43077a..57a87adaf3 100644 --- a/modules/openapi-generator/src/test/java/org/openapitools/codegen/slim/PhpSlimServerOptionsTest.java +++ b/modules/openapi-generator/src/test/java/org/openapitools/codegen/slim/PhpSlimServerOptionsTest.java @@ -63,6 +63,8 @@ public class PhpSlimServerOptionsTest extends AbstractOptionsTest { times = 1; clientCodegen.setSortParamsByRequiredFlag(Boolean.valueOf(PhpSlimServerOptionsProvider.SORT_PARAMS_VALUE)); times = 1; + clientCodegen.setPhpcsStandard(PhpSlimServerOptionsProvider.PHPCS_STANDARD_VALUE); + times = 1; }}; } } diff --git a/modules/openapi-generator/src/test/java/org/openapitools/codegen/utils/StringUtilsTest.java b/modules/openapi-generator/src/test/java/org/openapitools/codegen/utils/StringUtilsTest.java new file mode 100644 index 0000000000..cc920b9c6b --- /dev/null +++ b/modules/openapi-generator/src/test/java/org/openapitools/codegen/utils/StringUtilsTest.java @@ -0,0 +1,34 @@ +package org.openapitools.codegen.utils; + +import org.testng.Assert; +import org.testng.annotations.Test; + +import static org.openapitools.codegen.utils.StringUtils.*; + +public class StringUtilsTest { + // we'll assume that underscore (Twitter elephant bird) works fine + + @Test + public void testCamelize() throws Exception { + Assert.assertEquals(camelize("abcd"), "Abcd"); + Assert.assertEquals(camelize("some-value"), "SomeValue"); + Assert.assertEquals(camelize("some_value"), "SomeValue"); + Assert.assertEquals(camelize("$type"), "$Type"); + + Assert.assertEquals(camelize("abcd", true), "abcd"); + Assert.assertEquals(camelize("some-value", true), "someValue"); + Assert.assertEquals(camelize("some_value", true), "someValue"); + Assert.assertEquals(camelize("Abcd", true), "abcd"); + Assert.assertEquals(camelize("$type", true), "$type"); + + Assert.assertEquals(camelize("123", true), "123"); + Assert.assertEquals(camelize("$123", true), "$123"); + } + + @Test + public void testDashize() { + Assert.assertEquals(dashize("abcd"), "abcd"); + Assert.assertEquals(dashize("some-value"), "some-value"); + Assert.assertEquals(dashize("some_value"), "some-value"); + } +} diff --git a/modules/openapi-generator/src/test/resources/2_0/petstore-nullable.yaml b/modules/openapi-generator/src/test/resources/2_0/petstore-nullable.yaml new file mode 100644 index 0000000000..cff13ed73c --- /dev/null +++ b/modules/openapi-generator/src/test/resources/2_0/petstore-nullable.yaml @@ -0,0 +1,702 @@ +swagger: '2.0' +info: + description: 'This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters.' + version: 1.0.0 + title: OpenAPI Petstore + license: + name: Apache-2.0 + url: 'http://www.apache.org/licenses/LICENSE-2.0.html' +host: petstore.swagger.io +basePath: /v2 +tags: + - name: pet + description: Everything about your Pets + - name: store + description: Access to Petstore orders + - name: user + description: Operations about user +schemes: + - http +paths: + /pet: + post: + tags: + - pet + summary: Add a new pet to the store + description: '' + operationId: addPet + consumes: + - application/json + - application/xml + produces: + - application/xml + - application/json + parameters: + - in: body + name: body + description: Pet object that needs to be added to the store + required: true + schema: + $ref: '#/definitions/Pet' + responses: + '405': + description: Invalid input + security: + - petstore_auth: + - 'write:pets' + - 'read:pets' + put: + tags: + - pet + summary: Update an existing pet + description: '' + operationId: updatePet + consumes: + - application/json + - application/xml + produces: + - application/xml + - application/json + parameters: + - in: body + name: body + description: Pet object that needs to be added to the store + required: true + schema: + $ref: '#/definitions/Pet' + responses: + '400': + description: Invalid ID supplied + '404': + description: Pet not found + '405': + description: Validation exception + security: + - petstore_auth: + - 'write:pets' + - 'read:pets' + /pet/findByStatus: + get: + tags: + - pet + summary: Finds Pets by status + description: Multiple status values can be provided with comma separated strings + operationId: findPetsByStatus + produces: + - application/xml + - application/json + parameters: + - name: status + in: query + description: Status values that need to be considered for filter + required: true + type: array + items: + type: string + enum: + - available + - pending + - sold + default: available + collectionFormat: csv + responses: + '200': + description: successful operation + schema: + type: array + items: + $ref: '#/definitions/Pet' + '400': + description: Invalid status value + security: + - petstore_auth: + - 'write:pets' + - 'read:pets' + /pet/findByTags: + get: + tags: + - pet + summary: Finds Pets by tags + description: 'Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing.' + operationId: findPetsByTags + produces: + - application/xml + - application/json + parameters: + - name: tags + in: query + description: Tags to filter by + required: true + type: array + items: + type: string + collectionFormat: csv + responses: + '200': + description: successful operation + schema: + type: array + items: + $ref: '#/definitions/Pet' + '400': + description: Invalid tag value + security: + - petstore_auth: + - 'write:pets' + - 'read:pets' + deprecated: true + '/pet/{petId}': + get: + tags: + - pet + summary: Find pet by ID + description: Returns a single pet + operationId: getPetById + produces: + - application/xml + - application/json + parameters: + - name: petId + in: path + description: ID of pet to return + required: true + type: integer + format: int64 + responses: + '200': + description: successful operation + schema: + $ref: '#/definitions/Pet' + '400': + description: Invalid ID supplied + '404': + description: Pet not found + security: + - api_key: [] + post: + tags: + - pet + summary: Updates a pet in the store with form data + description: '' + operationId: updatePetWithForm + consumes: + - application/x-www-form-urlencoded + produces: + - application/xml + - application/json + parameters: + - name: petId + in: path + description: ID of pet that needs to be updated + required: true + type: integer + format: int64 + x-nullable: true + - name: name + in: formData + description: Updated name of the pet + required: false + type: string + - name: status + in: formData + description: Updated status of the pet + required: false + type: string + x-nullable: true + responses: + '405': + description: Invalid input + security: + - petstore_auth: + - 'write:pets' + - 'read:pets' + delete: + tags: + - pet + summary: Deletes a pet + description: '' + operationId: deletePet + produces: + - application/xml + - application/json + parameters: + - name: api_key + in: header + required: false + type: string + - name: petId + in: path + description: Pet id to delete + required: true + type: integer + format: int64 + responses: + '400': + description: Invalid pet value + security: + - petstore_auth: + - 'write:pets' + - 'read:pets' + '/pet/{petId}/uploadImage': + post: + tags: + - pet + summary: uploads an image + description: '' + operationId: uploadFile + consumes: + - multipart/form-data + produces: + - application/json + parameters: + - name: petId + in: path + description: ID of pet to update + required: true + type: integer + format: int64 + - name: additionalMetadata + in: formData + description: Additional data to pass to server + required: false + type: string + - name: file + in: formData + description: file to upload + required: false + type: file + responses: + '200': + description: successful operation + schema: + $ref: '#/definitions/ApiResponse' + security: + - petstore_auth: + - 'write:pets' + - 'read:pets' + /store/inventory: + get: + tags: + - store + summary: Returns pet inventories by status + description: Returns a map of status codes to quantities + operationId: getInventory + produces: + - application/json + parameters: [] + responses: + '200': + description: successful operation + schema: + type: object + additionalProperties: + type: integer + format: int32 + security: + - api_key: [] + /store/order: + post: + tags: + - store + summary: Place an order for a pet + description: '' + operationId: placeOrder + produces: + - application/xml + - application/json + parameters: + - in: body + name: body + description: order placed for purchasing the pet + required: true + schema: + $ref: '#/definitions/Order' + responses: + '200': + description: successful operation + schema: + $ref: '#/definitions/Order' + '400': + description: Invalid Order + '/store/order/{orderId}': + get: + tags: + - store + summary: Find purchase order by ID + description: 'For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions' + operationId: getOrderById + produces: + - application/xml + - application/json + parameters: + - name: orderId + in: path + description: ID of pet that needs to be fetched + required: true + type: integer + maximum: 5 + minimum: 1 + format: int64 + responses: + '200': + description: successful operation + schema: + $ref: '#/definitions/Order' + '400': + description: Invalid ID supplied + '404': + description: Order not found + delete: + tags: + - store + summary: Delete purchase order by ID + description: For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors + operationId: deleteOrder + produces: + - application/xml + - application/json + parameters: + - name: orderId + in: path + description: ID of the order that needs to be deleted + required: true + type: string + responses: + '400': + description: Invalid ID supplied + '404': + description: Order not found + /user: + post: + tags: + - user + summary: Create user + description: This can only be done by the logged in user. + operationId: createUser + produces: + - application/xml + - application/json + parameters: + - in: body + name: body + description: Created user object + required: true + schema: + $ref: '#/definitions/User' + responses: + default: + description: successful operation + /user/createWithArray: + post: + tags: + - user + summary: Creates list of users with given input array + description: '' + operationId: createUsersWithArrayInput + produces: + - application/xml + - application/json + parameters: + - in: body + name: body + description: List of user object + required: true + schema: + type: array + items: + $ref: '#/definitions/User' + responses: + default: + description: successful operation + /user/createWithList: + post: + tags: + - user + summary: Creates list of users with given input array + description: '' + operationId: createUsersWithListInput + produces: + - application/xml + - application/json + parameters: + - in: body + name: body + description: List of user object + required: true + schema: + type: array + items: + $ref: '#/definitions/User' + responses: + default: + description: successful operation + /user/login: + get: + tags: + - user + summary: Logs user into the system + description: '' + operationId: loginUser + produces: + - application/xml + - application/json + parameters: + - name: username + in: query + description: The user name for login + required: true + type: string + - name: password + in: query + description: The password for login in clear text + required: true + type: string + responses: + '200': + description: successful operation + schema: + type: string + headers: + X-Rate-Limit: + type: integer + format: int32 + description: calls per hour allowed by the user + X-Expires-After: + type: string + format: date-time + description: date in UTC when toekn expires + '400': + description: Invalid username/password supplied + /user/logout: + get: + tags: + - user + summary: Logs out current logged in user session + description: '' + operationId: logoutUser + produces: + - application/xml + - application/json + parameters: [] + responses: + default: + description: successful operation + '/user/{username}': + get: + tags: + - user + summary: Get user by user name + description: '' + operationId: getUserByName + produces: + - application/xml + - application/json + parameters: + - name: username + in: path + description: 'The name that needs to be fetched. Use user1 for testing.' + required: true + type: string + responses: + '200': + description: successful operation + schema: + $ref: '#/definitions/User' + '400': + description: Invalid username supplied + '404': + description: User not found + put: + tags: + - user + summary: Updated user + description: This can only be done by the logged in user. + operationId: updateUser + produces: + - application/xml + - application/json + parameters: + - name: username + in: path + description: name that need to be deleted + required: true + type: string + - in: body + name: body + description: Updated user object + required: true + schema: + $ref: '#/definitions/User' + responses: + '400': + description: Invalid user supplied + '404': + description: User not found + delete: + tags: + - user + summary: Delete user + description: This can only be done by the logged in user. + operationId: deleteUser + produces: + - application/xml + - application/json + parameters: + - name: username + in: path + description: The name that needs to be deleted + required: true + type: string + responses: + '400': + description: Invalid username supplied + '404': + description: User not found +securityDefinitions: + petstore_auth: + type: oauth2 + authorizationUrl: 'http://petstore.swagger.io/api/oauth/dialog' + flow: implicit + scopes: + 'write:pets': modify pets in your account + 'read:pets': read your pets + api_key: + type: apiKey + name: api_key + in: header +definitions: + Order: + title: Pet Order + description: An order for a pets from the pet store + type: object + properties: + id: + type: integer + format: int64 + petId: + type: integer + format: int64 + quantity: + type: integer + format: int32 + shipDate: + type: string + format: date-time + status: + type: string + description: Order Status + enum: + - placed + - approved + - delivered + complete: + type: boolean + default: false + xml: + name: Order + Category: + title: Pet category + description: A category for a pet + type: object + properties: + id: + type: integer + format: int64 + name: + type: string + xml: + name: Category + User: + title: a User + description: A User who is purchasing from the pet store + type: object + properties: + id: + type: integer + format: int64 + username: + type: string + firstName: + type: string + lastName: + type: string + email: + type: string + password: + type: string + phone: + type: string + userStatus: + type: integer + format: int32 + description: User Status + xml: + name: User + Tag: + title: Pet Tag + description: A tag for a pet + type: object + properties: + id: + type: integer + format: int64 + name: + type: string + xml: + name: Tag + Pet: + title: a Pet + description: A pet for sale in the pet store + type: object + required: + - name + - photoUrls + properties: + id: + type: integer + format: int64 + x-nullable: true + category: + $ref: '#/definitions/Category' + name: + type: string + example: doggie + x-nullable: true + photoUrls: + type: array + xml: + name: photoUrl + wrapped: true + items: + type: string + x-nullable: true + tags: + x-nullable: true + type: array + xml: + name: tag + wrapped: true + items: + $ref: '#/definitions/Tag' + status: + type: string + x-nullable: true + description: pet status in the store + enum: + - available + - pending + - sold + xml: + name: Pet + ApiResponse: + title: An uploaded response + description: Describes the result of uploading an image resource + type: object + properties: + code: + type: integer + format: int32 + type: + type: string + message: + type: string diff --git a/modules/openapi-generator/src/test/resources/3_0/callbacks.yaml b/modules/openapi-generator/src/test/resources/3_0/callbacks.yaml new file mode 100644 index 0000000000..1423867789 --- /dev/null +++ b/modules/openapi-generator/src/test/resources/3_0/callbacks.yaml @@ -0,0 +1,85 @@ +openapi: 3.0.0 +info: + title: Callback Example + version: 1.0.0 +paths: + /streams: + post: + description: subscribes a client to receive out-of-band data + parameters: + - name: callbackUrl + in: query + required: true + description: | + the location where data will be sent. Must be network accessible + by the source server + schema: + type: string + format: uri + example: https://tonys-server.com + responses: + '201': + description: subscription successfully created + content: + application/json: + schema: + description: subscription information + required: + - subscriptionId + properties: + subscriptionId: + description: this unique identifier allows management of the subscription + type: string + example: 2531329f-fb09-4ef7-887e-84e648214436 + callbacks: + onData: + '{$request.query.callbackUrl}/data': + post: + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/NewNotificationData' + responses: + '202': + description: | + Your server implementation should return this HTTP status code + if the data was received successfully + '204': + description: | + Your server should return this HTTP status code if no longer interested + in further updates + delete: + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/DeleteNotificationData' + responses: + '202': + description: | + Your server implementation should return this HTTP status code + if the data was received successfully + '204': + description: | + Your server should return this HTTP status code if no longer interested + in further updates + '{$request.query.callbackUrl}/test': {} + dummy: {} + +components: + schemas: + NewNotificationData: + description: subscription payload + properties: + timestamp: + type: string + format: date-time + userData: + type: string + DeleteNotificationData: + description: subscription payload + properties: + timestamp: + type: string + format: date-time diff --git a/modules/openapi-generator/src/test/resources/3_0/issue_241.yaml b/modules/openapi-generator/src/test/resources/3_0/issue_241.yaml new file mode 100644 index 0000000000..982f18a2d6 --- /dev/null +++ b/modules/openapi-generator/src/test/resources/3_0/issue_241.yaml @@ -0,0 +1,47 @@ +openapi: "3.0.0" +info: + description: "test" + version: "1.0.0" + title: "myTest" + contact: + email: "my@mail.com" +servers: +- url: "http://localhost:9998/v1" +tags: +- name: "users" +paths: + /users/create/{username}: + post: + tags: + - "user" + operationId: "createUser" + parameters: + - name: "username" + in: "path" + required: true + schema: + type: "string" + responses: + 200: + description: "The User just created" + content: + application/json: + schema: + $ref: "#/components/schemas/User" +components: + schemas: + User: + allOf: + - $ref: "#/components/schemas/UserDetail" + - type: "object" + description: "The User" + required: + - "userid" + - "username" + UserDetail: + type: "object" + description: "Detail of a User" + properties: + name: + type: "string" + description: "the name of the user" diff --git a/modules/openapi-generator/src/test/resources/3_0/petstore_oas3_test.yaml b/modules/openapi-generator/src/test/resources/3_0/petstore_oas3_test.yaml index c9c83e09a6..370ae3ee32 100644 --- a/modules/openapi-generator/src/test/resources/3_0/petstore_oas3_test.yaml +++ b/modules/openapi-generator/src/test/resources/3_0/petstore_oas3_test.yaml @@ -181,6 +181,7 @@ paths: schema: type: integer format: int64 + nullable: true responses: '405': description: Invalid input @@ -200,6 +201,7 @@ paths: status: description: Updated status of the pet type: string + nullable: true delete: tags: - pet diff --git a/samples/client/petstore-security-test/java/okhttp-gson/.openapi-generator/VERSION b/samples/client/petstore-security-test/java/okhttp-gson/.openapi-generator/VERSION index 096bf47efe..c791c986fb 100644 --- a/samples/client/petstore-security-test/java/okhttp-gson/.openapi-generator/VERSION +++ b/samples/client/petstore-security-test/java/okhttp-gson/.openapi-generator/VERSION @@ -1 +1 @@ -3.0.0-SNAPSHOT \ No newline at end of file +3.2.3-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore-security-test/java/okhttp-gson/docs/FakeApi.md b/samples/client/petstore-security-test/java/okhttp-gson/docs/FakeApi.md index 362984cef7..a125de0a89 100644 --- a/samples/client/petstore-security-test/java/okhttp-gson/docs/FakeApi.md +++ b/samples/client/petstore-security-test/java/okhttp-gson/docs/FakeApi.md @@ -1,6 +1,6 @@ # FakeApi -All URIs are relative to *petstore.swagger.io *_/ ' \" =end -- \\r\\n \\n \\r/v2 *_/ ' \" =end -- \\r\\n \\n \\r* +All URIs are relative to *http://petstore.swagger.io *_/ ' \" =end -- \\r\\n \\n \\r/v2 *_/ ' \" =end -- \\r\\n \\n \\r* Method | HTTP request | Description ------------- | ------------- | ------------- @@ -13,6 +13,8 @@ Method | HTTP request | Description To test code injection *_/ ' \" =end -- \\r\\n \\n \\r +To test code injection *_/ ' \" =end -- \\r\\n \\n \\r + ### Example ```java // Import classes: @@ -21,7 +23,7 @@ To test code injection *_/ ' \" =end -- \\r\\n \\n \\r FakeApi apiInstance = new FakeApi(); -Object UNKNOWN_BASE_TYPE = new UNKNOWN_BASE_TYPE(); // Object | +UNKNOWN_BASE_TYPE UNKNOWN_BASE_TYPE = new UNKNOWN_BASE_TYPE(); // UNKNOWN_BASE_TYPE | try { apiInstance.testCodeInjectEndRnNR(UNKNOWN_BASE_TYPE); } catch (ApiException e) { @@ -34,7 +36,7 @@ try { Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- - **UNKNOWN_BASE_TYPE** | [**Object**](UNKNOWN_BASE_TYPE.md)| | [optional] + **UNKNOWN_BASE_TYPE** | [**UNKNOWN_BASE_TYPE**](UNKNOWN_BASE_TYPE.md)| | [optional] ### Return type diff --git a/samples/client/petstore-security-test/java/okhttp-gson/src/main/java/org/openapitools/client/ApiClient.java b/samples/client/petstore-security-test/java/okhttp-gson/src/main/java/org/openapitools/client/ApiClient.java index e05519dae1..fb4236a046 100644 --- a/samples/client/petstore-security-test/java/okhttp-gson/src/main/java/org/openapitools/client/ApiClient.java +++ b/samples/client/petstore-security-test/java/okhttp-gson/src/main/java/org/openapitools/client/ApiClient.java @@ -52,7 +52,7 @@ import org.openapitools.client.auth.OAuth; public class ApiClient { - private String basePath = "petstore.swagger.io *_/ ' \" =end -- \\r\\n \\n \\r/v2 *_/ ' \" =end -- \\r\\n \\n \\r"; + private String basePath = "http://petstore.swagger.io *_/ ' \" =end -- \\r\\n \\n \\r/v2 *_/ ' \" =end -- \\r\\n \\n \\r"; private boolean debugging = false; private Map defaultHeaderMap = new HashMap(); private String tempFolderPath = null; @@ -107,7 +107,7 @@ public class ApiClient { /** * Set base path * - * @param basePath Base path of the URL (e.g petstore.swagger.io *_/ ' \" =end -- \\r\\n \\n \\r/v2 *_/ ' \" =end -- \\r\\n \\n \\r + * @param basePath Base path of the URL (e.g http://petstore.swagger.io *_/ ' \" =end -- \\r\\n \\n \\r/v2 *_/ ' \" =end -- \\r\\n \\n \\r * @return An instance of OkHttpClient */ public ApiClient setBasePath(String basePath) { @@ -895,7 +895,7 @@ public class ApiClient { * @param Type * @param response Response * @param returnType Return type - * @throws ApiException If the response has a unsuccessful status code or + * @throws ApiException If the response has an unsuccessful status code or * fail to deserialize the response body * @return Type */ diff --git a/samples/client/petstore-security-test/java/okhttp-gson/src/main/java/org/openapitools/client/JSON.java b/samples/client/petstore-security-test/java/okhttp-gson/src/main/java/org/openapitools/client/JSON.java index c9048812f0..9f14cab573 100644 --- a/samples/client/petstore-security-test/java/okhttp-gson/src/main/java/org/openapitools/client/JSON.java +++ b/samples/client/petstore-security-test/java/okhttp-gson/src/main/java/org/openapitools/client/JSON.java @@ -1,6 +1,6 @@ /* * OpenAPI Petstore *_/ ' \" =end -- \\r\\n \\n \\r - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ *_/ ' \" =end -- + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ *_/ ' \" =end -- * * OpenAPI spec version: 1.0.0 *_/ ' \" =end -- \\r\\n \\n \\r * Contact: something@something.abc *_/ ' \" =end -- \\r\\n \\n \\r @@ -15,21 +15,19 @@ package org.openapitools.client; import com.google.gson.Gson; import com.google.gson.GsonBuilder; +import com.google.gson.JsonElement; import com.google.gson.JsonParseException; import com.google.gson.TypeAdapter; import com.google.gson.internal.bind.util.ISO8601Utils; import com.google.gson.stream.JsonReader; import com.google.gson.stream.JsonWriter; -import com.google.gson.JsonElement; import io.gsonfire.GsonFireBuilder; -import io.gsonfire.TypeSelector; +import okio.ByteString; +import org.openapitools.client.model.*; import org.threeten.bp.LocalDate; import org.threeten.bp.OffsetDateTime; import org.threeten.bp.format.DateTimeFormatter; -import org.openapitools.client.model.*; -import okio.ByteString; - import java.io.IOException; import java.io.StringReader; import java.lang.reflect.Type; @@ -37,8 +35,8 @@ import java.text.DateFormat; import java.text.ParseException; import java.text.ParsePosition; import java.util.Date; +import java.util.Locale; import java.util.Map; -import java.util.HashMap; public class JSON { private Gson gson; @@ -51,8 +49,10 @@ public class JSON { public static GsonBuilder createGson() { GsonFireBuilder fireBuilder = new GsonFireBuilder() + ; - return fireBuilder.createGsonBuilder(); + GsonBuilder builder = fireBuilder.createGsonBuilder(); + return builder; } private static String getDiscriminatorValue(JsonElement readElement, String discriminatorField) { @@ -64,7 +64,7 @@ public class JSON { } private static Class getClassByDiscriminator(Map classByDiscriminatorValue, String discriminatorValue) { - Class clazz = (Class) classByDiscriminatorValue.get(discriminatorValue.toUpperCase()); + Class clazz = (Class) classByDiscriminatorValue.get(discriminatorValue.toUpperCase(Locale.ROOT)); if(null == clazz) { throw new IllegalArgumentException("cannot determine model class of name: <" + discriminatorValue + ">"); } diff --git a/samples/client/petstore-security-test/java/okhttp-gson/src/main/java/org/openapitools/client/api/FakeApi.java b/samples/client/petstore-security-test/java/okhttp-gson/src/main/java/org/openapitools/client/api/FakeApi.java index 2b03a1dbe8..d30884309a 100644 --- a/samples/client/petstore-security-test/java/okhttp-gson/src/main/java/org/openapitools/client/api/FakeApi.java +++ b/samples/client/petstore-security-test/java/okhttp-gson/src/main/java/org/openapitools/client/api/FakeApi.java @@ -27,6 +27,7 @@ import com.google.gson.reflect.TypeToken; import java.io.IOException; +import org.openapitools.client.model.UNKNOWN_BASE_TYPE; import java.lang.reflect.Type; import java.util.ArrayList; @@ -61,7 +62,7 @@ public class FakeApi { * @return Call to execute * @throws ApiException If fail to serialize the request body object */ - public com.squareup.okhttp.Call testCodeInjectEndRnNRCall(Object UNKNOWN_BASE_TYPE, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { + public com.squareup.okhttp.Call testCodeInjectEndRnNRCall(UNKNOWN_BASE_TYPE UNKNOWN_BASE_TYPE, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { Object localVarPostBody = UNKNOWN_BASE_TYPE; // create path and map variables @@ -103,7 +104,7 @@ public class FakeApi { } @SuppressWarnings("rawtypes") - private com.squareup.okhttp.Call testCodeInjectEndRnNRValidateBeforeCall(Object UNKNOWN_BASE_TYPE, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { + private com.squareup.okhttp.Call testCodeInjectEndRnNRValidateBeforeCall(UNKNOWN_BASE_TYPE UNKNOWN_BASE_TYPE, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { com.squareup.okhttp.Call call = testCodeInjectEndRnNRCall(UNKNOWN_BASE_TYPE, progressListener, progressRequestListener); @@ -113,35 +114,35 @@ public class FakeApi { /** * To test code injection *_/ ' \" =end -- \\r\\n \\n \\r - * + * To test code injection *_/ ' \" =end -- \\r\\n \\n \\r * @param UNKNOWN_BASE_TYPE (optional) * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body */ - public void testCodeInjectEndRnNR(Object UNKNOWN_BASE_TYPE) throws ApiException { + public void testCodeInjectEndRnNR(UNKNOWN_BASE_TYPE UNKNOWN_BASE_TYPE) throws ApiException { testCodeInjectEndRnNRWithHttpInfo(UNKNOWN_BASE_TYPE); } /** * To test code injection *_/ ' \" =end -- \\r\\n \\n \\r - * + * To test code injection *_/ ' \" =end -- \\r\\n \\n \\r * @param UNKNOWN_BASE_TYPE (optional) * @return ApiResponse<Void> * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body */ - public ApiResponse testCodeInjectEndRnNRWithHttpInfo(Object UNKNOWN_BASE_TYPE) throws ApiException { + public ApiResponse testCodeInjectEndRnNRWithHttpInfo(UNKNOWN_BASE_TYPE UNKNOWN_BASE_TYPE) throws ApiException { com.squareup.okhttp.Call call = testCodeInjectEndRnNRValidateBeforeCall(UNKNOWN_BASE_TYPE, null, null); return apiClient.execute(call); } /** * To test code injection *_/ ' \" =end -- \\r\\n \\n \\r (asynchronously) - * + * To test code injection *_/ ' \" =end -- \\r\\n \\n \\r * @param UNKNOWN_BASE_TYPE (optional) * @param callback The callback to be executed when the API call finishes * @return The request call * @throws ApiException If fail to process the API call, e.g. serializing the request body object */ - public com.squareup.okhttp.Call testCodeInjectEndRnNRAsync(Object UNKNOWN_BASE_TYPE, final ApiCallback callback) throws ApiException { + public com.squareup.okhttp.Call testCodeInjectEndRnNRAsync(UNKNOWN_BASE_TYPE UNKNOWN_BASE_TYPE, final ApiCallback callback) throws ApiException { ProgressResponseBody.ProgressListener progressListener = null; ProgressRequestBody.ProgressRequestListener progressRequestListener = null; diff --git a/samples/client/petstore-security-test/java/okhttp-gson/src/main/java/org/openapitools/client/model/ModelReturn.java b/samples/client/petstore-security-test/java/okhttp-gson/src/main/java/org/openapitools/client/model/ModelReturn.java index db937fd817..54a34f836a 100644 --- a/samples/client/petstore-security-test/java/okhttp-gson/src/main/java/org/openapitools/client/model/ModelReturn.java +++ b/samples/client/petstore-security-test/java/okhttp-gson/src/main/java/org/openapitools/client/model/ModelReturn.java @@ -1,6 +1,6 @@ /* * OpenAPI Petstore *_/ ' \" =end -- \\r\\n \\n \\r - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ *_/ ' \" =end -- + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ *_/ ' \" =end -- * * OpenAPI spec version: 1.0.0 *_/ ' \" =end -- \\r\\n \\n \\r * Contact: something@something.abc *_/ ' \" =end -- \\r\\n \\n \\r @@ -13,16 +13,11 @@ package org.openapitools.client.model; -import java.util.Objects; -import java.util.Arrays; -import com.google.gson.TypeAdapter; -import com.google.gson.annotations.JsonAdapter; import com.google.gson.annotations.SerializedName; -import com.google.gson.stream.JsonReader; -import com.google.gson.stream.JsonWriter; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; -import java.io.IOException; + +import java.util.Objects; /** * Model for testing reserved words *_/ ' \" =end -- \\r\\n \\n \\r @@ -30,7 +25,8 @@ import java.io.IOException; @ApiModel(description = "Model for testing reserved words *_/ ' \" =end -- \\r\\n \\n \\r") public class ModelReturn { - @SerializedName("return") + public static final String SERIALIZED_NAME_RETURN = "return"; + @SerializedName(SERIALIZED_NAME_RETURN) private Integer _return = null; public ModelReturn _return(Integer _return) { @@ -74,7 +70,7 @@ public class ModelReturn { public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class ModelReturn {\n"); - + sb.append(" _return: ").append(toIndentedString(_return)).append("\n"); sb.append("}"); return sb.toString(); diff --git a/samples/client/petstore/elm/.openapi-generator/VERSION b/samples/client/petstore/elm/.openapi-generator/VERSION index 4395ff5923..c791c986fb 100644 --- a/samples/client/petstore/elm/.openapi-generator/VERSION +++ b/samples/client/petstore/elm/.openapi-generator/VERSION @@ -1 +1 @@ -3.2.0-SNAPSHOT \ No newline at end of file +3.2.3-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/elm/src/Data/ApiResponse.elm b/samples/client/petstore/elm/src/Data/ApiResponse.elm index ce05291754..c740028308 100644 --- a/samples/client/petstore/elm/src/Data/ApiResponse.elm +++ b/samples/client/petstore/elm/src/Data/ApiResponse.elm @@ -44,4 +44,3 @@ apiResponseEncoder model = , ( "message", withDefault Encode.null (map Encode.string model.message) ) ] - diff --git a/samples/client/petstore/elm/src/Data/Category.elm b/samples/client/petstore/elm/src/Data/Category.elm index 8cac70ea45..b2baddd929 100644 --- a/samples/client/petstore/elm/src/Data/Category.elm +++ b/samples/client/petstore/elm/src/Data/Category.elm @@ -41,4 +41,3 @@ categoryEncoder model = , ( "name", withDefault Encode.null (map Encode.string model.name) ) ] - diff --git a/samples/client/petstore/elm/src/Data/Order_.elm b/samples/client/petstore/elm/src/Data/Order_.elm index c343084f39..58559b874b 100644 --- a/samples/client/petstore/elm/src/Data/Order_.elm +++ b/samples/client/petstore/elm/src/Data/Order_.elm @@ -62,7 +62,6 @@ orderEncoder model = ] - statusDecoder : Decoder Status statusDecoder = Decode.string diff --git a/samples/client/petstore/elm/src/Data/Pet.elm b/samples/client/petstore/elm/src/Data/Pet.elm index 7f15ea4416..cdb4296712 100644 --- a/samples/client/petstore/elm/src/Data/Pet.elm +++ b/samples/client/petstore/elm/src/Data/Pet.elm @@ -63,7 +63,6 @@ petEncoder model = ] - statusDecoder : Decoder Status statusDecoder = Decode.string diff --git a/samples/client/petstore/elm/src/Data/Tag.elm b/samples/client/petstore/elm/src/Data/Tag.elm index 74f6de1828..79d0fa2da2 100644 --- a/samples/client/petstore/elm/src/Data/Tag.elm +++ b/samples/client/petstore/elm/src/Data/Tag.elm @@ -41,4 +41,3 @@ tagEncoder model = , ( "name", withDefault Encode.null (map Encode.string model.name) ) ] - diff --git a/samples/client/petstore/elm/src/Data/User.elm b/samples/client/petstore/elm/src/Data/User.elm index 851f3a5102..657f6fb660 100644 --- a/samples/client/petstore/elm/src/Data/User.elm +++ b/samples/client/petstore/elm/src/Data/User.elm @@ -59,4 +59,3 @@ userEncoder model = , ( "userStatus", withDefault Encode.null (map Encode.int model.userStatus) ) ] - diff --git a/samples/client/petstore/java/feign/build.gradle b/samples/client/petstore/java/feign/build.gradle index b4d7da7926..e2126b1243 100644 --- a/samples/client/petstore/java/feign/build.gradle +++ b/samples/client/petstore/java/feign/build.gradle @@ -94,7 +94,7 @@ if(hasProperty('target') && target == 'android') { } ext { - swagger_annotations_version = "1.5.9" + swagger_annotations_version = "1.5.21" jackson_version = "2.8.7" threepane_version = "2.6.4" feign_version = "9.4.0" diff --git a/samples/client/petstore/java/feign/build.sbt b/samples/client/petstore/java/feign/build.sbt index 0b09ff26bd..b387ad56e6 100644 --- a/samples/client/petstore/java/feign/build.sbt +++ b/samples/client/petstore/java/feign/build.sbt @@ -9,7 +9,7 @@ lazy val root = (project in file(".")). publishArtifact in (Compile, packageDoc) := false, resolvers += Resolver.mavenLocal, libraryDependencies ++= Seq( - "io.swagger" % "swagger-annotations" % "1.5.9" % "compile", + "io.swagger" % "swagger-annotations" % "1.5.21" % "compile", "io.github.openfeign" % "feign-core" % "9.4.0" % "compile", "io.github.openfeign" % "feign-jackson" % "9.4.0" % "compile", "io.github.openfeign" % "feign-slf4j" % "9.4.0" % "compile", diff --git a/samples/client/petstore/java/feign/pom.xml b/samples/client/petstore/java/feign/pom.xml index ce837265ab..58b7d4d7e0 100644 --- a/samples/client/petstore/java/feign/pom.xml +++ b/samples/client/petstore/java/feign/pom.xml @@ -114,8 +114,7 @@ - - src/main/java + src/main/java @@ -127,8 +126,7 @@ - - src/test/java + src/test/java @@ -191,7 +189,7 @@ io.swagger swagger-annotations - ${swagger-core-version} + ${swagger-annotations-version} @@ -268,11 +266,11 @@ 1.7 ${java.version} ${java.version} - 1.5.18 + 1.5.21 9.4.0 2.1.0 2.8.9 - 2.6.4 + 2.6.4 4.12 1.0.0 1.0.1 diff --git a/samples/client/petstore/java/google-api-client/build.gradle b/samples/client/petstore/java/google-api-client/build.gradle index d66603375a..97de036a9c 100644 --- a/samples/client/petstore/java/google-api-client/build.gradle +++ b/samples/client/petstore/java/google-api-client/build.gradle @@ -94,7 +94,7 @@ if(hasProperty('target') && target == 'android') { } ext { - swagger_annotations_version = "1.5.17" + swagger_annotations_version = "1.5.21" jackson_version = "2.8.9" google_api_client_version = "1.23.0" jersey_common_version = "2.25.1" diff --git a/samples/client/petstore/java/google-api-client/build.sbt b/samples/client/petstore/java/google-api-client/build.sbt index 92a0aabedd..7052571b29 100644 --- a/samples/client/petstore/java/google-api-client/build.sbt +++ b/samples/client/petstore/java/google-api-client/build.sbt @@ -9,7 +9,7 @@ lazy val root = (project in file(".")). publishArtifact in (Compile, packageDoc) := false, resolvers += Resolver.mavenLocal, libraryDependencies ++= Seq( - "io.swagger" % "swagger-annotations" % "1.5.17", + "io.swagger" % "swagger-annotations" % "1.5.21", "com.google.api-client" % "google-api-client" % "1.23.0", "org.glassfish.jersey.core" % "jersey-common" % "2.25.1", "com.fasterxml.jackson.core" % "jackson-core" % "2.8.9" % "compile", diff --git a/samples/client/petstore/java/google-api-client/pom.xml b/samples/client/petstore/java/google-api-client/pom.xml index 02d4066015..af558ebb15 100644 --- a/samples/client/petstore/java/google-api-client/pom.xml +++ b/samples/client/petstore/java/google-api-client/pom.xml @@ -114,8 +114,7 @@ - - src/main/java + src/main/java @@ -127,8 +126,7 @@ - - src/test/java + src/test/java @@ -246,11 +244,11 @@ UTF-8 - 1.5.17 + 1.5.21 1.23.0 2.25.1 2.8.9 - 2.6.4 + 2.6.4 1.0.0 4.12 diff --git a/samples/client/petstore/java/jersey1/pom.xml b/samples/client/petstore/java/jersey1/pom.xml index 397958485b..c2ccfcede3 100644 --- a/samples/client/petstore/java/jersey1/pom.xml +++ b/samples/client/petstore/java/jersey1/pom.xml @@ -114,8 +114,7 @@ - - src/main/java + src/main/java @@ -127,8 +126,7 @@ - - src/test/java + src/test/java @@ -257,7 +255,7 @@ UTF-8 - 1.5.17 + 1.5.21 1.19.4 2.6.4 1.0.0 diff --git a/samples/client/petstore/java/jersey2-java6/build.sbt b/samples/client/petstore/java/jersey2-java6/build.sbt index 3d85a70e1d..ea742941dc 100644 --- a/samples/client/petstore/java/jersey2-java6/build.sbt +++ b/samples/client/petstore/java/jersey2-java6/build.sbt @@ -9,7 +9,7 @@ lazy val root = (project in file(".")). publishArtifact in (Compile, packageDoc) := false, resolvers += Resolver.mavenLocal, libraryDependencies ++= Seq( - "io.swagger" % "swagger-annotations" % "1.5.20", + "io.swagger" % "swagger-annotations" % "1.5.21", "org.glassfish.jersey.core" % "jersey-client" % "2.6", "org.glassfish.jersey.media" % "jersey-media-multipart" % "2.6", "org.glassfish.jersey.media" % "jersey-media-json-jackson" % "2.6", diff --git a/samples/client/petstore/java/jersey2-java6/pom.xml b/samples/client/petstore/java/jersey2-java6/pom.xml index 46ee931b3d..eea08b8d53 100644 --- a/samples/client/petstore/java/jersey2-java6/pom.xml +++ b/samples/client/petstore/java/jersey2-java6/pom.xml @@ -114,8 +114,7 @@ - - src/main/java + src/main/java @@ -127,8 +126,7 @@ - - src/test/java + src/test/java @@ -200,7 +198,7 @@ io.swagger swagger-annotations - ${swagger-core-version} + ${swagger-annotations-version} @@ -267,7 +265,7 @@ UTF-8 - 1.5.20 + 1.5.21 2.6 2.5 3.6 diff --git a/samples/client/petstore/java/jersey2-java8/build.gradle b/samples/client/petstore/java/jersey2-java8/build.gradle index d271017ae9..d2daa9fa14 100644 --- a/samples/client/petstore/java/jersey2-java8/build.gradle +++ b/samples/client/petstore/java/jersey2-java8/build.gradle @@ -93,7 +93,7 @@ if(hasProperty('target') && target == 'android') { } ext { - swagger_annotations_version = "1.5.20" + swagger_annotations_version = "1.5.21" jackson_version = "2.9.6" jersey_version = "2.27" junit_version = "4.12" diff --git a/samples/client/petstore/java/jersey2-java8/build.sbt b/samples/client/petstore/java/jersey2-java8/build.sbt index 1bd1f63a7d..8edfce668a 100644 --- a/samples/client/petstore/java/jersey2-java8/build.sbt +++ b/samples/client/petstore/java/jersey2-java8/build.sbt @@ -9,7 +9,7 @@ lazy val root = (project in file(".")). publishArtifact in (Compile, packageDoc) := false, resolvers += Resolver.mavenLocal, libraryDependencies ++= Seq( - "io.swagger" % "swagger-annotations" % "1.5.20", + "io.swagger" % "swagger-annotations" % "1.5.21", "org.glassfish.jersey.core" % "jersey-client" % "2.25.1", "org.glassfish.jersey.media" % "jersey-media-multipart" % "2.25.1", "org.glassfish.jersey.media" % "jersey-media-json-jackson" % "2.25.1", diff --git a/samples/client/petstore/java/jersey2-java8/pom.xml b/samples/client/petstore/java/jersey2-java8/pom.xml index c6317e79ee..70130e62c2 100644 --- a/samples/client/petstore/java/jersey2-java8/pom.xml +++ b/samples/client/petstore/java/jersey2-java8/pom.xml @@ -114,8 +114,7 @@ - - src/main/java + src/main/java @@ -127,8 +126,7 @@ - - src/test/java + src/test/java @@ -200,7 +198,7 @@ io.swagger swagger-annotations - ${swagger-core-version} + ${swagger-annotations-version} @@ -251,7 +249,7 @@ UTF-8 - 1.5.20 + 1.5.21 2.27 2.8.9 1.0.0 diff --git a/samples/client/petstore/java/jersey2/build.gradle b/samples/client/petstore/java/jersey2/build.gradle index f1a401ef53..84f8976c2c 100644 --- a/samples/client/petstore/java/jersey2/build.gradle +++ b/samples/client/petstore/java/jersey2/build.gradle @@ -93,7 +93,7 @@ if(hasProperty('target') && target == 'android') { } ext { - swagger_annotations_version = "1.5.20" + swagger_annotations_version = "1.5.21" jackson_version = "2.9.6" jersey_version = "2.27" junit_version = "4.12" diff --git a/samples/client/petstore/java/jersey2/build.sbt b/samples/client/petstore/java/jersey2/build.sbt index 578112888e..e3f30385ef 100644 --- a/samples/client/petstore/java/jersey2/build.sbt +++ b/samples/client/petstore/java/jersey2/build.sbt @@ -9,7 +9,7 @@ lazy val root = (project in file(".")). publishArtifact in (Compile, packageDoc) := false, resolvers += Resolver.mavenLocal, libraryDependencies ++= Seq( - "io.swagger" % "swagger-annotations" % "1.5.20", + "io.swagger" % "swagger-annotations" % "1.5.21", "org.glassfish.jersey.core" % "jersey-client" % "2.25.1", "org.glassfish.jersey.media" % "jersey-media-multipart" % "2.25.1", "org.glassfish.jersey.media" % "jersey-media-json-jackson" % "2.25.1", diff --git a/samples/client/petstore/java/jersey2/pom.xml b/samples/client/petstore/java/jersey2/pom.xml index ffc94e97de..94391c4544 100644 --- a/samples/client/petstore/java/jersey2/pom.xml +++ b/samples/client/petstore/java/jersey2/pom.xml @@ -114,8 +114,7 @@ - - src/main/java + src/main/java @@ -127,8 +126,7 @@ - - src/test/java + src/test/java @@ -200,7 +198,7 @@ io.swagger swagger-annotations - ${swagger-core-version} + ${swagger-annotations-version} @@ -257,7 +255,7 @@ UTF-8 - 1.5.20 + 1.5.21 2.27 2.8.9 2.6.4 diff --git a/samples/client/petstore/java/rest-assured/build.gradle b/samples/client/petstore/java/rest-assured/build.gradle index 8afb2af188..b9eb1e177e 100644 --- a/samples/client/petstore/java/rest-assured/build.gradle +++ b/samples/client/petstore/java/rest-assured/build.gradle @@ -94,7 +94,7 @@ if(hasProperty('target') && target == 'android') { } ext { - swagger_annotations_version = "1.5.15" + swagger_annotations_version = "1.5.21" rest_assured_version = "3.1.0" junit_version = "4.12" gson_version = "2.6.1" diff --git a/samples/client/petstore/java/rest-assured/build.sbt b/samples/client/petstore/java/rest-assured/build.sbt index a57bc62b67..eb61e74a89 100644 --- a/samples/client/petstore/java/rest-assured/build.sbt +++ b/samples/client/petstore/java/rest-assured/build.sbt @@ -9,7 +9,7 @@ lazy val root = (project in file(".")). publishArtifact in (Compile, packageDoc) := false, resolvers += Resolver.mavenLocal, libraryDependencies ++= Seq( - "io.swagger" % "swagger-annotations" % "1.5.15", + "io.swagger" % "swagger-annotations" % "1.5.21", "io.rest-assured" % "scala-support" % "3.1.0", "com.google.code.gson" % "gson" % "2.6.1", "io.gsonfire" % "gson-fire" % "1.8.2" % "compile", diff --git a/samples/client/petstore/java/rest-assured/pom.xml b/samples/client/petstore/java/rest-assured/pom.xml index 4ed742e465..ed7f35ac02 100644 --- a/samples/client/petstore/java/rest-assured/pom.xml +++ b/samples/client/petstore/java/rest-assured/pom.xml @@ -113,8 +113,7 @@ - - src/main/java + src/main/java @@ -126,8 +125,7 @@ - - src/test/java + src/test/java @@ -199,7 +197,7 @@ io.swagger swagger-annotations - ${swagger-core-version} + ${swagger-annotations-version} io.rest-assured @@ -236,7 +234,7 @@ UTF-8 - 1.5.15 + 1.5.21 3.1.0 2.6.1 1.8.2 diff --git a/samples/client/petstore/java/resteasy/pom.xml b/samples/client/petstore/java/resteasy/pom.xml index ffe295db73..de50c2bb94 100644 --- a/samples/client/petstore/java/resteasy/pom.xml +++ b/samples/client/petstore/java/resteasy/pom.xml @@ -95,8 +95,7 @@ - - src/main/java + src/main/java @@ -108,8 +107,7 @@ - - src/test/java + src/test/java @@ -143,7 +141,7 @@ io.swagger swagger-annotations - ${swagger-core-version} + ${swagger-annotations-version} @@ -215,7 +213,7 @@ UTF-8 - 1.5.18 + 1.5.21 3.1.3.Final 2.8.6 2.6.4 diff --git a/samples/client/petstore/java/resttemplate-withXml/build.gradle b/samples/client/petstore/java/resttemplate-withXml/build.gradle index 1d6787e3db..6448e545d5 100644 --- a/samples/client/petstore/java/resttemplate-withXml/build.gradle +++ b/samples/client/petstore/java/resttemplate-withXml/build.gradle @@ -94,7 +94,7 @@ if(hasProperty('target') && target == 'android') { } ext { - swagger_annotations_version = "1.5.17" + swagger_annotations_version = "1.5.21" jackson_version = "2.8.9" spring_web_version = "4.3.9.RELEASE" jodatime_version = "2.9.9" diff --git a/samples/client/petstore/java/resttemplate-withXml/pom.xml b/samples/client/petstore/java/resttemplate-withXml/pom.xml index e8c5b512c7..74cc0d02f0 100644 --- a/samples/client/petstore/java/resttemplate-withXml/pom.xml +++ b/samples/client/petstore/java/resttemplate-withXml/pom.xml @@ -114,8 +114,7 @@ - - src/main/java + src/main/java @@ -127,8 +126,7 @@ - - src/test/java + src/test/java @@ -255,7 +253,7 @@ UTF-8 - 1.5.17 + 1.5.21 4.3.9.RELEASE 2.8.9 2.6.4 diff --git a/samples/client/petstore/java/resttemplate/build.gradle b/samples/client/petstore/java/resttemplate/build.gradle index a6de57bd8c..1732501800 100644 --- a/samples/client/petstore/java/resttemplate/build.gradle +++ b/samples/client/petstore/java/resttemplate/build.gradle @@ -94,7 +94,7 @@ if(hasProperty('target') && target == 'android') { } ext { - swagger_annotations_version = "1.5.17" + swagger_annotations_version = "1.5.21" jackson_version = "2.8.9" spring_web_version = "4.3.9.RELEASE" jodatime_version = "2.9.9" diff --git a/samples/client/petstore/java/resttemplate/pom.xml b/samples/client/petstore/java/resttemplate/pom.xml index 9869bad196..d3a526022d 100644 --- a/samples/client/petstore/java/resttemplate/pom.xml +++ b/samples/client/petstore/java/resttemplate/pom.xml @@ -114,8 +114,7 @@ - - src/main/java + src/main/java @@ -127,8 +126,7 @@ - - src/test/java + src/test/java @@ -247,7 +245,7 @@ UTF-8 - 1.5.17 + 1.5.21 4.3.9.RELEASE 2.8.9 2.6.4 diff --git a/samples/client/petstore/java/retrofit/build.gradle b/samples/client/petstore/java/retrofit/build.gradle index fb1371f1f3..124982e859 100644 --- a/samples/client/petstore/java/retrofit/build.gradle +++ b/samples/client/petstore/java/retrofit/build.gradle @@ -97,7 +97,7 @@ ext { okhttp_version = "2.7.5" oltu_version = "1.0.1" retrofit_version = "1.9.0" - swagger_annotations_version = "1.5.8" + swagger_annotations_version = "1.5.21" junit_version = "4.12" jodatime_version = "2.9.3" } diff --git a/samples/client/petstore/java/retrofit/build.sbt b/samples/client/petstore/java/retrofit/build.sbt index 44fb828418..cedb083de9 100644 --- a/samples/client/petstore/java/retrofit/build.sbt +++ b/samples/client/petstore/java/retrofit/build.sbt @@ -11,7 +11,7 @@ lazy val root = (project in file(".")). libraryDependencies ++= Seq( "com.squareup.okhttp" % "okhttp" % "2.7.5" % "compile", "com.squareup.retrofit" % "retrofit" % "1.9.0" % "compile", - "io.swagger" % "swagger-annotations" % "1.5.8" % "compile", + "io.swagger" % "swagger-annotations" % "1.5.21" % "compile", "org.apache.oltu.oauth2" % "org.apache.oltu.oauth2.client" % "1.0.1" % "compile", "joda-time" % "joda-time" % "2.9.3" % "compile", "junit" % "junit" % "4.12" % "test", diff --git a/samples/client/petstore/java/retrofit/pom.xml b/samples/client/petstore/java/retrofit/pom.xml index 1373ec6264..3f6dfee60f 100644 --- a/samples/client/petstore/java/retrofit/pom.xml +++ b/samples/client/petstore/java/retrofit/pom.xml @@ -114,8 +114,7 @@ - - src/main/java + src/main/java @@ -127,8 +126,7 @@ - - src/test/java + src/test/java @@ -200,7 +198,7 @@ io.swagger swagger-annotations - ${swagger-core-version} + ${swagger-annotations-version} com.squareup.retrofit @@ -222,8 +220,6 @@ joda-time ${jodatime-version} - - junit @@ -234,7 +230,7 @@ UTF-8 - 1.5.18 + 1.5.21 1.9.0 2.7.5 2.9.9 diff --git a/samples/client/petstore/java/retrofit2-play24/build.gradle b/samples/client/petstore/java/retrofit2-play24/build.gradle index 714331ea31..667a9b283e 100644 --- a/samples/client/petstore/java/retrofit2-play24/build.gradle +++ b/samples/client/petstore/java/retrofit2-play24/build.gradle @@ -98,7 +98,7 @@ ext { retrofit_version = "2.3.0" jackson_version = "2.6.6" play_version = "2.4.11" - swagger_annotations_version = "1.5.17" + swagger_annotations_version = "1.5.21" junit_version = "4.12" json_fire_version = "1.8.0" } diff --git a/samples/client/petstore/java/retrofit2-play24/build.sbt b/samples/client/petstore/java/retrofit2-play24/build.sbt index d754ac539e..ef9a3ad810 100644 --- a/samples/client/petstore/java/retrofit2-play24/build.sbt +++ b/samples/client/petstore/java/retrofit2-play24/build.sbt @@ -16,7 +16,7 @@ lazy val root = (project in file(".")). "com.fasterxml.jackson.core" % "jackson-annotations" % "2.6.6" % "compile", "com.fasterxml.jackson.core" % "jackson-databind" % "2.6.6" % "compile", "com.squareup.retrofit2" % "converter-jackson" % "2.3.0" % "compile", - "io.swagger" % "swagger-annotations" % "1.5.17" % "compile", + "io.swagger" % "swagger-annotations" % "1.5.21" % "compile", "org.apache.oltu.oauth2" % "org.apache.oltu.oauth2.client" % "1.0.1" % "compile", "io.gsonfire" % "gson-fire" % "1.8.0" % "compile", "junit" % "junit" % "4.12" % "test", diff --git a/samples/client/petstore/java/retrofit2-play24/pom.xml b/samples/client/petstore/java/retrofit2-play24/pom.xml index 305b7e5e34..e73282392c 100644 --- a/samples/client/petstore/java/retrofit2-play24/pom.xml +++ b/samples/client/petstore/java/retrofit2-play24/pom.xml @@ -114,8 +114,7 @@ - - src/main/java + src/main/java @@ -127,8 +126,7 @@ - - src/test/java + src/test/java @@ -191,7 +189,7 @@ io.swagger swagger-annotations - ${swagger-core-version} + ${swagger-annotations-version} com.squareup.retrofit2 @@ -224,7 +222,6 @@ gson-fire ${gson-fire-version} - com.squareup.retrofit2 @@ -256,8 +253,6 @@ play-java-ws_2.11 ${play-version} - - junit @@ -272,9 +267,9 @@ ${java.version} ${java.version} 1.8.0 - 1.5.18 - 2.6.6 - 2.4.11 + 1.5.21 + 2.6.6 + 2.4.11 2.3.0 1.0.1 4.12 diff --git a/samples/client/petstore/java/retrofit2-play25/build.gradle b/samples/client/petstore/java/retrofit2-play25/build.gradle index 8197e91599..201ad458bb 100644 --- a/samples/client/petstore/java/retrofit2-play25/build.gradle +++ b/samples/client/petstore/java/retrofit2-play25/build.gradle @@ -98,7 +98,7 @@ ext { retrofit_version = "2.3.0" jackson_version = "2.7.8" play_version = "2.5.14" - swagger_annotations_version = "1.5.17" + swagger_annotations_version = "1.5.21" junit_version = "4.12" threetenbp_version = "1.3.5" json_fire_version = "1.8.0" diff --git a/samples/client/petstore/java/retrofit2-play25/build.sbt b/samples/client/petstore/java/retrofit2-play25/build.sbt index 49e5cc4d0e..1f17d6bfc9 100644 --- a/samples/client/petstore/java/retrofit2-play25/build.sbt +++ b/samples/client/petstore/java/retrofit2-play25/build.sbt @@ -16,7 +16,7 @@ lazy val root = (project in file(".")). "com.fasterxml.jackson.core" % "jackson-annotations" % "2.7.8" % "compile", "com.fasterxml.jackson.core" % "jackson-databind" % "2.7.8" % "compile", "com.squareup.retrofit2" % "converter-jackson" % "2.3.0" % "compile", - "io.swagger" % "swagger-annotations" % "1.5.17" % "compile", + "io.swagger" % "swagger-annotations" % "1.5.21" % "compile", "org.apache.oltu.oauth2" % "org.apache.oltu.oauth2.client" % "1.0.1" % "compile", "org.threeten" % "threetenbp" % "1.3.5" % "compile", "io.gsonfire" % "gson-fire" % "1.8.0" % "compile", diff --git a/samples/client/petstore/java/retrofit2-play25/pom.xml b/samples/client/petstore/java/retrofit2-play25/pom.xml index 9181b7d41b..4051b0036d 100644 --- a/samples/client/petstore/java/retrofit2-play25/pom.xml +++ b/samples/client/petstore/java/retrofit2-play25/pom.xml @@ -114,8 +114,7 @@ - - src/main/java + src/main/java @@ -127,8 +126,7 @@ - - src/test/java + src/test/java @@ -191,7 +189,7 @@ io.swagger swagger-annotations - ${swagger-core-version} + ${swagger-annotations-version} com.squareup.retrofit2 @@ -229,7 +227,6 @@ threetenbp ${threetenbp-version} - com.squareup.retrofit2 @@ -261,8 +258,6 @@ play-java-ws_2.11 ${play-version} - - junit @@ -277,11 +272,11 @@ ${java.version} ${java.version} 1.8.0 - 1.5.18 - 2.7.8 - 2.5.15 + 1.5.21 + 2.7.8 + 2.5.15 2.3.0 - 1.3.5 + 1.3.5 1.0.1 4.12 diff --git a/samples/client/petstore/java/retrofit2-play26/.gitignore b/samples/client/petstore/java/retrofit2-play26/.gitignore new file mode 100644 index 0000000000..a530464afa --- /dev/null +++ b/samples/client/petstore/java/retrofit2-play26/.gitignore @@ -0,0 +1,21 @@ +*.class + +# Mobile Tools for Java (J2ME) +.mtj.tmp/ + +# Package Files # +*.jar +*.war +*.ear + +# exclude jar for gradle wrapper +!gradle/wrapper/*.jar + +# virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml +hs_err_pid* + +# build files +**/target +target +.gradle +build diff --git a/samples/client/petstore/java/retrofit2-play26/.openapi-generator-ignore b/samples/client/petstore/java/retrofit2-play26/.openapi-generator-ignore new file mode 100644 index 0000000000..7484ee590a --- /dev/null +++ b/samples/client/petstore/java/retrofit2-play26/.openapi-generator-ignore @@ -0,0 +1,23 @@ +# OpenAPI Generator Ignore +# Generated by openapi-generator https://github.com/openapitools/openapi-generator + +# Use this file to prevent files from being overwritten by the generator. +# The patterns follow closely to .gitignore or .dockerignore. + +# As an example, the C# client generator defines ApiClient.cs. +# You can make changes and tell OpenAPI Generator to ignore just this file by uncommenting the following line: +#ApiClient.cs + +# You can match any string of characters against a directory, file or extension with a single asterisk (*): +#foo/*/qux +# The above matches foo/bar/qux and foo/baz/qux, but not foo/bar/baz/qux + +# You can recursively match patterns against a directory, file or extension with a double asterisk (**): +#foo/**/qux +# This matches foo/bar/qux, foo/baz/qux, and foo/bar/baz/qux + +# You can also negate patterns with an exclamation (!). +# For example, you can ignore all files in a docs folder with the file extension .md: +#docs/*.md +# Then explicitly reverse the ignore rule for a single file: +#!docs/README.md diff --git a/samples/client/petstore/java/retrofit2-play26/.openapi-generator/VERSION b/samples/client/petstore/java/retrofit2-play26/.openapi-generator/VERSION new file mode 100644 index 0000000000..c791c986fb --- /dev/null +++ b/samples/client/petstore/java/retrofit2-play26/.openapi-generator/VERSION @@ -0,0 +1 @@ +3.2.3-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/java/retrofit2-play26/.travis.yml b/samples/client/petstore/java/retrofit2-play26/.travis.yml new file mode 100644 index 0000000000..80a7f2fc66 --- /dev/null +++ b/samples/client/petstore/java/retrofit2-play26/.travis.yml @@ -0,0 +1,17 @@ +# +# Generated by: https://openapi-generator.tech +# +language: java +jdk: + - oraclejdk8 + - oraclejdk7 +before_install: + # ensure gradlew has proper permission + - chmod a+x ./gradlew +script: + # test using maven + - mvn test + # uncomment below to test using gradle + # - gradle test + # uncomment below to test using sbt + # - sbt test diff --git a/samples/client/petstore/java/retrofit2-play26/README.md b/samples/client/petstore/java/retrofit2-play26/README.md new file mode 100644 index 0000000000..b15898583f --- /dev/null +++ b/samples/client/petstore/java/retrofit2-play26/README.md @@ -0,0 +1,39 @@ +# petstore-java-client-retrofit2-play26 + +## Requirements + +Building the API client library requires [Maven](https://maven.apache.org/) to be installed. + +## Installation & Usage + +To install the API client library to your local Maven repository, simply execute: + +```shell +mvn install +``` + +To deploy it to a remote Maven repository instead, configure the settings of the repository and execute: + +```shell +mvn deploy +``` + +Refer to the [official documentation](https://maven.apache.org/plugins/maven-deploy-plugin/usage.html) for more information. + +After the client library is installed/deployed, you can use it in your Maven project by adding the following to your *pom.xml*: + +```xml + + org.openapitools + petstore-java-client-retrofit2-play26 + 1.0.0 + compile + + +``` + +## Author + + + + diff --git a/samples/client/petstore/java/retrofit2-play26/build.gradle b/samples/client/petstore/java/retrofit2-play26/build.gradle new file mode 100644 index 0000000000..dd9ded7db0 --- /dev/null +++ b/samples/client/petstore/java/retrofit2-play26/build.gradle @@ -0,0 +1,125 @@ +apply plugin: 'idea' +apply plugin: 'eclipse' + +group = 'org.openapitools' +version = '1.0.0' + +buildscript { + repositories { + 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 { + sourceCompatibility JavaVersion.VERSION_1_8 + targetCompatibility JavaVersion.VERSION_1_8 + } + + // 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' + + sourceCompatibility = JavaVersion.VERSION_1_8 + targetCompatibility = JavaVersion.VERSION_1_8 + + install { + repositories.mavenInstaller { + pom.artifactId = 'petstore-java-client-retrofit2-play26' + } + } + + task execute(type:JavaExec) { + main = System.getProperty('mainClass') + classpath = sourceSets.main.runtimeClasspath + } +} + +ext { + oltu_version = "1.0.1" + retrofit_version = "2.3.0" + jackson_version = "2.8.10" + play_version = "2.6.7" + swagger_annotations_version = "1.5.21" + junit_version = "4.12" + threetenbp_version = "1.3.5" + json_fire_version = "1.8.0" +} + +dependencies { + compile "com.squareup.retrofit2:retrofit:$retrofit_version" + compile "com.squareup.retrofit2:converter-scalars:$retrofit_version" + compile "com.squareup.retrofit2:converter-gson:$retrofit_version" + compile "io.swagger:swagger-annotations:$swagger_annotations_version" + compile ("org.apache.oltu.oauth2:org.apache.oltu.oauth2.client:$oltu_version"){ + exclude group:'org.apache.oltu.oauth2' , module: 'org.apache.oltu.oauth2.common' + } + compile "io.gsonfire:gson-fire:$json_fire_version" + compile "org.threeten:threetenbp:$threetenbp_version" + compile "com.typesafe.play:play-ahc-ws_2.12:$play_version" + compile "javax.validation:validation-api:1.1.0.Final" + compile "com.squareup.retrofit2:converter-jackson:$retrofit_version" + compile "com.fasterxml.jackson.core:jackson-core:$jackson_version" + compile "com.fasterxml.jackson.core:jackson-annotations:$jackson_version" + compile "com.fasterxml.jackson.datatype:jackson-datatype-jsr310:$jackson_version" + + testCompile "junit:junit:$junit_version" +} diff --git a/samples/client/petstore/java/retrofit2-play26/build.sbt b/samples/client/petstore/java/retrofit2-play26/build.sbt new file mode 100644 index 0000000000..6ef49aa26d --- /dev/null +++ b/samples/client/petstore/java/retrofit2-play26/build.sbt @@ -0,0 +1,27 @@ +lazy val root = (project in file(".")). + settings( + organization := "org.openapitools", + name := "petstore-java-client-retrofit2-play26", + version := "1.0.0", + scalaVersion := "2.11.4", + scalacOptions ++= Seq("-feature"), + javacOptions in compile ++= Seq("-Xlint:deprecation"), + publishArtifact in (Compile, packageDoc) := false, + resolvers += Resolver.mavenLocal, + libraryDependencies ++= Seq( + "com.squareup.retrofit2" % "retrofit" % "2.3.0" % "compile", + "com.squareup.retrofit2" % "converter-scalars" % "2.3.0" % "compile", + "com.typesafe.play" % "play-ahc-ws_2.12" % "2.6.7" % "compile", + "javax.validation" % "validation-api" % "1.1.0.Final" % "compile", + "com.fasterxml.jackson.core" % "jackson-core" % "2.8.10" % "compile", + "com.fasterxml.jackson.core" % "jackson-annotations" % "2.8.10" % "compile", + "com.fasterxml.jackson.core" % "jackson-databind" % "2.8.10" % "compile", + "com.squareup.retrofit2" % "converter-jackson" % "2.3.0" % "compile", + "io.swagger" % "swagger-annotations" % "1.5.21" % "compile", + "org.apache.oltu.oauth2" % "org.apache.oltu.oauth2.client" % "1.0.1" % "compile", + "org.threeten" % "threetenbp" % "1.3.5" % "compile", + "io.gsonfire" % "gson-fire" % "1.8.0" % "compile", + "junit" % "junit" % "4.12" % "test", + "com.novocode" % "junit-interface" % "0.11" % "test" + ) + ) diff --git a/samples/client/petstore/java/retrofit2-play26/docs/AdditionalPropertiesClass.md b/samples/client/petstore/java/retrofit2-play26/docs/AdditionalPropertiesClass.md new file mode 100644 index 0000000000..0437c4dd8c --- /dev/null +++ b/samples/client/petstore/java/retrofit2-play26/docs/AdditionalPropertiesClass.md @@ -0,0 +1,11 @@ + +# AdditionalPropertiesClass + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**mapProperty** | **Map<String, String>** | | [optional] +**mapOfMapProperty** | [**Map<String, Map<String, String>>**](Map.md) | | [optional] + + + diff --git a/samples/client/petstore/java/retrofit2-play26/docs/Animal.md b/samples/client/petstore/java/retrofit2-play26/docs/Animal.md new file mode 100644 index 0000000000..b3f325c352 --- /dev/null +++ b/samples/client/petstore/java/retrofit2-play26/docs/Animal.md @@ -0,0 +1,11 @@ + +# Animal + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**className** | **String** | | +**color** | **String** | | [optional] + + + diff --git a/samples/client/petstore/java/retrofit2-play26/docs/AnimalFarm.md b/samples/client/petstore/java/retrofit2-play26/docs/AnimalFarm.md new file mode 100644 index 0000000000..c7c7f1ddcc --- /dev/null +++ b/samples/client/petstore/java/retrofit2-play26/docs/AnimalFarm.md @@ -0,0 +1,9 @@ + +# AnimalFarm + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- + + + diff --git a/samples/client/petstore/java/retrofit2-play26/docs/AnotherFakeApi.md b/samples/client/petstore/java/retrofit2-play26/docs/AnotherFakeApi.md new file mode 100644 index 0000000000..c44a064755 --- /dev/null +++ b/samples/client/petstore/java/retrofit2-play26/docs/AnotherFakeApi.md @@ -0,0 +1,54 @@ +# AnotherFakeApi + +All URIs are relative to *http://petstore.swagger.io:80/v2* + +Method | HTTP request | Description +------------- | ------------- | ------------- +[**call123testSpecialTags**](AnotherFakeApi.md#call123testSpecialTags) | **PATCH** another-fake/dummy | To test special tags + + + +# **call123testSpecialTags** +> Client call123testSpecialTags(client) + +To test special tags + +To test special tags and operation ID starting with number + +### Example +```java +// Import classes: +//import org.openapitools.client.ApiException; +//import org.openapitools.client.api.AnotherFakeApi; + + +AnotherFakeApi apiInstance = new AnotherFakeApi(); +Client client = new Client(); // Client | client model +try { + Client result = apiInstance.call123testSpecialTags(client); + System.out.println(result); +} catch (ApiException e) { + System.err.println("Exception when calling AnotherFakeApi#call123testSpecialTags"); + e.printStackTrace(); +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **client** | [**Client**](Client.md)| client model | + +### Return type + +[**Client**](Client.md) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: application/json + - **Accept**: application/json + diff --git a/samples/client/petstore/java/retrofit2-play26/docs/ArrayOfArrayOfNumberOnly.md b/samples/client/petstore/java/retrofit2-play26/docs/ArrayOfArrayOfNumberOnly.md new file mode 100644 index 0000000000..7729254992 --- /dev/null +++ b/samples/client/petstore/java/retrofit2-play26/docs/ArrayOfArrayOfNumberOnly.md @@ -0,0 +1,10 @@ + +# ArrayOfArrayOfNumberOnly + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**arrayArrayNumber** | [**List<List<BigDecimal>>**](List.md) | | [optional] + + + diff --git a/samples/client/petstore/java/retrofit2-play26/docs/ArrayOfNumberOnly.md b/samples/client/petstore/java/retrofit2-play26/docs/ArrayOfNumberOnly.md new file mode 100644 index 0000000000..e8cc4cd36d --- /dev/null +++ b/samples/client/petstore/java/retrofit2-play26/docs/ArrayOfNumberOnly.md @@ -0,0 +1,10 @@ + +# ArrayOfNumberOnly + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**arrayNumber** | [**List<BigDecimal>**](BigDecimal.md) | | [optional] + + + diff --git a/samples/client/petstore/java/retrofit2-play26/docs/ArrayTest.md b/samples/client/petstore/java/retrofit2-play26/docs/ArrayTest.md new file mode 100644 index 0000000000..9feee16427 --- /dev/null +++ b/samples/client/petstore/java/retrofit2-play26/docs/ArrayTest.md @@ -0,0 +1,12 @@ + +# ArrayTest + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**arrayOfString** | **List<String>** | | [optional] +**arrayArrayOfInteger** | [**List<List<Long>>**](List.md) | | [optional] +**arrayArrayOfModel** | [**List<List<ReadOnlyFirst>>**](List.md) | | [optional] + + + diff --git a/samples/client/petstore/java/retrofit2-play26/docs/Capitalization.md b/samples/client/petstore/java/retrofit2-play26/docs/Capitalization.md new file mode 100644 index 0000000000..0f3064c199 --- /dev/null +++ b/samples/client/petstore/java/retrofit2-play26/docs/Capitalization.md @@ -0,0 +1,15 @@ + +# Capitalization + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**smallCamel** | **String** | | [optional] +**capitalCamel** | **String** | | [optional] +**smallSnake** | **String** | | [optional] +**capitalSnake** | **String** | | [optional] +**scAETHFlowPoints** | **String** | | [optional] +**ATT_NAME** | **String** | Name of the pet | [optional] + + + diff --git a/samples/client/petstore/java/retrofit2-play26/docs/Cat.md b/samples/client/petstore/java/retrofit2-play26/docs/Cat.md new file mode 100644 index 0000000000..6e9f71ce7d --- /dev/null +++ b/samples/client/petstore/java/retrofit2-play26/docs/Cat.md @@ -0,0 +1,10 @@ + +# Cat + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**declawed** | **Boolean** | | [optional] + + + diff --git a/samples/client/petstore/java/retrofit2-play26/docs/Category.md b/samples/client/petstore/java/retrofit2-play26/docs/Category.md new file mode 100644 index 0000000000..e2df080327 --- /dev/null +++ b/samples/client/petstore/java/retrofit2-play26/docs/Category.md @@ -0,0 +1,11 @@ + +# Category + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**id** | **Long** | | [optional] +**name** | **String** | | [optional] + + + diff --git a/samples/client/petstore/java/retrofit2-play26/docs/ClassModel.md b/samples/client/petstore/java/retrofit2-play26/docs/ClassModel.md new file mode 100644 index 0000000000..64f880c878 --- /dev/null +++ b/samples/client/petstore/java/retrofit2-play26/docs/ClassModel.md @@ -0,0 +1,10 @@ + +# ClassModel + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**propertyClass** | **String** | | [optional] + + + diff --git a/samples/client/petstore/java/retrofit2-play26/docs/Client.md b/samples/client/petstore/java/retrofit2-play26/docs/Client.md new file mode 100644 index 0000000000..5c490ea166 --- /dev/null +++ b/samples/client/petstore/java/retrofit2-play26/docs/Client.md @@ -0,0 +1,10 @@ + +# Client + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**client** | **String** | | [optional] + + + diff --git a/samples/client/petstore/java/retrofit2-play26/docs/Dog.md b/samples/client/petstore/java/retrofit2-play26/docs/Dog.md new file mode 100644 index 0000000000..ac7cea323f --- /dev/null +++ b/samples/client/petstore/java/retrofit2-play26/docs/Dog.md @@ -0,0 +1,10 @@ + +# Dog + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**breed** | **String** | | [optional] + + + diff --git a/samples/client/petstore/java/retrofit2-play26/docs/EnumArrays.md b/samples/client/petstore/java/retrofit2-play26/docs/EnumArrays.md new file mode 100644 index 0000000000..4dddc0bfd2 --- /dev/null +++ b/samples/client/petstore/java/retrofit2-play26/docs/EnumArrays.md @@ -0,0 +1,27 @@ + +# EnumArrays + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**justSymbol** | [**JustSymbolEnum**](#JustSymbolEnum) | | [optional] +**arrayEnum** | [**List<ArrayEnumEnum>**](#List<ArrayEnumEnum>) | | [optional] + + + +## Enum: JustSymbolEnum +Name | Value +---- | ----- +GREATER_THAN_OR_EQUAL_TO | ">=" +DOLLAR | "$" + + + +## Enum: List<ArrayEnumEnum> +Name | Value +---- | ----- +FISH | "fish" +CRAB | "crab" + + + diff --git a/samples/client/petstore/java/retrofit2-play26/docs/EnumClass.md b/samples/client/petstore/java/retrofit2-play26/docs/EnumClass.md new file mode 100644 index 0000000000..c746edc3cb --- /dev/null +++ b/samples/client/petstore/java/retrofit2-play26/docs/EnumClass.md @@ -0,0 +1,14 @@ + +# EnumClass + +## Enum + + +* `_ABC` (value: `"_abc"`) + +* `_EFG` (value: `"-efg"`) + +* `_XYZ_` (value: `"(xyz)"`) + + + diff --git a/samples/client/petstore/java/retrofit2-play26/docs/EnumTest.md b/samples/client/petstore/java/retrofit2-play26/docs/EnumTest.md new file mode 100644 index 0000000000..ca048bcc51 --- /dev/null +++ b/samples/client/petstore/java/retrofit2-play26/docs/EnumTest.md @@ -0,0 +1,48 @@ + +# EnumTest + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**enumString** | [**EnumStringEnum**](#EnumStringEnum) | | [optional] +**enumStringRequired** | [**EnumStringRequiredEnum**](#EnumStringRequiredEnum) | | +**enumInteger** | [**EnumIntegerEnum**](#EnumIntegerEnum) | | [optional] +**enumNumber** | [**EnumNumberEnum**](#EnumNumberEnum) | | [optional] +**outerEnum** | [**OuterEnum**](OuterEnum.md) | | [optional] + + + +## Enum: EnumStringEnum +Name | Value +---- | ----- +UPPER | "UPPER" +LOWER | "lower" +EMPTY | "" + + + +## Enum: EnumStringRequiredEnum +Name | Value +---- | ----- +UPPER | "UPPER" +LOWER | "lower" +EMPTY | "" + + + +## Enum: EnumIntegerEnum +Name | Value +---- | ----- +NUMBER_1 | 1 +NUMBER_MINUS_1 | -1 + + + +## Enum: EnumNumberEnum +Name | Value +---- | ----- +NUMBER_1_DOT_1 | 1.1 +NUMBER_MINUS_1_DOT_2 | -1.2 + + + diff --git a/samples/client/petstore/java/retrofit2-play26/docs/FakeApi.md b/samples/client/petstore/java/retrofit2-play26/docs/FakeApi.md new file mode 100644 index 0000000000..2d5d6ba136 --- /dev/null +++ b/samples/client/petstore/java/retrofit2-play26/docs/FakeApi.md @@ -0,0 +1,555 @@ +# FakeApi + +All URIs are relative to *http://petstore.swagger.io:80/v2* + +Method | HTTP request | Description +------------- | ------------- | ------------- +[**fakeOuterBooleanSerialize**](FakeApi.md#fakeOuterBooleanSerialize) | **POST** fake/outer/boolean | +[**fakeOuterCompositeSerialize**](FakeApi.md#fakeOuterCompositeSerialize) | **POST** fake/outer/composite | +[**fakeOuterNumberSerialize**](FakeApi.md#fakeOuterNumberSerialize) | **POST** fake/outer/number | +[**fakeOuterStringSerialize**](FakeApi.md#fakeOuterStringSerialize) | **POST** fake/outer/string | +[**testBodyWithFileSchema**](FakeApi.md#testBodyWithFileSchema) | **PUT** fake/body-with-file-schema | +[**testBodyWithQueryParams**](FakeApi.md#testBodyWithQueryParams) | **PUT** fake/body-with-query-params | +[**testClientModel**](FakeApi.md#testClientModel) | **PATCH** fake | To test \"client\" model +[**testEndpointParameters**](FakeApi.md#testEndpointParameters) | **POST** fake | Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 +[**testEnumParameters**](FakeApi.md#testEnumParameters) | **GET** fake | To test enum parameters +[**testInlineAdditionalProperties**](FakeApi.md#testInlineAdditionalProperties) | **POST** fake/inline-additionalProperties | test inline additionalProperties +[**testJsonFormData**](FakeApi.md#testJsonFormData) | **GET** fake/jsonFormData | test json serialization of form data + + + +# **fakeOuterBooleanSerialize** +> Boolean fakeOuterBooleanSerialize(body) + + + +Test serialization of outer boolean types + +### Example +```java +// Import classes: +//import org.openapitools.client.ApiException; +//import org.openapitools.client.api.FakeApi; + + +FakeApi apiInstance = new FakeApi(); +Boolean body = true; // Boolean | Input boolean as post body +try { + Boolean result = apiInstance.fakeOuterBooleanSerialize(body); + System.out.println(result); +} catch (ApiException e) { + System.err.println("Exception when calling FakeApi#fakeOuterBooleanSerialize"); + e.printStackTrace(); +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **body** | **Boolean**| Input boolean as post body | [optional] + +### Return type + +**Boolean** + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: */* + + +# **fakeOuterCompositeSerialize** +> OuterComposite fakeOuterCompositeSerialize(outerComposite) + + + +Test serialization of object with outer number type + +### Example +```java +// Import classes: +//import org.openapitools.client.ApiException; +//import org.openapitools.client.api.FakeApi; + + +FakeApi apiInstance = new FakeApi(); +OuterComposite outerComposite = new OuterComposite(); // OuterComposite | Input composite as post body +try { + OuterComposite result = apiInstance.fakeOuterCompositeSerialize(outerComposite); + System.out.println(result); +} catch (ApiException e) { + System.err.println("Exception when calling FakeApi#fakeOuterCompositeSerialize"); + e.printStackTrace(); +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **outerComposite** | [**OuterComposite**](OuterComposite.md)| Input composite as post body | [optional] + +### Return type + +[**OuterComposite**](OuterComposite.md) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: */* + + +# **fakeOuterNumberSerialize** +> BigDecimal fakeOuterNumberSerialize(body) + + + +Test serialization of outer number types + +### Example +```java +// Import classes: +//import org.openapitools.client.ApiException; +//import org.openapitools.client.api.FakeApi; + + +FakeApi apiInstance = new FakeApi(); +BigDecimal body = new BigDecimal(); // BigDecimal | Input number as post body +try { + BigDecimal result = apiInstance.fakeOuterNumberSerialize(body); + System.out.println(result); +} catch (ApiException e) { + System.err.println("Exception when calling FakeApi#fakeOuterNumberSerialize"); + e.printStackTrace(); +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **body** | **BigDecimal**| Input number as post body | [optional] + +### Return type + +[**BigDecimal**](BigDecimal.md) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: */* + + +# **fakeOuterStringSerialize** +> String fakeOuterStringSerialize(body) + + + +Test serialization of outer string types + +### Example +```java +// Import classes: +//import org.openapitools.client.ApiException; +//import org.openapitools.client.api.FakeApi; + + +FakeApi apiInstance = new FakeApi(); +String body = "body_example"; // String | Input string as post body +try { + String result = apiInstance.fakeOuterStringSerialize(body); + System.out.println(result); +} catch (ApiException e) { + System.err.println("Exception when calling FakeApi#fakeOuterStringSerialize"); + e.printStackTrace(); +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **body** | **String**| Input string as post body | [optional] + +### Return type + +**String** + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: */* + + +# **testBodyWithFileSchema** +> testBodyWithFileSchema(fileSchemaTestClass) + + + +For this test, the body for this request much reference a schema named `File`. + +### Example +```java +// Import classes: +//import org.openapitools.client.ApiException; +//import org.openapitools.client.api.FakeApi; + + +FakeApi apiInstance = new FakeApi(); +FileSchemaTestClass fileSchemaTestClass = new FileSchemaTestClass(); // FileSchemaTestClass | +try { + apiInstance.testBodyWithFileSchema(fileSchemaTestClass); +} catch (ApiException e) { + System.err.println("Exception when calling FakeApi#testBodyWithFileSchema"); + e.printStackTrace(); +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **fileSchemaTestClass** | [**FileSchemaTestClass**](FileSchemaTestClass.md)| | + +### Return type + +null (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: application/json + - **Accept**: Not defined + + +# **testBodyWithQueryParams** +> testBodyWithQueryParams(query, user) + + + +### Example +```java +// Import classes: +//import org.openapitools.client.ApiException; +//import org.openapitools.client.api.FakeApi; + + +FakeApi apiInstance = new FakeApi(); +String query = "query_example"; // String | +User user = new User(); // User | +try { + apiInstance.testBodyWithQueryParams(query, user); +} catch (ApiException e) { + System.err.println("Exception when calling FakeApi#testBodyWithQueryParams"); + e.printStackTrace(); +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **query** | **String**| | + **user** | [**User**](User.md)| | + +### Return type + +null (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: application/json + - **Accept**: Not defined + + +# **testClientModel** +> Client testClientModel(client) + +To test \"client\" model + +To test \"client\" model + +### Example +```java +// Import classes: +//import org.openapitools.client.ApiException; +//import org.openapitools.client.api.FakeApi; + + +FakeApi apiInstance = new FakeApi(); +Client client = new Client(); // Client | client model +try { + Client result = apiInstance.testClientModel(client); + System.out.println(result); +} catch (ApiException e) { + System.err.println("Exception when calling FakeApi#testClientModel"); + e.printStackTrace(); +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **client** | [**Client**](Client.md)| client model | + +### Return type + +[**Client**](Client.md) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: application/json + - **Accept**: application/json + + +# **testEndpointParameters** +> testEndpointParameters(number, _double, patternWithoutDelimiter, _byte, integer, int32, int64, _float, string, binary, date, dateTime, password, paramCallback) + +Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + +Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + +### Example +```java +// Import classes: +//import org.openapitools.client.ApiClient; +//import org.openapitools.client.ApiException; +//import org.openapitools.client.Configuration; +//import org.openapitools.client.auth.*; +//import org.openapitools.client.api.FakeApi; + +ApiClient defaultClient = Configuration.getDefaultApiClient(); + +// Configure HTTP basic authorization: http_basic_test +HttpBasicAuth http_basic_test = (HttpBasicAuth) defaultClient.getAuthentication("http_basic_test"); +http_basic_test.setUsername("YOUR USERNAME"); +http_basic_test.setPassword("YOUR PASSWORD"); + +FakeApi apiInstance = new FakeApi(); +BigDecimal number = new BigDecimal(); // BigDecimal | None +Double _double = 3.4D; // Double | None +String patternWithoutDelimiter = "null"; // String | None +byte[] _byte = null; // byte[] | None +Integer integer = null; // Integer | None +Integer int32 = null; // Integer | None +Long int64 = nullL; // Long | None +Float _float = nullF; // Float | None +String string = "null"; // String | None +File binary = new File("null"); // File | None +LocalDate date = new LocalDate(); // LocalDate | None +OffsetDateTime dateTime = new OffsetDateTime(); // OffsetDateTime | None +String password = "null"; // String | None +String paramCallback = "null"; // String | None +try { + apiInstance.testEndpointParameters(number, _double, patternWithoutDelimiter, _byte, integer, int32, int64, _float, string, binary, date, dateTime, password, paramCallback); +} catch (ApiException e) { + System.err.println("Exception when calling FakeApi#testEndpointParameters"); + e.printStackTrace(); +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **number** | **BigDecimal**| None | [default to null] + **_double** | **Double**| None | [default to null] + **patternWithoutDelimiter** | **String**| None | [default to null] + **_byte** | **byte[]**| None | [default to null] + **integer** | **Integer**| None | [optional] [default to null] + **int32** | **Integer**| None | [optional] [default to null] + **int64** | **Long**| None | [optional] [default to null] + **_float** | **Float**| None | [optional] [default to null] + **string** | **String**| None | [optional] [default to null] + **binary** | **File**| None | [optional] [default to null] + **date** | **LocalDate**| None | [optional] [default to null] + **dateTime** | **OffsetDateTime**| None | [optional] [default to null] + **password** | **String**| None | [optional] [default to null] + **paramCallback** | **String**| None | [optional] [default to null] + +### Return type + +null (empty response body) + +### Authorization + +[http_basic_test](../README.md#http_basic_test) + +### HTTP request headers + + - **Content-Type**: application/x-www-form-urlencoded + - **Accept**: Not defined + + +# **testEnumParameters** +> testEnumParameters(enumHeaderStringArray, enumHeaderString, enumQueryStringArray, enumQueryString, enumQueryInteger, enumQueryDouble, enumFormStringArray, enumFormString) + +To test enum parameters + +To test enum parameters + +### Example +```java +// Import classes: +//import org.openapitools.client.ApiException; +//import org.openapitools.client.api.FakeApi; + + +FakeApi apiInstance = new FakeApi(); +List enumHeaderStringArray = Arrays.asList("enumHeaderStringArray_example"); // List | Header parameter enum test (string array) +String enumHeaderString = "-efg"; // String | Header parameter enum test (string) +List enumQueryStringArray = Arrays.asList("enumQueryStringArray_example"); // List | Query parameter enum test (string array) +String enumQueryString = "-efg"; // String | Query parameter enum test (string) +Integer enumQueryInteger = 56; // Integer | Query parameter enum test (double) +Double enumQueryDouble = 3.4D; // Double | Query parameter enum test (double) +List enumFormStringArray = "$"; // List | Form parameter enum test (string array) +String enumFormString = "-efg"; // String | Form parameter enum test (string) +try { + apiInstance.testEnumParameters(enumHeaderStringArray, enumHeaderString, enumQueryStringArray, enumQueryString, enumQueryInteger, enumQueryDouble, enumFormStringArray, enumFormString); +} catch (ApiException e) { + System.err.println("Exception when calling FakeApi#testEnumParameters"); + e.printStackTrace(); +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **enumHeaderStringArray** | [**List<String>**](String.md)| Header parameter enum test (string array) | [optional] [enum: >, $] + **enumHeaderString** | **String**| Header parameter enum test (string) | [optional] [default to -efg] [enum: _abc, -efg, (xyz)] + **enumQueryStringArray** | [**List<String>**](String.md)| Query parameter enum test (string array) | [optional] [enum: >, $] + **enumQueryString** | **String**| Query parameter enum test (string) | [optional] [default to -efg] [enum: _abc, -efg, (xyz)] + **enumQueryInteger** | **Integer**| Query parameter enum test (double) | [optional] [enum: 1, -2] + **enumQueryDouble** | **Double**| Query parameter enum test (double) | [optional] [enum: 1.1, -1.2] + **enumFormStringArray** | [**List<String>**](String.md)| Form parameter enum test (string array) | [optional] [default to $] [enum: >, $] + **enumFormString** | **String**| Form parameter enum test (string) | [optional] [default to -efg] [enum: _abc, -efg, (xyz)] + +### Return type + +null (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: application/x-www-form-urlencoded + - **Accept**: Not defined + + +# **testInlineAdditionalProperties** +> testInlineAdditionalProperties(requestBody) + +test inline additionalProperties + +### Example +```java +// Import classes: +//import org.openapitools.client.ApiException; +//import org.openapitools.client.api.FakeApi; + + +FakeApi apiInstance = new FakeApi(); +Map requestBody = new HashMap(); // Map | request body +try { + apiInstance.testInlineAdditionalProperties(requestBody); +} catch (ApiException e) { + System.err.println("Exception when calling FakeApi#testInlineAdditionalProperties"); + e.printStackTrace(); +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **requestBody** | [**Map<String, String>**](String.md)| request body | + +### Return type + +null (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: application/json + - **Accept**: Not defined + + +# **testJsonFormData** +> testJsonFormData(param, param2) + +test json serialization of form data + +### Example +```java +// Import classes: +//import org.openapitools.client.ApiException; +//import org.openapitools.client.api.FakeApi; + + +FakeApi apiInstance = new FakeApi(); +String param = "null"; // String | field1 +String param2 = "null"; // String | field2 +try { + apiInstance.testJsonFormData(param, param2); +} catch (ApiException e) { + System.err.println("Exception when calling FakeApi#testJsonFormData"); + e.printStackTrace(); +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **param** | **String**| field1 | [default to null] + **param2** | **String**| field2 | [default to null] + +### Return type + +null (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: application/x-www-form-urlencoded + - **Accept**: Not defined + diff --git a/samples/client/petstore/java/retrofit2-play26/docs/FakeClassnameTags123Api.md b/samples/client/petstore/java/retrofit2-play26/docs/FakeClassnameTags123Api.md new file mode 100644 index 0000000000..d805d10a83 --- /dev/null +++ b/samples/client/petstore/java/retrofit2-play26/docs/FakeClassnameTags123Api.md @@ -0,0 +1,64 @@ +# FakeClassnameTags123Api + +All URIs are relative to *http://petstore.swagger.io:80/v2* + +Method | HTTP request | Description +------------- | ------------- | ------------- +[**testClassname**](FakeClassnameTags123Api.md#testClassname) | **PATCH** fake_classname_test | To test class name in snake case + + + +# **testClassname** +> Client testClassname(client) + +To test class name in snake case + +To test class name in snake case + +### Example +```java +// Import classes: +//import org.openapitools.client.ApiClient; +//import org.openapitools.client.ApiException; +//import org.openapitools.client.Configuration; +//import org.openapitools.client.auth.*; +//import org.openapitools.client.api.FakeClassnameTags123Api; + +ApiClient defaultClient = Configuration.getDefaultApiClient(); + +// Configure API key authorization: api_key_query +ApiKeyAuth api_key_query = (ApiKeyAuth) defaultClient.getAuthentication("api_key_query"); +api_key_query.setApiKey("YOUR API KEY"); +// Uncomment the following line to set a prefix for the API key, e.g. "Token" (defaults to null) +//api_key_query.setApiKeyPrefix("Token"); + +FakeClassnameTags123Api apiInstance = new FakeClassnameTags123Api(); +Client client = new Client(); // Client | client model +try { + Client result = apiInstance.testClassname(client); + System.out.println(result); +} catch (ApiException e) { + System.err.println("Exception when calling FakeClassnameTags123Api#testClassname"); + e.printStackTrace(); +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **client** | [**Client**](Client.md)| client model | + +### Return type + +[**Client**](Client.md) + +### Authorization + +[api_key_query](../README.md#api_key_query) + +### HTTP request headers + + - **Content-Type**: application/json + - **Accept**: application/json + diff --git a/samples/client/petstore/java/retrofit2-play26/docs/FileSchemaTestClass.md b/samples/client/petstore/java/retrofit2-play26/docs/FileSchemaTestClass.md new file mode 100644 index 0000000000..95ba647df6 --- /dev/null +++ b/samples/client/petstore/java/retrofit2-play26/docs/FileSchemaTestClass.md @@ -0,0 +1,11 @@ + +# FileSchemaTestClass + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**file** | [**java.io.File**](java.io.File.md) | | [optional] +**files** | [**List<java.io.File>**](java.io.File.md) | | [optional] + + + diff --git a/samples/client/petstore/java/retrofit2-play26/docs/FormatTest.md b/samples/client/petstore/java/retrofit2-play26/docs/FormatTest.md new file mode 100644 index 0000000000..986f70236e --- /dev/null +++ b/samples/client/petstore/java/retrofit2-play26/docs/FormatTest.md @@ -0,0 +1,22 @@ + +# FormatTest + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**integer** | **Integer** | | [optional] +**int32** | **Integer** | | [optional] +**int64** | **Long** | | [optional] +**number** | [**BigDecimal**](BigDecimal.md) | | +**_float** | **Float** | | [optional] +**_double** | **Double** | | [optional] +**string** | **String** | | [optional] +**_byte** | **byte[]** | | +**binary** | [**File**](File.md) | | [optional] +**date** | [**LocalDate**](LocalDate.md) | | +**dateTime** | [**OffsetDateTime**](OffsetDateTime.md) | | [optional] +**uuid** | [**UUID**](UUID.md) | | [optional] +**password** | **String** | | + + + diff --git a/samples/client/petstore/java/retrofit2-play26/docs/HasOnlyReadOnly.md b/samples/client/petstore/java/retrofit2-play26/docs/HasOnlyReadOnly.md new file mode 100644 index 0000000000..c1d0aac567 --- /dev/null +++ b/samples/client/petstore/java/retrofit2-play26/docs/HasOnlyReadOnly.md @@ -0,0 +1,11 @@ + +# HasOnlyReadOnly + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**bar** | **String** | | [optional] +**foo** | **String** | | [optional] + + + diff --git a/samples/client/petstore/java/retrofit2-play26/docs/MapTest.md b/samples/client/petstore/java/retrofit2-play26/docs/MapTest.md new file mode 100644 index 0000000000..f3b592d43f --- /dev/null +++ b/samples/client/petstore/java/retrofit2-play26/docs/MapTest.md @@ -0,0 +1,21 @@ + +# MapTest + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**mapMapOfString** | [**Map<String, Map<String, String>>**](Map.md) | | [optional] +**mapOfEnumString** | [**Map<String, InnerEnum>**](#Map<String, InnerEnum>) | | [optional] +**directMap** | **Map<String, Boolean>** | | [optional] +**indirectMap** | [**StringBooleanMap**](StringBooleanMap.md) | | [optional] + + + +## Enum: Map<String, InnerEnum> +Name | Value +---- | ----- +UPPER | "UPPER" +LOWER | "lower" + + + diff --git a/samples/client/petstore/java/retrofit2-play26/docs/MixedPropertiesAndAdditionalPropertiesClass.md b/samples/client/petstore/java/retrofit2-play26/docs/MixedPropertiesAndAdditionalPropertiesClass.md new file mode 100644 index 0000000000..b12e2cd70e --- /dev/null +++ b/samples/client/petstore/java/retrofit2-play26/docs/MixedPropertiesAndAdditionalPropertiesClass.md @@ -0,0 +1,12 @@ + +# MixedPropertiesAndAdditionalPropertiesClass + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**uuid** | [**UUID**](UUID.md) | | [optional] +**dateTime** | [**OffsetDateTime**](OffsetDateTime.md) | | [optional] +**map** | [**Map<String, Animal>**](Animal.md) | | [optional] + + + diff --git a/samples/client/petstore/java/retrofit2-play26/docs/Model200Response.md b/samples/client/petstore/java/retrofit2-play26/docs/Model200Response.md new file mode 100644 index 0000000000..5b3a9a0e46 --- /dev/null +++ b/samples/client/petstore/java/retrofit2-play26/docs/Model200Response.md @@ -0,0 +1,11 @@ + +# Model200Response + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**name** | **Integer** | | [optional] +**propertyClass** | **String** | | [optional] + + + diff --git a/samples/client/petstore/java/retrofit2-play26/docs/ModelApiResponse.md b/samples/client/petstore/java/retrofit2-play26/docs/ModelApiResponse.md new file mode 100644 index 0000000000..3eec8686cc --- /dev/null +++ b/samples/client/petstore/java/retrofit2-play26/docs/ModelApiResponse.md @@ -0,0 +1,12 @@ + +# ModelApiResponse + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**code** | **Integer** | | [optional] +**type** | **String** | | [optional] +**message** | **String** | | [optional] + + + diff --git a/samples/client/petstore/java/retrofit2-play26/docs/ModelReturn.md b/samples/client/petstore/java/retrofit2-play26/docs/ModelReturn.md new file mode 100644 index 0000000000..a679b04953 --- /dev/null +++ b/samples/client/petstore/java/retrofit2-play26/docs/ModelReturn.md @@ -0,0 +1,10 @@ + +# ModelReturn + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**_return** | **Integer** | | [optional] + + + diff --git a/samples/client/petstore/java/retrofit2-play26/docs/Name.md b/samples/client/petstore/java/retrofit2-play26/docs/Name.md new file mode 100644 index 0000000000..64060f82de --- /dev/null +++ b/samples/client/petstore/java/retrofit2-play26/docs/Name.md @@ -0,0 +1,13 @@ + +# Name + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**name** | **Integer** | | +**snakeCase** | **Integer** | | [optional] +**property** | **String** | | [optional] +**_123number** | **Integer** | | [optional] + + + diff --git a/samples/client/petstore/java/retrofit2-play26/docs/NumberOnly.md b/samples/client/petstore/java/retrofit2-play26/docs/NumberOnly.md new file mode 100644 index 0000000000..a3feac7fad --- /dev/null +++ b/samples/client/petstore/java/retrofit2-play26/docs/NumberOnly.md @@ -0,0 +1,10 @@ + +# NumberOnly + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**justNumber** | [**BigDecimal**](BigDecimal.md) | | [optional] + + + diff --git a/samples/client/petstore/java/retrofit2-play26/docs/Order.md b/samples/client/petstore/java/retrofit2-play26/docs/Order.md new file mode 100644 index 0000000000..268c617d1f --- /dev/null +++ b/samples/client/petstore/java/retrofit2-play26/docs/Order.md @@ -0,0 +1,24 @@ + +# Order + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**id** | **Long** | | [optional] +**petId** | **Long** | | [optional] +**quantity** | **Integer** | | [optional] +**shipDate** | [**OffsetDateTime**](OffsetDateTime.md) | | [optional] +**status** | [**StatusEnum**](#StatusEnum) | Order Status | [optional] +**complete** | **Boolean** | | [optional] + + + +## Enum: StatusEnum +Name | Value +---- | ----- +PLACED | "placed" +APPROVED | "approved" +DELIVERED | "delivered" + + + diff --git a/samples/client/petstore/java/retrofit2-play26/docs/OuterComposite.md b/samples/client/petstore/java/retrofit2-play26/docs/OuterComposite.md new file mode 100644 index 0000000000..3f5a633c99 --- /dev/null +++ b/samples/client/petstore/java/retrofit2-play26/docs/OuterComposite.md @@ -0,0 +1,12 @@ + +# OuterComposite + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**myNumber** | [**BigDecimal**](BigDecimal.md) | | [optional] +**myString** | **String** | | [optional] +**myBoolean** | **Boolean** | | [optional] + + + diff --git a/samples/client/petstore/java/retrofit2-play26/docs/OuterEnum.md b/samples/client/petstore/java/retrofit2-play26/docs/OuterEnum.md new file mode 100644 index 0000000000..ed2cb20678 --- /dev/null +++ b/samples/client/petstore/java/retrofit2-play26/docs/OuterEnum.md @@ -0,0 +1,14 @@ + +# OuterEnum + +## Enum + + +* `PLACED` (value: `"placed"`) + +* `APPROVED` (value: `"approved"`) + +* `DELIVERED` (value: `"delivered"`) + + + diff --git a/samples/client/petstore/java/retrofit2-play26/docs/Pet.md b/samples/client/petstore/java/retrofit2-play26/docs/Pet.md new file mode 100644 index 0000000000..5b63109ef9 --- /dev/null +++ b/samples/client/petstore/java/retrofit2-play26/docs/Pet.md @@ -0,0 +1,24 @@ + +# Pet + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**id** | **Long** | | [optional] +**category** | [**Category**](Category.md) | | [optional] +**name** | **String** | | +**photoUrls** | **List<String>** | | +**tags** | [**List<Tag>**](Tag.md) | | [optional] +**status** | [**StatusEnum**](#StatusEnum) | pet status in the store | [optional] + + + +## Enum: StatusEnum +Name | Value +---- | ----- +AVAILABLE | "available" +PENDING | "pending" +SOLD | "sold" + + + diff --git a/samples/client/petstore/java/retrofit2-play26/docs/PetApi.md b/samples/client/petstore/java/retrofit2-play26/docs/PetApi.md new file mode 100644 index 0000000000..0005f28329 --- /dev/null +++ b/samples/client/petstore/java/retrofit2-play26/docs/PetApi.md @@ -0,0 +1,494 @@ +# PetApi + +All URIs are relative to *http://petstore.swagger.io:80/v2* + +Method | HTTP request | Description +------------- | ------------- | ------------- +[**addPet**](PetApi.md#addPet) | **POST** pet | Add a new pet to the store +[**deletePet**](PetApi.md#deletePet) | **DELETE** pet/{petId} | Deletes a pet +[**findPetsByStatus**](PetApi.md#findPetsByStatus) | **GET** pet/findByStatus | Finds Pets by status +[**findPetsByTags**](PetApi.md#findPetsByTags) | **GET** pet/findByTags | Finds Pets by tags +[**getPetById**](PetApi.md#getPetById) | **GET** pet/{petId} | Find pet by ID +[**updatePet**](PetApi.md#updatePet) | **PUT** pet | Update an existing pet +[**updatePetWithForm**](PetApi.md#updatePetWithForm) | **POST** pet/{petId} | Updates a pet in the store with form data +[**uploadFile**](PetApi.md#uploadFile) | **POST** pet/{petId}/uploadImage | uploads an image +[**uploadFileWithRequiredFile**](PetApi.md#uploadFileWithRequiredFile) | **POST** fake/{petId}/uploadImageWithRequiredFile | uploads an image (required) + + + +# **addPet** +> addPet(pet) + +Add a new pet to the store + +### Example +```java +// Import classes: +//import org.openapitools.client.ApiClient; +//import org.openapitools.client.ApiException; +//import org.openapitools.client.Configuration; +//import org.openapitools.client.auth.*; +//import org.openapitools.client.api.PetApi; + +ApiClient defaultClient = Configuration.getDefaultApiClient(); + +// Configure OAuth2 access token for authorization: petstore_auth +OAuth petstore_auth = (OAuth) defaultClient.getAuthentication("petstore_auth"); +petstore_auth.setAccessToken("YOUR ACCESS TOKEN"); + +PetApi apiInstance = new PetApi(); +Pet pet = new Pet(); // Pet | Pet object that needs to be added to the store +try { + apiInstance.addPet(pet); +} catch (ApiException e) { + System.err.println("Exception when calling PetApi#addPet"); + e.printStackTrace(); +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **pet** | [**Pet**](Pet.md)| Pet object that needs to be added to the store | + +### Return type + +null (empty response body) + +### Authorization + +[petstore_auth](../README.md#petstore_auth) + +### HTTP request headers + + - **Content-Type**: application/json, application/xml + - **Accept**: Not defined + + +# **deletePet** +> deletePet(petId, apiKey) + +Deletes a pet + +### Example +```java +// Import classes: +//import org.openapitools.client.ApiClient; +//import org.openapitools.client.ApiException; +//import org.openapitools.client.Configuration; +//import org.openapitools.client.auth.*; +//import org.openapitools.client.api.PetApi; + +ApiClient defaultClient = Configuration.getDefaultApiClient(); + +// Configure OAuth2 access token for authorization: petstore_auth +OAuth petstore_auth = (OAuth) defaultClient.getAuthentication("petstore_auth"); +petstore_auth.setAccessToken("YOUR ACCESS TOKEN"); + +PetApi apiInstance = new PetApi(); +Long petId = 56L; // Long | Pet id to delete +String apiKey = "apiKey_example"; // String | +try { + apiInstance.deletePet(petId, apiKey); +} catch (ApiException e) { + System.err.println("Exception when calling PetApi#deletePet"); + e.printStackTrace(); +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **petId** | **Long**| Pet id to delete | + **apiKey** | **String**| | [optional] + +### Return type + +null (empty response body) + +### Authorization + +[petstore_auth](../README.md#petstore_auth) + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: Not defined + + +# **findPetsByStatus** +> List<Pet> findPetsByStatus(status) + +Finds Pets by status + +Multiple status values can be provided with comma separated strings + +### Example +```java +// Import classes: +//import org.openapitools.client.ApiClient; +//import org.openapitools.client.ApiException; +//import org.openapitools.client.Configuration; +//import org.openapitools.client.auth.*; +//import org.openapitools.client.api.PetApi; + +ApiClient defaultClient = Configuration.getDefaultApiClient(); + +// Configure OAuth2 access token for authorization: petstore_auth +OAuth petstore_auth = (OAuth) defaultClient.getAuthentication("petstore_auth"); +petstore_auth.setAccessToken("YOUR ACCESS TOKEN"); + +PetApi apiInstance = new PetApi(); +List status = Arrays.asList("status_example"); // List | Status values that need to be considered for filter +try { + List result = apiInstance.findPetsByStatus(status); + System.out.println(result); +} catch (ApiException e) { + System.err.println("Exception when calling PetApi#findPetsByStatus"); + e.printStackTrace(); +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **status** | [**List<String>**](String.md)| Status values that need to be considered for filter | [enum: available, pending, sold] + +### Return type + +[**List<Pet>**](Pet.md) + +### Authorization + +[petstore_auth](../README.md#petstore_auth) + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/xml, application/json + + +# **findPetsByTags** +> List<Pet> findPetsByTags(tags) + +Finds Pets by tags + +Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. + +### Example +```java +// Import classes: +//import org.openapitools.client.ApiClient; +//import org.openapitools.client.ApiException; +//import org.openapitools.client.Configuration; +//import org.openapitools.client.auth.*; +//import org.openapitools.client.api.PetApi; + +ApiClient defaultClient = Configuration.getDefaultApiClient(); + +// Configure OAuth2 access token for authorization: petstore_auth +OAuth petstore_auth = (OAuth) defaultClient.getAuthentication("petstore_auth"); +petstore_auth.setAccessToken("YOUR ACCESS TOKEN"); + +PetApi apiInstance = new PetApi(); +List tags = Arrays.asList("tags_example"); // List | Tags to filter by +try { + List result = apiInstance.findPetsByTags(tags); + System.out.println(result); +} catch (ApiException e) { + System.err.println("Exception when calling PetApi#findPetsByTags"); + e.printStackTrace(); +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **tags** | [**List<String>**](String.md)| Tags to filter by | + +### Return type + +[**List<Pet>**](Pet.md) + +### Authorization + +[petstore_auth](../README.md#petstore_auth) + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/xml, application/json + + +# **getPetById** +> Pet getPetById(petId) + +Find pet by ID + +Returns a single pet + +### Example +```java +// Import classes: +//import org.openapitools.client.ApiClient; +//import org.openapitools.client.ApiException; +//import org.openapitools.client.Configuration; +//import org.openapitools.client.auth.*; +//import org.openapitools.client.api.PetApi; + +ApiClient defaultClient = Configuration.getDefaultApiClient(); + +// Configure API key authorization: api_key +ApiKeyAuth api_key = (ApiKeyAuth) defaultClient.getAuthentication("api_key"); +api_key.setApiKey("YOUR API KEY"); +// Uncomment the following line to set a prefix for the API key, e.g. "Token" (defaults to null) +//api_key.setApiKeyPrefix("Token"); + +PetApi apiInstance = new PetApi(); +Long petId = 56L; // Long | ID of pet to return +try { + Pet result = apiInstance.getPetById(petId); + System.out.println(result); +} catch (ApiException e) { + System.err.println("Exception when calling PetApi#getPetById"); + e.printStackTrace(); +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **petId** | **Long**| ID of pet to return | + +### Return type + +[**Pet**](Pet.md) + +### Authorization + +[api_key](../README.md#api_key) + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/xml, application/json + + +# **updatePet** +> updatePet(pet) + +Update an existing pet + +### Example +```java +// Import classes: +//import org.openapitools.client.ApiClient; +//import org.openapitools.client.ApiException; +//import org.openapitools.client.Configuration; +//import org.openapitools.client.auth.*; +//import org.openapitools.client.api.PetApi; + +ApiClient defaultClient = Configuration.getDefaultApiClient(); + +// Configure OAuth2 access token for authorization: petstore_auth +OAuth petstore_auth = (OAuth) defaultClient.getAuthentication("petstore_auth"); +petstore_auth.setAccessToken("YOUR ACCESS TOKEN"); + +PetApi apiInstance = new PetApi(); +Pet pet = new Pet(); // Pet | Pet object that needs to be added to the store +try { + apiInstance.updatePet(pet); +} catch (ApiException e) { + System.err.println("Exception when calling PetApi#updatePet"); + e.printStackTrace(); +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **pet** | [**Pet**](Pet.md)| Pet object that needs to be added to the store | + +### Return type + +null (empty response body) + +### Authorization + +[petstore_auth](../README.md#petstore_auth) + +### HTTP request headers + + - **Content-Type**: application/json, application/xml + - **Accept**: Not defined + + +# **updatePetWithForm** +> updatePetWithForm(petId, name, status) + +Updates a pet in the store with form data + +### Example +```java +// Import classes: +//import org.openapitools.client.ApiClient; +//import org.openapitools.client.ApiException; +//import org.openapitools.client.Configuration; +//import org.openapitools.client.auth.*; +//import org.openapitools.client.api.PetApi; + +ApiClient defaultClient = Configuration.getDefaultApiClient(); + +// Configure OAuth2 access token for authorization: petstore_auth +OAuth petstore_auth = (OAuth) defaultClient.getAuthentication("petstore_auth"); +petstore_auth.setAccessToken("YOUR ACCESS TOKEN"); + +PetApi apiInstance = new PetApi(); +Long petId = 56L; // Long | ID of pet that needs to be updated +String name = "null"; // String | Updated name of the pet +String status = "null"; // String | Updated status of the pet +try { + apiInstance.updatePetWithForm(petId, name, status); +} catch (ApiException e) { + System.err.println("Exception when calling PetApi#updatePetWithForm"); + e.printStackTrace(); +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **petId** | **Long**| ID of pet that needs to be updated | + **name** | **String**| Updated name of the pet | [optional] [default to null] + **status** | **String**| Updated status of the pet | [optional] [default to null] + +### Return type + +null (empty response body) + +### Authorization + +[petstore_auth](../README.md#petstore_auth) + +### HTTP request headers + + - **Content-Type**: application/x-www-form-urlencoded + - **Accept**: Not defined + + +# **uploadFile** +> ModelApiResponse uploadFile(petId, additionalMetadata, file) + +uploads an image + +### Example +```java +// Import classes: +//import org.openapitools.client.ApiClient; +//import org.openapitools.client.ApiException; +//import org.openapitools.client.Configuration; +//import org.openapitools.client.auth.*; +//import org.openapitools.client.api.PetApi; + +ApiClient defaultClient = Configuration.getDefaultApiClient(); + +// Configure OAuth2 access token for authorization: petstore_auth +OAuth petstore_auth = (OAuth) defaultClient.getAuthentication("petstore_auth"); +petstore_auth.setAccessToken("YOUR ACCESS TOKEN"); + +PetApi apiInstance = new PetApi(); +Long petId = 56L; // Long | ID of pet to update +String additionalMetadata = "null"; // String | Additional data to pass to server +File file = new File("null"); // File | file to upload +try { + ModelApiResponse result = apiInstance.uploadFile(petId, additionalMetadata, file); + System.out.println(result); +} catch (ApiException e) { + System.err.println("Exception when calling PetApi#uploadFile"); + e.printStackTrace(); +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **petId** | **Long**| ID of pet to update | + **additionalMetadata** | **String**| Additional data to pass to server | [optional] [default to null] + **file** | **File**| file to upload | [optional] [default to null] + +### Return type + +[**ModelApiResponse**](ModelApiResponse.md) + +### Authorization + +[petstore_auth](../README.md#petstore_auth) + +### HTTP request headers + + - **Content-Type**: multipart/form-data + - **Accept**: application/json + + +# **uploadFileWithRequiredFile** +> ModelApiResponse uploadFileWithRequiredFile(petId, requiredFile, additionalMetadata) + +uploads an image (required) + +### Example +```java +// Import classes: +//import org.openapitools.client.ApiClient; +//import org.openapitools.client.ApiException; +//import org.openapitools.client.Configuration; +//import org.openapitools.client.auth.*; +//import org.openapitools.client.api.PetApi; + +ApiClient defaultClient = Configuration.getDefaultApiClient(); + +// Configure OAuth2 access token for authorization: petstore_auth +OAuth petstore_auth = (OAuth) defaultClient.getAuthentication("petstore_auth"); +petstore_auth.setAccessToken("YOUR ACCESS TOKEN"); + +PetApi apiInstance = new PetApi(); +Long petId = 56L; // Long | ID of pet to update +File requiredFile = new File("null"); // File | file to upload +String additionalMetadata = "null"; // String | Additional data to pass to server +try { + ModelApiResponse result = apiInstance.uploadFileWithRequiredFile(petId, requiredFile, additionalMetadata); + System.out.println(result); +} catch (ApiException e) { + System.err.println("Exception when calling PetApi#uploadFileWithRequiredFile"); + e.printStackTrace(); +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **petId** | **Long**| ID of pet to update | + **requiredFile** | **File**| file to upload | [default to null] + **additionalMetadata** | **String**| Additional data to pass to server | [optional] [default to null] + +### Return type + +[**ModelApiResponse**](ModelApiResponse.md) + +### Authorization + +[petstore_auth](../README.md#petstore_auth) + +### HTTP request headers + + - **Content-Type**: multipart/form-data + - **Accept**: application/json + diff --git a/samples/client/petstore/java/retrofit2-play26/docs/ReadOnlyFirst.md b/samples/client/petstore/java/retrofit2-play26/docs/ReadOnlyFirst.md new file mode 100644 index 0000000000..426b7cde95 --- /dev/null +++ b/samples/client/petstore/java/retrofit2-play26/docs/ReadOnlyFirst.md @@ -0,0 +1,11 @@ + +# ReadOnlyFirst + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**bar** | **String** | | [optional] +**baz** | **String** | | [optional] + + + diff --git a/samples/client/petstore/java/retrofit2-play26/docs/SpecialModelName.md b/samples/client/petstore/java/retrofit2-play26/docs/SpecialModelName.md new file mode 100644 index 0000000000..6cf53410ac --- /dev/null +++ b/samples/client/petstore/java/retrofit2-play26/docs/SpecialModelName.md @@ -0,0 +1,10 @@ + +# SpecialModelName + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**$specialPropertyName** | **Long** | | [optional] + + + diff --git a/samples/client/petstore/java/retrofit2-play26/docs/StoreApi.md b/samples/client/petstore/java/retrofit2-play26/docs/StoreApi.md new file mode 100644 index 0000000000..06886f6d56 --- /dev/null +++ b/samples/client/petstore/java/retrofit2-play26/docs/StoreApi.md @@ -0,0 +1,195 @@ +# StoreApi + +All URIs are relative to *http://petstore.swagger.io:80/v2* + +Method | HTTP request | Description +------------- | ------------- | ------------- +[**deleteOrder**](StoreApi.md#deleteOrder) | **DELETE** store/order/{order_id} | Delete purchase order by ID +[**getInventory**](StoreApi.md#getInventory) | **GET** store/inventory | Returns pet inventories by status +[**getOrderById**](StoreApi.md#getOrderById) | **GET** store/order/{order_id} | Find purchase order by ID +[**placeOrder**](StoreApi.md#placeOrder) | **POST** store/order | Place an order for a pet + + + +# **deleteOrder** +> deleteOrder(orderId) + +Delete purchase order by ID + +For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors + +### Example +```java +// Import classes: +//import org.openapitools.client.ApiException; +//import org.openapitools.client.api.StoreApi; + + +StoreApi apiInstance = new StoreApi(); +String orderId = "orderId_example"; // String | ID of the order that needs to be deleted +try { + apiInstance.deleteOrder(orderId); +} catch (ApiException e) { + System.err.println("Exception when calling StoreApi#deleteOrder"); + e.printStackTrace(); +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **orderId** | **String**| ID of the order that needs to be deleted | + +### Return type + +null (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: Not defined + + +# **getInventory** +> Map<String, Integer> getInventory() + +Returns pet inventories by status + +Returns a map of status codes to quantities + +### Example +```java +// Import classes: +//import org.openapitools.client.ApiClient; +//import org.openapitools.client.ApiException; +//import org.openapitools.client.Configuration; +//import org.openapitools.client.auth.*; +//import org.openapitools.client.api.StoreApi; + +ApiClient defaultClient = Configuration.getDefaultApiClient(); + +// Configure API key authorization: api_key +ApiKeyAuth api_key = (ApiKeyAuth) defaultClient.getAuthentication("api_key"); +api_key.setApiKey("YOUR API KEY"); +// Uncomment the following line to set a prefix for the API key, e.g. "Token" (defaults to null) +//api_key.setApiKeyPrefix("Token"); + +StoreApi apiInstance = new StoreApi(); +try { + Map result = apiInstance.getInventory(); + System.out.println(result); +} catch (ApiException e) { + System.err.println("Exception when calling StoreApi#getInventory"); + e.printStackTrace(); +} +``` + +### Parameters +This endpoint does not need any parameter. + +### Return type + +**Map<String, Integer>** + +### Authorization + +[api_key](../README.md#api_key) + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/json + + +# **getOrderById** +> Order getOrderById(orderId) + +Find purchase order by ID + +For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions + +### Example +```java +// Import classes: +//import org.openapitools.client.ApiException; +//import org.openapitools.client.api.StoreApi; + + +StoreApi apiInstance = new StoreApi(); +Long orderId = 56L; // Long | ID of pet that needs to be fetched +try { + Order result = apiInstance.getOrderById(orderId); + System.out.println(result); +} catch (ApiException e) { + System.err.println("Exception when calling StoreApi#getOrderById"); + e.printStackTrace(); +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **orderId** | **Long**| ID of pet that needs to be fetched | + +### Return type + +[**Order**](Order.md) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/xml, application/json + + +# **placeOrder** +> Order placeOrder(order) + +Place an order for a pet + +### Example +```java +// Import classes: +//import org.openapitools.client.ApiException; +//import org.openapitools.client.api.StoreApi; + + +StoreApi apiInstance = new StoreApi(); +Order order = new Order(); // Order | order placed for purchasing the pet +try { + Order result = apiInstance.placeOrder(order); + System.out.println(result); +} catch (ApiException e) { + System.err.println("Exception when calling StoreApi#placeOrder"); + e.printStackTrace(); +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **order** | [**Order**](Order.md)| order placed for purchasing the pet | + +### Return type + +[**Order**](Order.md) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/xml, application/json + diff --git a/samples/client/petstore/java/retrofit2-play26/docs/StringBooleanMap.md b/samples/client/petstore/java/retrofit2-play26/docs/StringBooleanMap.md new file mode 100644 index 0000000000..cac7afc80e --- /dev/null +++ b/samples/client/petstore/java/retrofit2-play26/docs/StringBooleanMap.md @@ -0,0 +1,9 @@ + +# StringBooleanMap + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- + + + diff --git a/samples/client/petstore/java/retrofit2-play26/docs/Tag.md b/samples/client/petstore/java/retrofit2-play26/docs/Tag.md new file mode 100644 index 0000000000..de6814b55d --- /dev/null +++ b/samples/client/petstore/java/retrofit2-play26/docs/Tag.md @@ -0,0 +1,11 @@ + +# Tag + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**id** | **Long** | | [optional] +**name** | **String** | | [optional] + + + diff --git a/samples/client/petstore/java/retrofit2-play26/docs/User.md b/samples/client/petstore/java/retrofit2-play26/docs/User.md new file mode 100644 index 0000000000..8b6753dd28 --- /dev/null +++ b/samples/client/petstore/java/retrofit2-play26/docs/User.md @@ -0,0 +1,17 @@ + +# User + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**id** | **Long** | | [optional] +**username** | **String** | | [optional] +**firstName** | **String** | | [optional] +**lastName** | **String** | | [optional] +**email** | **String** | | [optional] +**password** | **String** | | [optional] +**phone** | **String** | | [optional] +**userStatus** | **Integer** | User Status | [optional] + + + diff --git a/samples/client/petstore/java/retrofit2-play26/docs/UserApi.md b/samples/client/petstore/java/retrofit2-play26/docs/UserApi.md new file mode 100644 index 0000000000..795bb22a03 --- /dev/null +++ b/samples/client/petstore/java/retrofit2-play26/docs/UserApi.md @@ -0,0 +1,360 @@ +# UserApi + +All URIs are relative to *http://petstore.swagger.io:80/v2* + +Method | HTTP request | Description +------------- | ------------- | ------------- +[**createUser**](UserApi.md#createUser) | **POST** user | Create user +[**createUsersWithArrayInput**](UserApi.md#createUsersWithArrayInput) | **POST** user/createWithArray | Creates list of users with given input array +[**createUsersWithListInput**](UserApi.md#createUsersWithListInput) | **POST** user/createWithList | Creates list of users with given input array +[**deleteUser**](UserApi.md#deleteUser) | **DELETE** user/{username} | Delete user +[**getUserByName**](UserApi.md#getUserByName) | **GET** user/{username} | Get user by user name +[**loginUser**](UserApi.md#loginUser) | **GET** user/login | Logs user into the system +[**logoutUser**](UserApi.md#logoutUser) | **GET** user/logout | Logs out current logged in user session +[**updateUser**](UserApi.md#updateUser) | **PUT** user/{username} | Updated user + + + +# **createUser** +> createUser(user) + +Create user + +This can only be done by the logged in user. + +### Example +```java +// Import classes: +//import org.openapitools.client.ApiException; +//import org.openapitools.client.api.UserApi; + + +UserApi apiInstance = new UserApi(); +User user = new User(); // User | Created user object +try { + apiInstance.createUser(user); +} catch (ApiException e) { + System.err.println("Exception when calling UserApi#createUser"); + e.printStackTrace(); +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **user** | [**User**](User.md)| Created user object | + +### Return type + +null (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: Not defined + + +# **createUsersWithArrayInput** +> createUsersWithArrayInput(user) + +Creates list of users with given input array + +### Example +```java +// Import classes: +//import org.openapitools.client.ApiException; +//import org.openapitools.client.api.UserApi; + + +UserApi apiInstance = new UserApi(); +List user = Arrays.asList(new List()); // List | List of user object +try { + apiInstance.createUsersWithArrayInput(user); +} catch (ApiException e) { + System.err.println("Exception when calling UserApi#createUsersWithArrayInput"); + e.printStackTrace(); +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **user** | [**List<User>**](List.md)| List of user object | + +### Return type + +null (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: Not defined + + +# **createUsersWithListInput** +> createUsersWithListInput(user) + +Creates list of users with given input array + +### Example +```java +// Import classes: +//import org.openapitools.client.ApiException; +//import org.openapitools.client.api.UserApi; + + +UserApi apiInstance = new UserApi(); +List user = Arrays.asList(new List()); // List | List of user object +try { + apiInstance.createUsersWithListInput(user); +} catch (ApiException e) { + System.err.println("Exception when calling UserApi#createUsersWithListInput"); + e.printStackTrace(); +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **user** | [**List<User>**](List.md)| List of user object | + +### Return type + +null (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: Not defined + + +# **deleteUser** +> deleteUser(username) + +Delete user + +This can only be done by the logged in user. + +### Example +```java +// Import classes: +//import org.openapitools.client.ApiException; +//import org.openapitools.client.api.UserApi; + + +UserApi apiInstance = new UserApi(); +String username = "username_example"; // String | The name that needs to be deleted +try { + apiInstance.deleteUser(username); +} catch (ApiException e) { + System.err.println("Exception when calling UserApi#deleteUser"); + e.printStackTrace(); +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **username** | **String**| The name that needs to be deleted | + +### Return type + +null (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: Not defined + + +# **getUserByName** +> User getUserByName(username) + +Get user by user name + +### Example +```java +// Import classes: +//import org.openapitools.client.ApiException; +//import org.openapitools.client.api.UserApi; + + +UserApi apiInstance = new UserApi(); +String username = "username_example"; // String | The name that needs to be fetched. Use user1 for testing. +try { + User result = apiInstance.getUserByName(username); + System.out.println(result); +} catch (ApiException e) { + System.err.println("Exception when calling UserApi#getUserByName"); + e.printStackTrace(); +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **username** | **String**| The name that needs to be fetched. Use user1 for testing. | + +### Return type + +[**User**](User.md) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/xml, application/json + + +# **loginUser** +> String loginUser(username, password) + +Logs user into the system + +### Example +```java +// Import classes: +//import org.openapitools.client.ApiException; +//import org.openapitools.client.api.UserApi; + + +UserApi apiInstance = new UserApi(); +String username = "username_example"; // String | The user name for login +String password = "password_example"; // String | The password for login in clear text +try { + String result = apiInstance.loginUser(username, password); + System.out.println(result); +} catch (ApiException e) { + System.err.println("Exception when calling UserApi#loginUser"); + e.printStackTrace(); +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **username** | **String**| The user name for login | + **password** | **String**| The password for login in clear text | + +### Return type + +**String** + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/xml, application/json + + +# **logoutUser** +> logoutUser() + +Logs out current logged in user session + +### Example +```java +// Import classes: +//import org.openapitools.client.ApiException; +//import org.openapitools.client.api.UserApi; + + +UserApi apiInstance = new UserApi(); +try { + apiInstance.logoutUser(); +} catch (ApiException e) { + System.err.println("Exception when calling UserApi#logoutUser"); + e.printStackTrace(); +} +``` + +### Parameters +This endpoint does not need any parameter. + +### Return type + +null (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: Not defined + + +# **updateUser** +> updateUser(username, user) + +Updated user + +This can only be done by the logged in user. + +### Example +```java +// Import classes: +//import org.openapitools.client.ApiException; +//import org.openapitools.client.api.UserApi; + + +UserApi apiInstance = new UserApi(); +String username = "username_example"; // String | name that need to be deleted +User user = new User(); // User | Updated user object +try { + apiInstance.updateUser(username, user); +} catch (ApiException e) { + System.err.println("Exception when calling UserApi#updateUser"); + e.printStackTrace(); +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **username** | **String**| name that need to be deleted | + **user** | [**User**](User.md)| Updated user object | + +### Return type + +null (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: Not defined + diff --git a/samples/client/petstore/java/retrofit2-play26/git_push.sh b/samples/client/petstore/java/retrofit2-play26/git_push.sh new file mode 100644 index 0000000000..8442b80bb4 --- /dev/null +++ b/samples/client/petstore/java/retrofit2-play26/git_push.sh @@ -0,0 +1,52 @@ +#!/bin/sh +# ref: https://help.github.com/articles/adding-an-existing-project-to-github-using-the-command-line/ +# +# Usage example: /bin/sh ./git_push.sh wing328 openapi-pestore-perl "minor update" + +git_user_id=$1 +git_repo_id=$2 +release_note=$3 + +if [ "$git_user_id" = "" ]; then + git_user_id="GIT_USER_ID" + echo "[INFO] No command line input provided. Set \$git_user_id to $git_user_id" +fi + +if [ "$git_repo_id" = "" ]; then + git_repo_id="GIT_REPO_ID" + echo "[INFO] No command line input provided. Set \$git_repo_id to $git_repo_id" +fi + +if [ "$release_note" = "" ]; then + release_note="Minor update" + echo "[INFO] No command line input provided. Set \$release_note to $release_note" +fi + +# Initialize the local directory as a Git repository +git init + +# Adds the files in the local repository and stages them for commit. +git add . + +# Commits the tracked changes and prepares them to be pushed to a remote repository. +git commit -m "$release_note" + +# Sets the new remote +git_remote=`git remote` +if [ "$git_remote" = "" ]; then # git remote not defined + + if [ "$GIT_TOKEN" = "" ]; then + echo "[INFO] \$GIT_TOKEN (environment variable) is not set. Using the git credential in your environment." + git remote add origin https://github.com/${git_user_id}/${git_repo_id}.git + else + git remote add origin https://${git_user_id}:${GIT_TOKEN}@github.com/${git_user_id}/${git_repo_id}.git + fi + +fi + +git pull origin master + +# Pushes (Forces) the changes in the local repository up to the remote repository +echo "Git pushing to https://github.com/${git_user_id}/${git_repo_id}.git" +git push origin master 2>&1 | grep -v 'To https' + diff --git a/samples/client/petstore/java/retrofit2-play26/gradle.properties b/samples/client/petstore/java/retrofit2-play26/gradle.properties new file mode 100644 index 0000000000..05644f0754 --- /dev/null +++ b/samples/client/petstore/java/retrofit2-play26/gradle.properties @@ -0,0 +1,2 @@ +# Uncomment to build for Android +#target = android \ No newline at end of file diff --git a/samples/client/petstore/java/retrofit2-play26/gradle/wrapper/gradle-wrapper.jar b/samples/client/petstore/java/retrofit2-play26/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 0000000000..2c6137b878 Binary files /dev/null and b/samples/client/petstore/java/retrofit2-play26/gradle/wrapper/gradle-wrapper.jar differ diff --git a/samples/client/petstore/java/retrofit2-play26/gradle/wrapper/gradle-wrapper.properties b/samples/client/petstore/java/retrofit2-play26/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 0000000000..b7a3647395 --- /dev/null +++ b/samples/client/petstore/java/retrofit2-play26/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,6 @@ +#Tue May 17 23:08:05 CST 2016 +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-2.6-bin.zip diff --git a/samples/client/petstore/java/retrofit2-play26/gradlew b/samples/client/petstore/java/retrofit2-play26/gradlew new file mode 100644 index 0000000000..9d82f78915 --- /dev/null +++ b/samples/client/petstore/java/retrofit2-play26/gradlew @@ -0,0 +1,160 @@ +#!/usr/bin/env bash + +############################################################################## +## +## Gradle start up script for UN*X +## +############################################################################## + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS="" + +APP_NAME="Gradle" +APP_BASE_NAME=`basename "$0"` + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD="maximum" + +warn ( ) { + echo "$*" +} + +die ( ) { + echo + echo "$*" + echo + exit 1 +} + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +case "`uname`" in + CYGWIN* ) + cygwin=true + ;; + Darwin* ) + darwin=true + ;; + MINGW* ) + msys=true + ;; +esac + +# Attempt to set APP_HOME +# Resolve links: $0 may be a link +PRG="$0" +# Need this for relative symlinks. +while [ -h "$PRG" ] ; do + ls=`ls -ld "$PRG"` + link=`expr "$ls" : '.*-> \(.*\)$'` + if expr "$link" : '/.*' > /dev/null; then + PRG="$link" + else + PRG=`dirname "$PRG"`"/$link" + fi +done +SAVED="`pwd`" +cd "`dirname \"$PRG\"`/" >/dev/null +APP_HOME="`pwd -P`" +cd "$SAVED" >/dev/null + +CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD="$JAVA_HOME/jre/sh/java" + else + JAVACMD="$JAVA_HOME/bin/java" + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD="java" + which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." +fi + +# Increase the maximum file descriptors if we can. +if [ "$cygwin" = "false" -a "$darwin" = "false" ] ; then + MAX_FD_LIMIT=`ulimit -H -n` + if [ $? -eq 0 ] ; then + if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then + MAX_FD="$MAX_FD_LIMIT" + fi + ulimit -n $MAX_FD + if [ $? -ne 0 ] ; then + warn "Could not set maximum file descriptor limit: $MAX_FD" + fi + else + warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" + fi +fi + +# For Darwin, add options to specify how the application appears in the dock +if $darwin; then + GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" +fi + +# For Cygwin, switch paths to Windows format before running java +if $cygwin ; then + APP_HOME=`cygpath --path --mixed "$APP_HOME"` + CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` + JAVACMD=`cygpath --unix "$JAVACMD"` + + # We build the pattern for arguments to be converted via cygpath + ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` + SEP="" + for dir in $ROOTDIRSRAW ; do + ROOTDIRS="$ROOTDIRS$SEP$dir" + SEP="|" + done + OURCYGPATTERN="(^($ROOTDIRS))" + # Add a user-defined pattern to the cygpath arguments + if [ "$GRADLE_CYGPATTERN" != "" ] ; then + OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" + fi + # Now convert the arguments - kludge to limit ourselves to /bin/sh + i=0 + for arg in "$@" ; do + CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` + CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option + + if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition + eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` + else + eval `echo args$i`="\"$arg\"" + fi + i=$((i+1)) + done + case $i in + (0) set -- ;; + (1) set -- "$args0" ;; + (2) set -- "$args0" "$args1" ;; + (3) set -- "$args0" "$args1" "$args2" ;; + (4) set -- "$args0" "$args1" "$args2" "$args3" ;; + (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; + (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; + (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; + (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; + (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; + esac +fi + +# Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules +function splitJvmOpts() { + JVM_OPTS=("$@") +} +eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS +JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME" + +exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@" diff --git a/samples/client/petstore/java/retrofit2-play26/gradlew.bat b/samples/client/petstore/java/retrofit2-play26/gradlew.bat new file mode 100644 index 0000000000..5f192121eb --- /dev/null +++ b/samples/client/petstore/java/retrofit2-play26/gradlew.bat @@ -0,0 +1,90 @@ +@if "%DEBUG%" == "" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS= + +set DIRNAME=%~dp0 +if "%DIRNAME%" == "" set DIRNAME=. +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if "%ERRORLEVEL%" == "0" goto init + +echo. +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto init + +echo. +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:init +@rem Get command-line arguments, handling Windows variants + +if not "%OS%" == "Windows_NT" goto win9xME_args +if "%@eval[2+2]" == "4" goto 4NT_args + +:win9xME_args +@rem Slurp the command line arguments. +set CMD_LINE_ARGS= +set _SKIP=2 + +:win9xME_args_slurp +if "x%~1" == "x" goto execute + +set CMD_LINE_ARGS=%* +goto execute + +:4NT_args +@rem Get arguments from the 4NT Shell from JP Software +set CMD_LINE_ARGS=%$ + +:execute +@rem Setup the command line + +set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% + +:end +@rem End local scope for the variables with windows NT shell +if "%ERRORLEVEL%"=="0" goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 +exit /b 1 + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/samples/client/petstore/java/retrofit2-play26/pom.xml b/samples/client/petstore/java/retrofit2-play26/pom.xml new file mode 100644 index 0000000000..6957bc7ec6 --- /dev/null +++ b/samples/client/petstore/java/retrofit2-play26/pom.xml @@ -0,0 +1,288 @@ + + 4.0.0 + org.openapitools + petstore-java-client-retrofit2-play26 + jar + petstore-java-client-retrofit2-play26 + 1.0.0 + https://github.com/openapitools/openapi-generator + OpenAPI Java + + scm:git:git@github.com:openapitools/openapi-generator.git + scm:git:git@github.com:openapitools/openapi-generator.git + https://github.com/openapitools/openapi-generator + + + + + Unlicense + http://www.apache.org/licenses/LICENSE-2.0.html + repo + + + + + + OpenAPI + team@openapitools.org + OpenAPI + http://openapitools.org + + + + + + + org.apache.maven.plugins + maven-enforcer-plugin + 3.0.0-M1 + + + enforce-maven + + enforce + + + + + 2.2.0 + + + + + + + + org.apache.maven.plugins + maven-surefire-plugin + 2.12 + + + + loggerPath + conf/log4j.properties + + + -Xms512m -Xmx1500m + methods + pertest + + + + maven-dependency-plugin + + + package + + copy-dependencies + + + ${project.build.directory}/lib + + + + + + + + org.apache.maven.plugins + maven-jar-plugin + 2.2 + + + + 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-javadoc-plugin + 2.10.4 + + + attach-javadocs + + jar + + + + + + 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.squareup.retrofit2 + converter-gson + ${retrofit-version} + + + com.squareup.retrofit2 + retrofit + ${retrofit-version} + + + com.squareup.retrofit2 + converter-scalars + ${retrofit-version} + + + org.apache.oltu.oauth2 + org.apache.oltu.oauth2.client + ${oltu-version} + + + org.apache.oltu.oauth2 + common + + + + + io.gsonfire + gson-fire + ${gson-fire-version} + + + org.threeten + threetenbp + ${threetenbp-version} + + + + com.squareup.retrofit2 + converter-jackson + ${retrofit-version} + + + com.fasterxml.jackson.core + jackson-core + ${jackson-version} + + + com.fasterxml.jackson.core + jackson-annotations + ${jackson-version} + + + com.fasterxml.jackson.core + jackson-databind + ${jackson-version} + + + com.fasterxml.jackson.datatype + jackson-datatype-jsr310 + ${jackson-version} + + + com.typesafe.play + play-ahc-ws_2.12 + ${play-version} + + + javax.validation + validation-api + 1.1.0.Final + + + + junit + junit + ${junit-version} + test + + + + UTF-8 + 1.8 + ${java.version} + ${java.version} + 1.8.0 + 1.5.21 + 2.8.10 + 2.6.7 + 2.3.0 + 1.3.5 + 1.0.1 + 4.12 + + diff --git a/samples/client/petstore/java/retrofit2-play26/project/build.properties b/samples/client/petstore/java/retrofit2-play26/project/build.properties new file mode 100644 index 0000000000..5620cc502b --- /dev/null +++ b/samples/client/petstore/java/retrofit2-play26/project/build.properties @@ -0,0 +1 @@ +sbt.version=1.2.1 diff --git a/samples/client/petstore/java/retrofit2-play26/settings.gradle b/samples/client/petstore/java/retrofit2-play26/settings.gradle new file mode 100644 index 0000000000..5b3f1e5886 --- /dev/null +++ b/samples/client/petstore/java/retrofit2-play26/settings.gradle @@ -0,0 +1 @@ +rootProject.name = "petstore-java-client-retrofit2-play26" \ No newline at end of file diff --git a/samples/client/petstore/java/retrofit2-play26/src/main/AndroidManifest.xml b/samples/client/petstore/java/retrofit2-play26/src/main/AndroidManifest.xml new file mode 100644 index 0000000000..54fbcb3da1 --- /dev/null +++ b/samples/client/petstore/java/retrofit2-play26/src/main/AndroidManifest.xml @@ -0,0 +1,3 @@ + + + diff --git a/samples/client/petstore/java/retrofit2-play26/src/main/java/org/openapitools/client/ApiClient.java b/samples/client/petstore/java/retrofit2-play26/src/main/java/org/openapitools/client/ApiClient.java new file mode 100644 index 0000000000..6daa98296f --- /dev/null +++ b/samples/client/petstore/java/retrofit2-play26/src/main/java/org/openapitools/client/ApiClient.java @@ -0,0 +1,206 @@ +package org.openapitools.client; + +import java.io.File; +import java.io.IOException; +import java.lang.annotation.Annotation; +import java.lang.reflect.Type; +import java.nio.file.Files; +import java.nio.file.Paths; +import java.util.*; + +import com.fasterxml.jackson.databind.ObjectMapper; +import retrofit2.Converter; +import retrofit2.Retrofit; +import retrofit2.converter.scalars.ScalarsConverterFactory; +import retrofit2.converter.jackson.JacksonConverterFactory; + +import play.libs.Json; +import play.libs.ws.WSClient; + +import org.openapitools.client.Play26CallAdapterFactory; +import org.openapitools.client.Play26CallFactory; + +import okhttp3.Interceptor; +import okhttp3.ResponseBody; +import org.openapitools.client.auth.ApiKeyAuth; +import org.openapitools.client.auth.Authentication; + +/** + * API client + */ +public class ApiClient { + + /** Underlying HTTP-client */ + private WSClient wsClient; + + /** Creates HTTP call instances */ + private Play26CallFactory callFactory; + + /** Create {@link java.util.concurrent.CompletionStage} instances from HTTP calls */ + private Play26CallAdapterFactory callAdapterFactory; + + /** Supported auths */ + private Map authentications; + + /** API base path */ + private String basePath = "http://petstore.swagger.io:80/v2"; + + /** Default ObjectMapper */ + private ObjectMapper defaultMapper; + + public ApiClient(WSClient wsClient) { + this(); + this.wsClient = wsClient; + } + + public ApiClient() { + // Setup authentications (key: authentication name, value: authentication). + authentications = new HashMap<>(); + authentications.put("api_key", new ApiKeyAuth("header", "api_key")); + authentications.put("api_key_query", new ApiKeyAuth("query", "api_key_query")); + // authentications.put("http_basic_test", new HttpBasicAuth()); + // authentications.put("petstore_auth", new OAuth()); + // Prevent the authentications from being modified. + authentications = Collections.unmodifiableMap(authentications); + } + + /** + * Creates a retrofit2 client for given API interface + */ + public S createService(Class serviceClass) { + if(!basePath.endsWith("/")) { + basePath = basePath + "/"; + } + + Map extraHeaders = new HashMap<>(); + List extraQueryParams = new ArrayList<>(); + + for (String authName : authentications.keySet()) { + Authentication auth = authentications.get(authName); + if (auth == null) throw new RuntimeException("Authentication undefined: " + authName); + + auth.applyToParams(extraQueryParams, extraHeaders); + } + + if (callFactory == null) { + callFactory = new Play26CallFactory(wsClient, extraHeaders, extraQueryParams); + } + if (callAdapterFactory == null) { + callAdapterFactory = new Play26CallAdapterFactory(); + } + if (defaultMapper == null) { + defaultMapper = Json.mapper(); + } + + return new Retrofit.Builder() + .baseUrl(basePath) + .addConverterFactory(new FileConverter()) + .addConverterFactory(ScalarsConverterFactory.create()) + .addConverterFactory(JacksonConverterFactory.create(defaultMapper)) + .callFactory(callFactory) + .addCallAdapterFactory(callAdapterFactory) + .build() + .create(serviceClass); + } + + /** + * Helper method to set API base path + */ + public ApiClient setBasePath(String basePath) { + this.basePath = basePath; + return this; + } + + /** + * Get authentications (key: authentication name, value: authentication). + */ + 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 API key value for the first API key authentication. + */ + public ApiClient setApiKey(String apiKey) { + for (Authentication auth : authentications.values()) { + if (auth instanceof ApiKeyAuth) { + ((ApiKeyAuth) auth).setApiKey(apiKey); + return this; + } + } + + throw new RuntimeException("No API key authentication configured!"); + } + + /** + * Helper method to set API key prefix for the first API key authentication. + */ + public ApiClient setApiKeyPrefix(String apiKeyPrefix) { + for (Authentication auth : authentications.values()) { + if (auth instanceof ApiKeyAuth) { + ((ApiKeyAuth) auth).setApiKeyPrefix(apiKeyPrefix); + return this; + } + } + + throw new RuntimeException("No API key authentication configured!"); + } + + /** + * Helper method to set HTTP call instances factory + */ + public ApiClient setCallFactory(Play26CallFactory callFactory) { + this.callFactory = callFactory; + return this; + } + + /** + * Helper method to set {@link java.util.concurrent.CompletionStage} instances factory + */ + public ApiClient setCallAdapterFactory(Play26CallAdapterFactory callAdapterFactory) { + this.callAdapterFactory = callAdapterFactory; + return this; + } + + /** + * Helper method to set Jackson's {@link ObjectMapper} + */ + public ApiClient setObjectMapper(ObjectMapper mapper) { + this.defaultMapper = mapper; + return this; + } + + static class FileConverter extends Converter.Factory { + + @Override + public Converter responseBodyConverter(Type type, + Annotation[] annotations, Retrofit retrofit) { + + if (!File.class.getTypeName().equals(type.getTypeName())) { + return null; + } + + return new Converter() { + + @Override + public File convert(ResponseBody value) throws IOException { + + File file = File.createTempFile("retrofit-file", ".tmp"); + Files.write(Paths.get(file.getPath()), value.bytes()); + return file; + } + }; + } + } + +} diff --git a/samples/client/petstore/java/retrofit2-play26/src/main/java/org/openapitools/client/CollectionFormats.java b/samples/client/petstore/java/retrofit2-play26/src/main/java/org/openapitools/client/CollectionFormats.java new file mode 100644 index 0000000000..15cfcd1bd9 --- /dev/null +++ b/samples/client/petstore/java/retrofit2-play26/src/main/java/org/openapitools/client/CollectionFormats.java @@ -0,0 +1,95 @@ +package org.openapitools.client; + +import java.util.Arrays; +import java.util.List; + +public class CollectionFormats { + + public static class CSVParams { + + protected List params; + + public CSVParams() { + } + + public CSVParams(List params) { + this.params = params; + } + + public CSVParams(String... params) { + this.params = Arrays.asList(params); + } + + public List getParams() { + return params; + } + + public void setParams(List params) { + this.params = params; + } + + @Override + public String toString() { + return StringUtil.join(params.toArray(new String[0]), ","); + } + + } + + public static class SSVParams extends CSVParams { + + public SSVParams() { + } + + public SSVParams(List params) { + super(params); + } + + public SSVParams(String... params) { + super(params); + } + + @Override + public String toString() { + return StringUtil.join(params.toArray(new String[0]), " "); + } + } + + public static class TSVParams extends CSVParams { + + public TSVParams() { + } + + public TSVParams(List params) { + super(params); + } + + public TSVParams(String... params) { + super(params); + } + + @Override + public String toString() { + return StringUtil.join( params.toArray(new String[0]), "\t"); + } + } + + public static class PIPESParams extends CSVParams { + + public PIPESParams() { + } + + public PIPESParams(List params) { + super(params); + } + + public PIPESParams(String... params) { + super(params); + } + + @Override + public String toString() { + return StringUtil.join(params.toArray(new String[0]), "|"); + } + } + +} diff --git a/samples/client/petstore/java/retrofit2-play26/src/main/java/org/openapitools/client/Pair.java b/samples/client/petstore/java/retrofit2-play26/src/main/java/org/openapitools/client/Pair.java new file mode 100644 index 0000000000..18a0e96bfc --- /dev/null +++ b/samples/client/petstore/java/retrofit2-play26/src/main/java/org/openapitools/client/Pair.java @@ -0,0 +1,52 @@ +/* + * 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 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client; + + +public class Pair { + private String name = ""; + private String value = ""; + + public Pair (String name, String value) { + setName(name); + setValue(value); + } + + private void setName(String name) { + if (!isValidString(name)) return; + + this.name = name; + } + + private void setValue(String value) { + if (!isValidString(value)) return; + + this.value = value; + } + + public String getName() { + return this.name; + } + + public String getValue() { + return this.value; + } + + private boolean isValidString(String arg) { + if (arg == null) return false; + if (arg.trim().isEmpty()) return false; + + return true; + } +} diff --git a/samples/client/petstore/java/retrofit2-play26/src/main/java/org/openapitools/client/Play26CallAdapterFactory.java b/samples/client/petstore/java/retrofit2-play26/src/main/java/org/openapitools/client/Play26CallAdapterFactory.java new file mode 100644 index 0000000000..e3777b8eb7 --- /dev/null +++ b/samples/client/petstore/java/retrofit2-play26/src/main/java/org/openapitools/client/Play26CallAdapterFactory.java @@ -0,0 +1,116 @@ +package org.openapitools.client; + +import java.util.concurrent.CompletionStage; +import retrofit2.*; + +import java.lang.annotation.Annotation; +import java.lang.reflect.ParameterizedType; +import java.lang.reflect.Type; +import java.lang.reflect.WildcardType; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.CompletionStage; +import java.util.function.Function; + +/** + * Creates {@link CallAdapter} instances that convert {@link Call} into {@link java.util.concurrent.CompletionStage} + */ +public class Play26CallAdapterFactory extends CallAdapter.Factory { + + private Function exceptionConverter = Function.identity(); + + public Play26CallAdapterFactory() { + } + + public Play26CallAdapterFactory( + Function exceptionConverter) { + this.exceptionConverter = exceptionConverter; + } + + @Override + public CallAdapter get(Type returnType, Annotation[] annotations, Retrofit retrofit) { + if (!(returnType instanceof ParameterizedType)) { + return null; + } + + ParameterizedType type = (ParameterizedType) returnType; + if (type.getRawType() != CompletionStage.class) { + return null; + } + + return createAdapter((ParameterizedType) returnType); + } + + private CallAdapter> createAdapter(ParameterizedType returnType) { + // Get CompletionStage type argument + Type[] types = returnType.getActualTypeArguments(); + if (types.length != 1) { + throw new IllegalStateException("Must be exactly one type parameter"); + } + + Type resultType = types[0]; + Class rawTypeParam = getRawType(resultType); + + boolean includeResponse = false; + if (rawTypeParam == Response.class) { + if (!(resultType instanceof ParameterizedType)) { + throw new IllegalStateException("Response must be parameterized" + + " as Response"); + } + resultType = ((ParameterizedType) resultType).getActualTypeArguments()[0]; + includeResponse = true; + } + + return new ValueAdapter(resultType, includeResponse, exceptionConverter); + } + + /** + * Adpater that coverts values returned by API interface into CompletionStage + */ + private static final class ValueAdapter implements CallAdapter> { + + private final Type responseType; + private final boolean includeResponse; + private Function exceptionConverter; + + ValueAdapter(Type responseType, boolean includeResponse, + Function exceptionConverter) { + this.responseType = responseType; + this.includeResponse = includeResponse; + this.exceptionConverter = exceptionConverter; + } + + @Override + public Type responseType() { + return responseType; + } + + @Override + public CompletionStage adapt(final Call call) { + final CompletableFuture promise = new CompletableFuture(); + + call.enqueue(new Callback() { + + @Override + public void onResponse(Call call, Response response) { + if (response.isSuccessful()) { + if (includeResponse) { + promise.complete((R) response); + } else { + promise.complete(response.body()); + } + } else { + promise.completeExceptionally(exceptionConverter.apply(new HttpException(response))); + } + } + + @Override + public void onFailure(Call call, Throwable t) { + promise.completeExceptionally(t); + } + + }); + + return promise; + } + } +} diff --git a/samples/client/petstore/java/retrofit2-play26/src/main/java/org/openapitools/client/Play26CallFactory.java b/samples/client/petstore/java/retrofit2-play26/src/main/java/org/openapitools/client/Play26CallFactory.java new file mode 100644 index 0000000000..d320157bcf --- /dev/null +++ b/samples/client/petstore/java/retrofit2-play26/src/main/java/org/openapitools/client/Play26CallFactory.java @@ -0,0 +1,245 @@ +package org.openapitools.client; + +import okhttp3.*; +import okio.Buffer; +import okio.BufferedSource; +import play.libs.ws.WSClient; +import play.libs.ws.WSRequest; +import play.libs.ws.WSResponse; +import play.libs.ws.WSRequestFilter; + +import java.io.IOException; +import java.net.MalformedURLException; +import java.net.URI; +import java.net.URISyntaxException; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.concurrent.CompletionStage; +import java.util.concurrent.Executor; + +/** + * Creates {@link Call} instances that invoke underlying {@link WSClient} + */ +public class Play26CallFactory implements okhttp3.Call.Factory { + + /** PlayWS http client */ + private final WSClient wsClient; + + /** Extra headers to add to request */ + private Map extraHeaders = new HashMap<>(); + + /** Extra query parameters to add to request */ + private List extraQueryParams = new ArrayList<>(); + + /** Filters (interceptors) */ + private List filters = new ArrayList<>(); + + /** Executor for WSClient */ + private Executor executor; + + public Play26CallFactory(WSClient wsClient) { + this.wsClient = wsClient; + } + + public Play26CallFactory(WSClient wsClient, List filters) { + this.wsClient = wsClient; + this.filters.addAll(filters); + } + + public Play26CallFactory(WSClient wsClient, Map extraHeaders, + List extraQueryParams) { + this.wsClient = wsClient; + + this.extraHeaders.putAll(extraHeaders); + this.extraQueryParams.addAll(extraQueryParams); + } + + public Play26CallFactory withExecutor(Executor executor) { + this.executor = executor; + return this; + } + + @Override + public Call newCall(Request request) { + // add extra headers + Request.Builder rb = request.newBuilder(); + for (Map.Entry header : this.extraHeaders.entrySet()) { + rb.addHeader(header.getKey(), header.getValue()); + } + + // add extra query params + if (!this.extraQueryParams.isEmpty()) { + String newQuery = request.url().uri().getQuery(); + for (Pair queryParam : this.extraQueryParams) { + String param = String.format("%s=%s", queryParam.getName(), queryParam.getValue()); + if (newQuery == null) { + newQuery = param; + } else { + newQuery += "&" + param; + } + } + + URI newUri; + try { + newUri = new URI(request.url().uri().getScheme(), request.url().uri().getAuthority(), + request.url().uri().getPath(), newQuery, request.url().uri().getFragment()); + rb.url(newUri.toURL()); + } catch (MalformedURLException | URISyntaxException e) { + throw new RuntimeException("Error while updating an url", e); + } + } + + return new PlayWSCall(wsClient, this.executor, this.filters, rb.build()); + } + + /** + * Call implementation that delegates to Play WS Client + */ + static class PlayWSCall implements Call { + + private final WSClient wsClient; + private WSRequest wsRequest; + private List filters; + private Executor executor = java.util.concurrent.ForkJoinPool.commonPool(); + + private final Request request; + + public PlayWSCall(WSClient wsClient, Executor executor, List filters, Request request) { + this.wsClient = wsClient; + this.request = request; + this.filters = filters; + + if (executor != null) { + this.executor = executor; + } + } + + @Override + public Request request() { + return request; + } + + @Override + public void enqueue(final okhttp3.Callback responseCallback) { + final Call call = this; + final CompletionStage promise = executeAsync(); + + promise.whenCompleteAsync((v, t) -> { + if (t != null) { + if (t instanceof IOException) { + responseCallback.onFailure(call, (IOException) t); + } else { + responseCallback.onFailure(call, new IOException(t)); + } + } else { + try { + responseCallback.onResponse(call, PlayWSCall.this.toWSResponse(v)); + } catch (Exception e) { + responseCallback.onFailure(call, new IOException(e)); + } + } + }, this.executor); + } + + CompletionStage executeAsync() { + try { + HttpUrl url = request.url(); + wsRequest = wsClient.url(url.scheme()+ "://" + url.host() + ":" + url.port() + url.encodedPath()); + url.queryParameterNames().forEach(queryParam -> { + wsRequest.addQueryParameter(queryParam, url.queryParameter(queryParam)); + }); + addHeaders(wsRequest); + if (request.body() != null) { + addBody(wsRequest); + } + filters.stream().forEach(f -> wsRequest.setRequestFilter(f)); + + return wsRequest.execute(request.method()); + } catch (Exception e) { + throw new RuntimeException(e.getMessage(), e); + } + } + + private void addHeaders(WSRequest wsRequest) { + for(Map.Entry> entry : request.headers().toMultimap().entrySet()) { + List values = entry.getValue(); + for (String value : values) { + wsRequest.setHeader(entry.getKey(), value); + } + } + } + + private void addBody(WSRequest wsRequest) throws IOException { + MediaType mediaType = request.body().contentType(); + if (mediaType != null) { + wsRequest.setContentType(mediaType.toString()); + } + + Buffer buffer = new Buffer(); + request.body().writeTo(buffer); + wsRequest.setBody(buffer.inputStream()); + } + + private Response toWSResponse(final WSResponse r) { + final Response.Builder builder = new Response.Builder(); + builder.request(request) + .code(r.getStatus()) + .body(new ResponseBody() { + + @Override + public MediaType contentType() { + return r.getSingleHeader("Content-Type") + .map(MediaType::parse) + .orElse(null); + } + + @Override + public long contentLength() { + return r.asByteArray().length; + } + + @Override + public BufferedSource source() { + return new Buffer().write(r.asByteArray()); + } + }); + + for (Map.Entry> entry : r.getAllHeaders().entrySet()) { + for (String value : entry.getValue()) { + builder.addHeader(entry.getKey(), value); + } + } + + builder.message(r.getStatusText()); + builder.protocol(Protocol.HTTP_1_1); + return builder.build(); + } + + @Override + public Response execute() throws IOException { + throw new UnsupportedOperationException("Not supported"); + } + + @Override + public void cancel() { + throw new UnsupportedOperationException("Not supported"); + } + + @Override + public PlayWSCall clone() { + throw new UnsupportedOperationException("Not supported"); + } + + @Override + public boolean isExecuted() { + return false; + } + + @Override + public boolean isCanceled() { + return false; + } + } +} diff --git a/samples/client/petstore/java/retrofit2-play26/src/main/java/org/openapitools/client/RFC3339DateFormat.java b/samples/client/petstore/java/retrofit2-play26/src/main/java/org/openapitools/client/RFC3339DateFormat.java new file mode 100644 index 0000000000..4ed672bced --- /dev/null +++ b/samples/client/petstore/java/retrofit2-play26/src/main/java/org/openapitools/client/RFC3339DateFormat.java @@ -0,0 +1,32 @@ +/* + * 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 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package org.openapitools.client; + +import com.fasterxml.jackson.databind.util.ISO8601DateFormat; +import com.fasterxml.jackson.databind.util.ISO8601Utils; + +import java.text.FieldPosition; +import java.util.Date; + + +public class RFC3339DateFormat extends ISO8601DateFormat { + + // Same as ISO8601DateFormat but serializing milliseconds. + @Override + public StringBuffer format(Date date, StringBuffer toAppendTo, FieldPosition fieldPosition) { + String value = ISO8601Utils.format(date, true); + toAppendTo.append(value); + return toAppendTo; + } + +} \ No newline at end of file diff --git a/samples/client/petstore/java/retrofit2-play26/src/main/java/org/openapitools/client/StringUtil.java b/samples/client/petstore/java/retrofit2-play26/src/main/java/org/openapitools/client/StringUtil.java new file mode 100644 index 0000000000..b731bc530e --- /dev/null +++ b/samples/client/petstore/java/retrofit2-play26/src/main/java/org/openapitools/client/StringUtil.java @@ -0,0 +1,55 @@ +/* + * 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 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client; + + +public class StringUtil { + /** + * Check if the given array contains the given value (with case-insensitive comparison). + * + * @param array The array + * @param value The value to search + * @return true if the array contains the value + */ + public static boolean containsIgnoreCase(String[] array, String value) { + for (String str : array) { + if (value == null && str == null) return true; + if (value != null && value.equalsIgnoreCase(str)) return true; + } + return false; + } + + /** + * Join an array of strings with the given separator. + *

+ * Note: This might be replaced by utility method from commons-lang or guava someday + * if one of those libraries is added as dependency. + *

+ * + * @param array The array of strings + * @param separator The separator + * @return the resulting string + */ + public static String join(String[] array, String separator) { + int len = array.length; + if (len == 0) return ""; + + StringBuilder out = new StringBuilder(); + out.append(array[0]); + for (int i = 1; i < len; i++) { + out.append(separator).append(array[i]); + } + return out.toString(); + } +} diff --git a/samples/client/petstore/java/retrofit2-play26/src/main/java/org/openapitools/client/api/AnotherFakeApi.java b/samples/client/petstore/java/retrofit2-play26/src/main/java/org/openapitools/client/api/AnotherFakeApi.java new file mode 100644 index 0000000000..616c44b010 --- /dev/null +++ b/samples/client/petstore/java/retrofit2-play26/src/main/java/org/openapitools/client/api/AnotherFakeApi.java @@ -0,0 +1,39 @@ +package org.openapitools.client.api; + +import org.openapitools.client.CollectionFormats.*; + + + +import retrofit2.Call; +import retrofit2.http.*; + +import okhttp3.RequestBody; +import okhttp3.ResponseBody; +import okhttp3.MultipartBody; + +import org.openapitools.client.model.Client; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import java.util.concurrent.*; +import retrofit2.Response; + +public interface AnotherFakeApi { + /** + * To test special tags + * To test special tags and operation ID starting with number + * @param client client model (required) + * @return Call<Client> + */ + @Headers({ + "Content-Type:application/json" + }) + @PATCH("another-fake/dummy") + CompletionStage> call123testSpecialTags( + @retrofit2.http.Body Client client + ); + +} diff --git a/samples/client/petstore/java/retrofit2-play26/src/main/java/org/openapitools/client/api/FakeApi.java b/samples/client/petstore/java/retrofit2-play26/src/main/java/org/openapitools/client/api/FakeApi.java new file mode 100644 index 0000000000..1a9ea5cbba --- /dev/null +++ b/samples/client/petstore/java/retrofit2-play26/src/main/java/org/openapitools/client/api/FakeApi.java @@ -0,0 +1,190 @@ +package org.openapitools.client.api; + +import org.openapitools.client.CollectionFormats.*; + + + +import retrofit2.Call; +import retrofit2.http.*; + +import okhttp3.RequestBody; +import okhttp3.ResponseBody; +import okhttp3.MultipartBody; + +import java.math.BigDecimal; +import org.openapitools.client.model.Client; +import java.io.File; +import org.openapitools.client.model.FileSchemaTestClass; +import org.threeten.bp.LocalDate; +import org.threeten.bp.OffsetDateTime; +import org.openapitools.client.model.OuterComposite; +import org.openapitools.client.model.User; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import java.util.concurrent.*; +import retrofit2.Response; + +public interface FakeApi { + /** + * + * Test serialization of outer boolean types + * @param body Input boolean as post body (optional) + * @return Call<Boolean> + */ + @POST("fake/outer/boolean") + CompletionStage> fakeOuterBooleanSerialize( + @retrofit2.http.Body Boolean body + ); + + /** + * + * Test serialization of object with outer number type + * @param outerComposite Input composite as post body (optional) + * @return Call<OuterComposite> + */ + @POST("fake/outer/composite") + CompletionStage> fakeOuterCompositeSerialize( + @retrofit2.http.Body OuterComposite outerComposite + ); + + /** + * + * Test serialization of outer number types + * @param body Input number as post body (optional) + * @return Call<BigDecimal> + */ + @POST("fake/outer/number") + CompletionStage> fakeOuterNumberSerialize( + @retrofit2.http.Body BigDecimal body + ); + + /** + * + * Test serialization of outer string types + * @param body Input string as post body (optional) + * @return Call<String> + */ + @POST("fake/outer/string") + CompletionStage> fakeOuterStringSerialize( + @retrofit2.http.Body String body + ); + + /** + * + * For this test, the body for this request much reference a schema named `File`. + * @param fileSchemaTestClass (required) + * @return Call<Void> + */ + @Headers({ + "Content-Type:application/json" + }) + @PUT("fake/body-with-file-schema") + CompletionStage> testBodyWithFileSchema( + @retrofit2.http.Body FileSchemaTestClass fileSchemaTestClass + ); + + /** + * + * + * @param query (required) + * @param user (required) + * @return Call<Void> + */ + @Headers({ + "Content-Type:application/json" + }) + @PUT("fake/body-with-query-params") + CompletionStage> testBodyWithQueryParams( + @retrofit2.http.Query("query") String query, @retrofit2.http.Body User user + ); + + /** + * To test \"client\" model + * To test \"client\" model + * @param client client model (required) + * @return Call<Client> + */ + @Headers({ + "Content-Type:application/json" + }) + @PATCH("fake") + CompletionStage> testClientModel( + @retrofit2.http.Body Client client + ); + + /** + * Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + * Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + * @param number None (required) + * @param _double None (required) + * @param patternWithoutDelimiter None (required) + * @param _byte None (required) + * @param integer None (optional, default to null) + * @param int32 None (optional, default to null) + * @param int64 None (optional, default to null) + * @param _float None (optional, default to null) + * @param string None (optional, default to null) + * @param binary None (optional, default to null) + * @param date None (optional, default to null) + * @param dateTime None (optional, default to null) + * @param password None (optional, default to null) + * @param paramCallback None (optional, default to null) + * @return Call<Void> + */ + @retrofit2.http.FormUrlEncoded + @POST("fake") + CompletionStage> testEndpointParameters( + @retrofit2.http.Field("number") BigDecimal number, @retrofit2.http.Field("double") Double _double, @retrofit2.http.Field("pattern_without_delimiter") String patternWithoutDelimiter, @retrofit2.http.Field("byte") byte[] _byte, @retrofit2.http.Field("integer") Integer integer, @retrofit2.http.Field("int32") Integer int32, @retrofit2.http.Field("int64") Long int64, @retrofit2.http.Field("float") Float _float, @retrofit2.http.Field("string") String string, @retrofit2.http.Field("binary") MultipartBody.Part binary, @retrofit2.http.Field("date") LocalDate date, @retrofit2.http.Field("dateTime") OffsetDateTime dateTime, @retrofit2.http.Field("password") String password, @retrofit2.http.Field("callback") String paramCallback + ); + + /** + * To test enum parameters + * To test enum parameters + * @param enumHeaderStringArray Header parameter enum test (string array) (optional) + * @param enumHeaderString Header parameter enum test (string) (optional, default to -efg) + * @param enumQueryStringArray Query parameter enum test (string array) (optional) + * @param enumQueryString Query parameter enum test (string) (optional, default to -efg) + * @param enumQueryInteger Query parameter enum test (double) (optional) + * @param enumQueryDouble Query parameter enum test (double) (optional) + * @param enumFormStringArray Form parameter enum test (string array) (optional, default to $) + * @param enumFormString Form parameter enum test (string) (optional, default to -efg) + * @return Call<Void> + */ + @retrofit2.http.FormUrlEncoded + @GET("fake") + CompletionStage> testEnumParameters( + @retrofit2.http.Header("enum_header_string_array") List enumHeaderStringArray, @retrofit2.http.Header("enum_header_string") String enumHeaderString, @retrofit2.http.Query("enum_query_string_array") CSVParams enumQueryStringArray, @retrofit2.http.Query("enum_query_string") String enumQueryString, @retrofit2.http.Query("enum_query_integer") Integer enumQueryInteger, @retrofit2.http.Query("enum_query_double") Double enumQueryDouble, @retrofit2.http.Field("enum_form_string_array") List enumFormStringArray, @retrofit2.http.Field("enum_form_string") String enumFormString + ); + + /** + * test inline additionalProperties + * + * @param requestBody request body (required) + * @return Call<Void> + */ + @Headers({ + "Content-Type:application/json" + }) + @POST("fake/inline-additionalProperties") + CompletionStage> testInlineAdditionalProperties( + @retrofit2.http.Body Map requestBody + ); + + /** + * test json serialization of form data + * + * @param param field1 (required) + * @param param2 field2 (required) + * @return Call<Void> + */ + @retrofit2.http.FormUrlEncoded + @GET("fake/jsonFormData") + CompletionStage> testJsonFormData( + @retrofit2.http.Field("param") String param, @retrofit2.http.Field("param2") String param2 + ); + +} diff --git a/samples/client/petstore/java/retrofit2-play26/src/main/java/org/openapitools/client/api/FakeClassnameTags123Api.java b/samples/client/petstore/java/retrofit2-play26/src/main/java/org/openapitools/client/api/FakeClassnameTags123Api.java new file mode 100644 index 0000000000..c3db217e30 --- /dev/null +++ b/samples/client/petstore/java/retrofit2-play26/src/main/java/org/openapitools/client/api/FakeClassnameTags123Api.java @@ -0,0 +1,39 @@ +package org.openapitools.client.api; + +import org.openapitools.client.CollectionFormats.*; + + + +import retrofit2.Call; +import retrofit2.http.*; + +import okhttp3.RequestBody; +import okhttp3.ResponseBody; +import okhttp3.MultipartBody; + +import org.openapitools.client.model.Client; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import java.util.concurrent.*; +import retrofit2.Response; + +public interface FakeClassnameTags123Api { + /** + * To test class name in snake case + * To test class name in snake case + * @param client client model (required) + * @return Call<Client> + */ + @Headers({ + "Content-Type:application/json" + }) + @PATCH("fake_classname_test") + CompletionStage> testClassname( + @retrofit2.http.Body Client client + ); + +} diff --git a/samples/client/petstore/java/retrofit2-play26/src/main/java/org/openapitools/client/api/PetApi.java b/samples/client/petstore/java/retrofit2-play26/src/main/java/org/openapitools/client/api/PetApi.java new file mode 100644 index 0000000000..75fff9f67c --- /dev/null +++ b/samples/client/petstore/java/retrofit2-play26/src/main/java/org/openapitools/client/api/PetApi.java @@ -0,0 +1,142 @@ +package org.openapitools.client.api; + +import org.openapitools.client.CollectionFormats.*; + + + +import retrofit2.Call; +import retrofit2.http.*; + +import okhttp3.RequestBody; +import okhttp3.ResponseBody; +import okhttp3.MultipartBody; + +import java.io.File; +import org.openapitools.client.model.ModelApiResponse; +import org.openapitools.client.model.Pet; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import java.util.concurrent.*; +import retrofit2.Response; + +public interface PetApi { + /** + * Add a new pet to the store + * + * @param pet Pet object that needs to be added to the store (required) + * @return Call<Void> + */ + @Headers({ + "Content-Type:application/json" + }) + @POST("pet") + CompletionStage> addPet( + @retrofit2.http.Body Pet pet + ); + + /** + * Deletes a pet + * + * @param petId Pet id to delete (required) + * @param apiKey (optional) + * @return Call<Void> + */ + @DELETE("pet/{petId}") + CompletionStage> deletePet( + @retrofit2.http.Path("petId") Long petId, @retrofit2.http.Header("api_key") String apiKey + ); + + /** + * Finds Pets by status + * Multiple status values can be provided with comma separated strings + * @param status Status values that need to be considered for filter (required) + * @return Call<List<Pet>> + */ + @GET("pet/findByStatus") + CompletionStage>> findPetsByStatus( + @retrofit2.http.Query("status") CSVParams status + ); + + /** + * Finds Pets by tags + * Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. + * @param tags Tags to filter by (required) + * @return Call<List<Pet>> + */ + @GET("pet/findByTags") + CompletionStage>> findPetsByTags( + @retrofit2.http.Query("tags") CSVParams tags + ); + + /** + * Find pet by ID + * Returns a single pet + * @param petId ID of pet to return (required) + * @return Call<Pet> + */ + @GET("pet/{petId}") + CompletionStage> getPetById( + @retrofit2.http.Path("petId") Long petId + ); + + /** + * Update an existing pet + * + * @param pet Pet object that needs to be added to the store (required) + * @return Call<Void> + */ + @Headers({ + "Content-Type:application/json" + }) + @PUT("pet") + CompletionStage> updatePet( + @retrofit2.http.Body Pet pet + ); + + /** + * Updates a pet in the store with form data + * + * @param petId ID of pet that needs to be updated (required) + * @param name Updated name of the pet (optional, default to null) + * @param status Updated status of the pet (optional, default to null) + * @return Call<Void> + */ + @retrofit2.http.FormUrlEncoded + @POST("pet/{petId}") + CompletionStage> updatePetWithForm( + @retrofit2.http.Path("petId") Long petId, @retrofit2.http.Field("name") String name, @retrofit2.http.Field("status") String status + ); + + /** + * uploads an image + * + * @param petId ID of pet to update (required) + * @param additionalMetadata Additional data to pass to server (optional, default to null) + * @param file file to upload (optional, default to null) + * @return Call<ModelApiResponse> + */ + @retrofit2.http.Multipart + @POST("pet/{petId}/uploadImage") + CompletionStage> uploadFile( + @retrofit2.http.Path("petId") Long petId, @retrofit2.http.Part("additionalMetadata") String additionalMetadata, @retrofit2.http.Part("file") MultipartBody.Part file + ); + + /** + * uploads an image (required) + * + * @param petId ID of pet to update (required) + * @param requiredFile file to upload (required) + * @param additionalMetadata Additional data to pass to server (optional, default to null) + * @return Call<ModelApiResponse> + */ + @retrofit2.http.Multipart + @POST("fake/{petId}/uploadImageWithRequiredFile") + CompletionStage> uploadFileWithRequiredFile( + @retrofit2.http.Path("petId") Long petId, @retrofit2.http.Part("requiredFile") MultipartBody.Part requiredFile, @retrofit2.http.Part("additionalMetadata") String additionalMetadata + ); + +} diff --git a/samples/client/petstore/java/retrofit2-play26/src/main/java/org/openapitools/client/api/StoreApi.java b/samples/client/petstore/java/retrofit2-play26/src/main/java/org/openapitools/client/api/StoreApi.java new file mode 100644 index 0000000000..040c168020 --- /dev/null +++ b/samples/client/petstore/java/retrofit2-play26/src/main/java/org/openapitools/client/api/StoreApi.java @@ -0,0 +1,67 @@ +package org.openapitools.client.api; + +import org.openapitools.client.CollectionFormats.*; + + + +import retrofit2.Call; +import retrofit2.http.*; + +import okhttp3.RequestBody; +import okhttp3.ResponseBody; +import okhttp3.MultipartBody; + +import org.openapitools.client.model.Order; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import java.util.concurrent.*; +import retrofit2.Response; + +public interface StoreApi { + /** + * Delete purchase order by ID + * For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors + * @param orderId ID of the order that needs to be deleted (required) + * @return Call<Void> + */ + @DELETE("store/order/{order_id}") + CompletionStage> deleteOrder( + @retrofit2.http.Path("order_id") String orderId + ); + + /** + * Returns pet inventories by status + * Returns a map of status codes to quantities + * @return Call<Map<String, Integer>> + */ + @GET("store/inventory") + CompletionStage>> getInventory(); + + + /** + * Find purchase order by ID + * For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions + * @param orderId ID of pet that needs to be fetched (required) + * @return Call<Order> + */ + @GET("store/order/{order_id}") + CompletionStage> getOrderById( + @retrofit2.http.Path("order_id") Long orderId + ); + + /** + * Place an order for a pet + * + * @param order order placed for purchasing the pet (required) + * @return Call<Order> + */ + @POST("store/order") + CompletionStage> placeOrder( + @retrofit2.http.Body Order order + ); + +} diff --git a/samples/client/petstore/java/retrofit2-play26/src/main/java/org/openapitools/client/api/UserApi.java b/samples/client/petstore/java/retrofit2-play26/src/main/java/org/openapitools/client/api/UserApi.java new file mode 100644 index 0000000000..47f55e188e --- /dev/null +++ b/samples/client/petstore/java/retrofit2-play26/src/main/java/org/openapitools/client/api/UserApi.java @@ -0,0 +1,113 @@ +package org.openapitools.client.api; + +import org.openapitools.client.CollectionFormats.*; + + + +import retrofit2.Call; +import retrofit2.http.*; + +import okhttp3.RequestBody; +import okhttp3.ResponseBody; +import okhttp3.MultipartBody; + +import org.openapitools.client.model.User; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import java.util.concurrent.*; +import retrofit2.Response; + +public interface UserApi { + /** + * Create user + * This can only be done by the logged in user. + * @param user Created user object (required) + * @return Call<Void> + */ + @POST("user") + CompletionStage> createUser( + @retrofit2.http.Body User user + ); + + /** + * Creates list of users with given input array + * + * @param user List of user object (required) + * @return Call<Void> + */ + @POST("user/createWithArray") + CompletionStage> createUsersWithArrayInput( + @retrofit2.http.Body List user + ); + + /** + * Creates list of users with given input array + * + * @param user List of user object (required) + * @return Call<Void> + */ + @POST("user/createWithList") + CompletionStage> createUsersWithListInput( + @retrofit2.http.Body List user + ); + + /** + * Delete user + * This can only be done by the logged in user. + * @param username The name that needs to be deleted (required) + * @return Call<Void> + */ + @DELETE("user/{username}") + CompletionStage> deleteUser( + @retrofit2.http.Path("username") String username + ); + + /** + * Get user by user name + * + * @param username The name that needs to be fetched. Use user1 for testing. (required) + * @return Call<User> + */ + @GET("user/{username}") + CompletionStage> getUserByName( + @retrofit2.http.Path("username") String username + ); + + /** + * Logs user into the system + * + * @param username The user name for login (required) + * @param password The password for login in clear text (required) + * @return Call<String> + */ + @GET("user/login") + CompletionStage> loginUser( + @retrofit2.http.Query("username") String username, @retrofit2.http.Query("password") String password + ); + + /** + * Logs out current logged in user session + * + * @return Call<Void> + */ + @GET("user/logout") + CompletionStage> logoutUser(); + + + /** + * Updated user + * This can only be done by the logged in user. + * @param username name that need to be deleted (required) + * @param user Updated user object (required) + * @return Call<Void> + */ + @PUT("user/{username}") + CompletionStage> updateUser( + @retrofit2.http.Path("username") String username, @retrofit2.http.Body User user + ); + +} diff --git a/samples/client/petstore/java/retrofit2-play26/src/main/java/org/openapitools/client/auth/ApiKeyAuth.java b/samples/client/petstore/java/retrofit2-play26/src/main/java/org/openapitools/client/auth/ApiKeyAuth.java new file mode 100644 index 0000000000..a84e013524 --- /dev/null +++ b/samples/client/petstore/java/retrofit2-play26/src/main/java/org/openapitools/client/auth/ApiKeyAuth.java @@ -0,0 +1,78 @@ +/* + * 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 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.auth; + +import org.openapitools.client.Pair; + +import java.util.Map; +import java.util.List; + +/** + * Holds ApiKey auth info + */ + +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) { + 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); + } + } +} diff --git a/samples/client/petstore/java/retrofit2-play26/src/main/java/org/openapitools/client/auth/Authentication.java b/samples/client/petstore/java/retrofit2-play26/src/main/java/org/openapitools/client/auth/Authentication.java new file mode 100644 index 0000000000..ff392f0451 --- /dev/null +++ b/samples/client/petstore/java/retrofit2-play26/src/main/java/org/openapitools/client/auth/Authentication.java @@ -0,0 +1,29 @@ +/* + * 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 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.auth; + +import org.openapitools.client.Pair; + +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 + */ + void applyToParams(List queryParams, Map headerParams); +} diff --git a/samples/client/petstore/java/retrofit2-play26/src/main/java/org/openapitools/client/model/AdditionalPropertiesClass.java b/samples/client/petstore/java/retrofit2-play26/src/main/java/org/openapitools/client/model/AdditionalPropertiesClass.java new file mode 100644 index 0000000000..2f9a3c4eae --- /dev/null +++ b/samples/client/petstore/java/retrofit2-play26/src/main/java/org/openapitools/client/model/AdditionalPropertiesClass.java @@ -0,0 +1,136 @@ +/* + * 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 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import java.util.Objects; +import java.util.Arrays; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import javax.validation.constraints.*; +import javax.validation.Valid; + +/** + * AdditionalPropertiesClass + */ + +public class AdditionalPropertiesClass { + @JsonProperty("map_property") + private Map mapProperty = null; + + @JsonProperty("map_of_map_property") + private Map> mapOfMapProperty = null; + + public AdditionalPropertiesClass mapProperty(Map mapProperty) { + this.mapProperty = mapProperty; + return this; + } + + public AdditionalPropertiesClass putMapPropertyItem(String key, String mapPropertyItem) { + if (this.mapProperty == null) { + this.mapProperty = new HashMap<>(); + } + this.mapProperty.put(key, mapPropertyItem); + return this; + } + + /** + * Get mapProperty + * @return mapProperty + **/ + @ApiModelProperty(value = "") + public Map getMapProperty() { + return mapProperty; + } + + public void setMapProperty(Map mapProperty) { + this.mapProperty = mapProperty; + } + + public AdditionalPropertiesClass mapOfMapProperty(Map> mapOfMapProperty) { + this.mapOfMapProperty = mapOfMapProperty; + return this; + } + + public AdditionalPropertiesClass putMapOfMapPropertyItem(String key, Map mapOfMapPropertyItem) { + if (this.mapOfMapProperty == null) { + this.mapOfMapProperty = new HashMap<>(); + } + this.mapOfMapProperty.put(key, mapOfMapPropertyItem); + return this; + } + + /** + * Get mapOfMapProperty + * @return mapOfMapProperty + **/ + @Valid + @ApiModelProperty(value = "") + public Map> getMapOfMapProperty() { + return mapOfMapProperty; + } + + public void setMapOfMapProperty(Map> mapOfMapProperty) { + this.mapOfMapProperty = mapOfMapProperty; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + AdditionalPropertiesClass additionalPropertiesClass = (AdditionalPropertiesClass) o; + return Objects.equals(this.mapProperty, additionalPropertiesClass.mapProperty) && + Objects.equals(this.mapOfMapProperty, additionalPropertiesClass.mapOfMapProperty); + } + + @Override + public int hashCode() { + return Objects.hash(mapProperty, mapOfMapProperty); + } + + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class AdditionalPropertiesClass {\n"); + + sb.append(" mapProperty: ").append(toIndentedString(mapProperty)).append("\n"); + sb.append(" mapOfMapProperty: ").append(toIndentedString(mapOfMapProperty)).append("\n"); + 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 "); + } + +} + diff --git a/samples/client/petstore/java/retrofit2-play26/src/main/java/org/openapitools/client/model/Animal.java b/samples/client/petstore/java/retrofit2-play26/src/main/java/org/openapitools/client/model/Animal.java new file mode 100644 index 0000000000..96bdf02833 --- /dev/null +++ b/samples/client/petstore/java/retrofit2-play26/src/main/java/org/openapitools/client/model/Animal.java @@ -0,0 +1,125 @@ +/* + * 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 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import java.util.Objects; +import java.util.Arrays; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonSubTypes; +import com.fasterxml.jackson.annotation.JsonTypeInfo; +import com.fasterxml.jackson.annotation.JsonValue; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import javax.validation.constraints.*; +import javax.validation.Valid; + +/** + * Animal + */ + +@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "className", visible = true) +@JsonSubTypes({ + @JsonSubTypes.Type(value = Dog.class, name = "Dog"), + @JsonSubTypes.Type(value = Cat.class, name = "Cat"), +}) + +public class Animal { + @JsonProperty("className") + private String className = null; + + @JsonProperty("color") + private String color = "red"; + + public Animal className(String className) { + this.className = className; + return this; + } + + /** + * Get className + * @return className + **/ + @NotNull + @ApiModelProperty(required = true, value = "") + public String getClassName() { + return className; + } + + public void setClassName(String className) { + this.className = className; + } + + public Animal color(String color) { + this.color = color; + return this; + } + + /** + * Get color + * @return color + **/ + @ApiModelProperty(value = "") + public String getColor() { + return color; + } + + public void setColor(String color) { + this.color = color; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + Animal animal = (Animal) o; + return Objects.equals(this.className, animal.className) && + Objects.equals(this.color, animal.color); + } + + @Override + public int hashCode() { + return Objects.hash(className, color); + } + + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Animal {\n"); + + sb.append(" className: ").append(toIndentedString(className)).append("\n"); + sb.append(" color: ").append(toIndentedString(color)).append("\n"); + 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 "); + } + +} + diff --git a/samples/client/petstore/java/retrofit2-play26/src/main/java/org/openapitools/client/model/AnimalFarm.java b/samples/client/petstore/java/retrofit2-play26/src/main/java/org/openapitools/client/model/AnimalFarm.java new file mode 100644 index 0000000000..867cf78d4a --- /dev/null +++ b/samples/client/petstore/java/retrofit2-play26/src/main/java/org/openapitools/client/model/AnimalFarm.java @@ -0,0 +1,68 @@ +/* + * 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 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import java.util.Objects; +import java.util.Arrays; +import java.util.ArrayList; +import java.util.List; +import org.openapitools.client.model.Animal; +import javax.validation.constraints.*; +import javax.validation.Valid; + +/** + * AnimalFarm + */ + +public class AnimalFarm extends ArrayList { + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + return super.equals(o); + } + + @Override + public int hashCode() { + return Objects.hash(super.hashCode()); + } + + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class AnimalFarm {\n"); + sb.append(" ").append(toIndentedString(super.toString())).append("\n"); + 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 "); + } + +} + diff --git a/samples/client/petstore/java/retrofit2-play26/src/main/java/org/openapitools/client/model/ArrayOfArrayOfNumberOnly.java b/samples/client/petstore/java/retrofit2-play26/src/main/java/org/openapitools/client/model/ArrayOfArrayOfNumberOnly.java new file mode 100644 index 0000000000..3f30332d24 --- /dev/null +++ b/samples/client/petstore/java/retrofit2-play26/src/main/java/org/openapitools/client/model/ArrayOfArrayOfNumberOnly.java @@ -0,0 +1,105 @@ +/* + * 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 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import java.util.Objects; +import java.util.Arrays; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import java.math.BigDecimal; +import java.util.ArrayList; +import java.util.List; +import javax.validation.constraints.*; +import javax.validation.Valid; + +/** + * ArrayOfArrayOfNumberOnly + */ + +public class ArrayOfArrayOfNumberOnly { + @JsonProperty("ArrayArrayNumber") + private List> arrayArrayNumber = null; + + public ArrayOfArrayOfNumberOnly arrayArrayNumber(List> arrayArrayNumber) { + this.arrayArrayNumber = arrayArrayNumber; + return this; + } + + public ArrayOfArrayOfNumberOnly addArrayArrayNumberItem(List arrayArrayNumberItem) { + if (this.arrayArrayNumber == null) { + this.arrayArrayNumber = new ArrayList<>(); + } + this.arrayArrayNumber.add(arrayArrayNumberItem); + return this; + } + + /** + * Get arrayArrayNumber + * @return arrayArrayNumber + **/ + @Valid + @ApiModelProperty(value = "") + public List> getArrayArrayNumber() { + return arrayArrayNumber; + } + + public void setArrayArrayNumber(List> arrayArrayNumber) { + this.arrayArrayNumber = arrayArrayNumber; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + ArrayOfArrayOfNumberOnly arrayOfArrayOfNumberOnly = (ArrayOfArrayOfNumberOnly) o; + return Objects.equals(this.arrayArrayNumber, arrayOfArrayOfNumberOnly.arrayArrayNumber); + } + + @Override + public int hashCode() { + return Objects.hash(arrayArrayNumber); + } + + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class ArrayOfArrayOfNumberOnly {\n"); + + sb.append(" arrayArrayNumber: ").append(toIndentedString(arrayArrayNumber)).append("\n"); + 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 "); + } + +} + diff --git a/samples/client/petstore/java/retrofit2-play26/src/main/java/org/openapitools/client/model/ArrayOfNumberOnly.java b/samples/client/petstore/java/retrofit2-play26/src/main/java/org/openapitools/client/model/ArrayOfNumberOnly.java new file mode 100644 index 0000000000..6f9af6ac2c --- /dev/null +++ b/samples/client/petstore/java/retrofit2-play26/src/main/java/org/openapitools/client/model/ArrayOfNumberOnly.java @@ -0,0 +1,105 @@ +/* + * 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 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import java.util.Objects; +import java.util.Arrays; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import java.math.BigDecimal; +import java.util.ArrayList; +import java.util.List; +import javax.validation.constraints.*; +import javax.validation.Valid; + +/** + * ArrayOfNumberOnly + */ + +public class ArrayOfNumberOnly { + @JsonProperty("ArrayNumber") + private List arrayNumber = null; + + public ArrayOfNumberOnly arrayNumber(List arrayNumber) { + this.arrayNumber = arrayNumber; + return this; + } + + public ArrayOfNumberOnly addArrayNumberItem(BigDecimal arrayNumberItem) { + if (this.arrayNumber == null) { + this.arrayNumber = new ArrayList<>(); + } + this.arrayNumber.add(arrayNumberItem); + return this; + } + + /** + * Get arrayNumber + * @return arrayNumber + **/ + @Valid + @ApiModelProperty(value = "") + public List getArrayNumber() { + return arrayNumber; + } + + public void setArrayNumber(List arrayNumber) { + this.arrayNumber = arrayNumber; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + ArrayOfNumberOnly arrayOfNumberOnly = (ArrayOfNumberOnly) o; + return Objects.equals(this.arrayNumber, arrayOfNumberOnly.arrayNumber); + } + + @Override + public int hashCode() { + return Objects.hash(arrayNumber); + } + + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class ArrayOfNumberOnly {\n"); + + sb.append(" arrayNumber: ").append(toIndentedString(arrayNumber)).append("\n"); + 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 "); + } + +} + diff --git a/samples/client/petstore/java/retrofit2-play26/src/main/java/org/openapitools/client/model/ArrayTest.java b/samples/client/petstore/java/retrofit2-play26/src/main/java/org/openapitools/client/model/ArrayTest.java new file mode 100644 index 0000000000..1dab8f3356 --- /dev/null +++ b/samples/client/petstore/java/retrofit2-play26/src/main/java/org/openapitools/client/model/ArrayTest.java @@ -0,0 +1,168 @@ +/* + * 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 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import java.util.Objects; +import java.util.Arrays; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import java.util.ArrayList; +import java.util.List; +import org.openapitools.client.model.ReadOnlyFirst; +import javax.validation.constraints.*; +import javax.validation.Valid; + +/** + * ArrayTest + */ + +public class ArrayTest { + @JsonProperty("array_of_string") + private List arrayOfString = null; + + @JsonProperty("array_array_of_integer") + private List> arrayArrayOfInteger = null; + + @JsonProperty("array_array_of_model") + private List> arrayArrayOfModel = null; + + public ArrayTest arrayOfString(List arrayOfString) { + this.arrayOfString = arrayOfString; + return this; + } + + public ArrayTest addArrayOfStringItem(String arrayOfStringItem) { + if (this.arrayOfString == null) { + this.arrayOfString = new ArrayList<>(); + } + this.arrayOfString.add(arrayOfStringItem); + return this; + } + + /** + * Get arrayOfString + * @return arrayOfString + **/ + @ApiModelProperty(value = "") + public List getArrayOfString() { + return arrayOfString; + } + + public void setArrayOfString(List arrayOfString) { + this.arrayOfString = arrayOfString; + } + + public ArrayTest arrayArrayOfInteger(List> arrayArrayOfInteger) { + this.arrayArrayOfInteger = arrayArrayOfInteger; + return this; + } + + public ArrayTest addArrayArrayOfIntegerItem(List arrayArrayOfIntegerItem) { + if (this.arrayArrayOfInteger == null) { + this.arrayArrayOfInteger = new ArrayList<>(); + } + this.arrayArrayOfInteger.add(arrayArrayOfIntegerItem); + return this; + } + + /** + * Get arrayArrayOfInteger + * @return arrayArrayOfInteger + **/ + @Valid + @ApiModelProperty(value = "") + public List> getArrayArrayOfInteger() { + return arrayArrayOfInteger; + } + + public void setArrayArrayOfInteger(List> arrayArrayOfInteger) { + this.arrayArrayOfInteger = arrayArrayOfInteger; + } + + public ArrayTest arrayArrayOfModel(List> arrayArrayOfModel) { + this.arrayArrayOfModel = arrayArrayOfModel; + return this; + } + + public ArrayTest addArrayArrayOfModelItem(List arrayArrayOfModelItem) { + if (this.arrayArrayOfModel == null) { + this.arrayArrayOfModel = new ArrayList<>(); + } + this.arrayArrayOfModel.add(arrayArrayOfModelItem); + return this; + } + + /** + * Get arrayArrayOfModel + * @return arrayArrayOfModel + **/ + @Valid + @ApiModelProperty(value = "") + public List> getArrayArrayOfModel() { + return arrayArrayOfModel; + } + + public void setArrayArrayOfModel(List> arrayArrayOfModel) { + this.arrayArrayOfModel = arrayArrayOfModel; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + ArrayTest arrayTest = (ArrayTest) o; + return Objects.equals(this.arrayOfString, arrayTest.arrayOfString) && + Objects.equals(this.arrayArrayOfInteger, arrayTest.arrayArrayOfInteger) && + Objects.equals(this.arrayArrayOfModel, arrayTest.arrayArrayOfModel); + } + + @Override + public int hashCode() { + return Objects.hash(arrayOfString, arrayArrayOfInteger, arrayArrayOfModel); + } + + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class ArrayTest {\n"); + + sb.append(" arrayOfString: ").append(toIndentedString(arrayOfString)).append("\n"); + sb.append(" arrayArrayOfInteger: ").append(toIndentedString(arrayArrayOfInteger)).append("\n"); + sb.append(" arrayArrayOfModel: ").append(toIndentedString(arrayArrayOfModel)).append("\n"); + 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 "); + } + +} + diff --git a/samples/client/petstore/java/retrofit2-play26/src/main/java/org/openapitools/client/model/Capitalization.java b/samples/client/petstore/java/retrofit2-play26/src/main/java/org/openapitools/client/model/Capitalization.java new file mode 100644 index 0000000000..93ab5bb6ad --- /dev/null +++ b/samples/client/petstore/java/retrofit2-play26/src/main/java/org/openapitools/client/model/Capitalization.java @@ -0,0 +1,208 @@ +/* + * 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 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import java.util.Objects; +import java.util.Arrays; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import javax.validation.constraints.*; +import javax.validation.Valid; + +/** + * Capitalization + */ + +public class Capitalization { + @JsonProperty("smallCamel") + private String smallCamel = null; + + @JsonProperty("CapitalCamel") + private String capitalCamel = null; + + @JsonProperty("small_Snake") + private String smallSnake = null; + + @JsonProperty("Capital_Snake") + private String capitalSnake = null; + + @JsonProperty("SCA_ETH_Flow_Points") + private String scAETHFlowPoints = null; + + @JsonProperty("ATT_NAME") + private String ATT_NAME = null; + + public Capitalization smallCamel(String smallCamel) { + this.smallCamel = smallCamel; + return this; + } + + /** + * Get smallCamel + * @return smallCamel + **/ + @ApiModelProperty(value = "") + public String getSmallCamel() { + return smallCamel; + } + + public void setSmallCamel(String smallCamel) { + this.smallCamel = smallCamel; + } + + public Capitalization capitalCamel(String capitalCamel) { + this.capitalCamel = capitalCamel; + return this; + } + + /** + * Get capitalCamel + * @return capitalCamel + **/ + @ApiModelProperty(value = "") + public String getCapitalCamel() { + return capitalCamel; + } + + public void setCapitalCamel(String capitalCamel) { + this.capitalCamel = capitalCamel; + } + + public Capitalization smallSnake(String smallSnake) { + this.smallSnake = smallSnake; + return this; + } + + /** + * Get smallSnake + * @return smallSnake + **/ + @ApiModelProperty(value = "") + public String getSmallSnake() { + return smallSnake; + } + + public void setSmallSnake(String smallSnake) { + this.smallSnake = smallSnake; + } + + public Capitalization capitalSnake(String capitalSnake) { + this.capitalSnake = capitalSnake; + return this; + } + + /** + * Get capitalSnake + * @return capitalSnake + **/ + @ApiModelProperty(value = "") + public String getCapitalSnake() { + return capitalSnake; + } + + public void setCapitalSnake(String capitalSnake) { + this.capitalSnake = capitalSnake; + } + + public Capitalization scAETHFlowPoints(String scAETHFlowPoints) { + this.scAETHFlowPoints = scAETHFlowPoints; + return this; + } + + /** + * Get scAETHFlowPoints + * @return scAETHFlowPoints + **/ + @ApiModelProperty(value = "") + public String getScAETHFlowPoints() { + return scAETHFlowPoints; + } + + public void setScAETHFlowPoints(String scAETHFlowPoints) { + this.scAETHFlowPoints = scAETHFlowPoints; + } + + public Capitalization ATT_NAME(String ATT_NAME) { + this.ATT_NAME = ATT_NAME; + return this; + } + + /** + * Name of the pet + * @return ATT_NAME + **/ + @ApiModelProperty(value = "Name of the pet ") + public String getATTNAME() { + return ATT_NAME; + } + + public void setATTNAME(String ATT_NAME) { + this.ATT_NAME = ATT_NAME; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + Capitalization capitalization = (Capitalization) o; + return Objects.equals(this.smallCamel, capitalization.smallCamel) && + Objects.equals(this.capitalCamel, capitalization.capitalCamel) && + Objects.equals(this.smallSnake, capitalization.smallSnake) && + Objects.equals(this.capitalSnake, capitalization.capitalSnake) && + Objects.equals(this.scAETHFlowPoints, capitalization.scAETHFlowPoints) && + Objects.equals(this.ATT_NAME, capitalization.ATT_NAME); + } + + @Override + public int hashCode() { + return Objects.hash(smallCamel, capitalCamel, smallSnake, capitalSnake, scAETHFlowPoints, ATT_NAME); + } + + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Capitalization {\n"); + + sb.append(" smallCamel: ").append(toIndentedString(smallCamel)).append("\n"); + sb.append(" capitalCamel: ").append(toIndentedString(capitalCamel)).append("\n"); + sb.append(" smallSnake: ").append(toIndentedString(smallSnake)).append("\n"); + sb.append(" capitalSnake: ").append(toIndentedString(capitalSnake)).append("\n"); + sb.append(" scAETHFlowPoints: ").append(toIndentedString(scAETHFlowPoints)).append("\n"); + sb.append(" ATT_NAME: ").append(toIndentedString(ATT_NAME)).append("\n"); + 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 "); + } + +} + diff --git a/samples/client/petstore/java/retrofit2-play26/src/main/java/org/openapitools/client/model/Cat.java b/samples/client/petstore/java/retrofit2-play26/src/main/java/org/openapitools/client/model/Cat.java new file mode 100644 index 0000000000..bed98769d8 --- /dev/null +++ b/samples/client/petstore/java/retrofit2-play26/src/main/java/org/openapitools/client/model/Cat.java @@ -0,0 +1,95 @@ +/* + * 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 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import java.util.Objects; +import java.util.Arrays; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import org.openapitools.client.model.Animal; +import javax.validation.constraints.*; +import javax.validation.Valid; + +/** + * Cat + */ + +public class Cat extends Animal { + @JsonProperty("declawed") + private Boolean declawed = null; + + public Cat declawed(Boolean declawed) { + this.declawed = declawed; + return this; + } + + /** + * Get declawed + * @return declawed + **/ + @ApiModelProperty(value = "") + public Boolean getDeclawed() { + return declawed; + } + + public void setDeclawed(Boolean declawed) { + this.declawed = declawed; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + Cat cat = (Cat) o; + return Objects.equals(this.declawed, cat.declawed) && + super.equals(o); + } + + @Override + public int hashCode() { + return Objects.hash(declawed, super.hashCode()); + } + + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Cat {\n"); + sb.append(" ").append(toIndentedString(super.toString())).append("\n"); + sb.append(" declawed: ").append(toIndentedString(declawed)).append("\n"); + 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 "); + } + +} + diff --git a/samples/client/petstore/java/retrofit2-play26/src/main/java/org/openapitools/client/model/Category.java b/samples/client/petstore/java/retrofit2-play26/src/main/java/org/openapitools/client/model/Category.java new file mode 100644 index 0000000000..7a34207246 --- /dev/null +++ b/samples/client/petstore/java/retrofit2-play26/src/main/java/org/openapitools/client/model/Category.java @@ -0,0 +1,116 @@ +/* + * 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 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import java.util.Objects; +import java.util.Arrays; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import javax.validation.constraints.*; +import javax.validation.Valid; + +/** + * Category + */ + +public class Category { + @JsonProperty("id") + private Long id = null; + + @JsonProperty("name") + private String name = null; + + public Category id(Long id) { + this.id = id; + return this; + } + + /** + * Get id + * @return id + **/ + @ApiModelProperty(value = "") + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public Category name(String name) { + this.name = name; + return this; + } + + /** + * Get name + * @return name + **/ + @ApiModelProperty(value = "") + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + Category category = (Category) o; + return Objects.equals(this.id, category.id) && + Objects.equals(this.name, category.name); + } + + @Override + public int hashCode() { + return Objects.hash(id, name); + } + + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Category {\n"); + + sb.append(" id: ").append(toIndentedString(id)).append("\n"); + sb.append(" name: ").append(toIndentedString(name)).append("\n"); + 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 "); + } + +} + diff --git a/samples/client/petstore/java/retrofit2-play26/src/main/java/org/openapitools/client/model/ClassModel.java b/samples/client/petstore/java/retrofit2-play26/src/main/java/org/openapitools/client/model/ClassModel.java new file mode 100644 index 0000000000..2f4d3aadd3 --- /dev/null +++ b/samples/client/petstore/java/retrofit2-play26/src/main/java/org/openapitools/client/model/ClassModel.java @@ -0,0 +1,94 @@ +/* + * 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 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import java.util.Objects; +import java.util.Arrays; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import javax.validation.constraints.*; +import javax.validation.Valid; + +/** + * Model for testing model with \"_class\" property + */ +@ApiModel(description = "Model for testing model with \"_class\" property") + +public class ClassModel { + @JsonProperty("_class") + private String propertyClass = null; + + public ClassModel propertyClass(String propertyClass) { + this.propertyClass = propertyClass; + return this; + } + + /** + * Get propertyClass + * @return propertyClass + **/ + @ApiModelProperty(value = "") + public String getPropertyClass() { + return propertyClass; + } + + public void setPropertyClass(String propertyClass) { + this.propertyClass = propertyClass; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + ClassModel classModel = (ClassModel) o; + return Objects.equals(this.propertyClass, classModel.propertyClass); + } + + @Override + public int hashCode() { + return Objects.hash(propertyClass); + } + + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class ClassModel {\n"); + + sb.append(" propertyClass: ").append(toIndentedString(propertyClass)).append("\n"); + 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 "); + } + +} + diff --git a/samples/client/petstore/java/retrofit2-play26/src/main/java/org/openapitools/client/model/Client.java b/samples/client/petstore/java/retrofit2-play26/src/main/java/org/openapitools/client/model/Client.java new file mode 100644 index 0000000000..c6efc5a533 --- /dev/null +++ b/samples/client/petstore/java/retrofit2-play26/src/main/java/org/openapitools/client/model/Client.java @@ -0,0 +1,93 @@ +/* + * 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 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import java.util.Objects; +import java.util.Arrays; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import javax.validation.constraints.*; +import javax.validation.Valid; + +/** + * Client + */ + +public class Client { + @JsonProperty("client") + private String client = null; + + public Client client(String client) { + this.client = client; + return this; + } + + /** + * Get client + * @return client + **/ + @ApiModelProperty(value = "") + public String getClient() { + return client; + } + + public void setClient(String client) { + this.client = client; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + Client client = (Client) o; + return Objects.equals(this.client, client.client); + } + + @Override + public int hashCode() { + return Objects.hash(client); + } + + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Client {\n"); + + sb.append(" client: ").append(toIndentedString(client)).append("\n"); + 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 "); + } + +} + diff --git a/samples/client/petstore/java/retrofit2-play26/src/main/java/org/openapitools/client/model/Dog.java b/samples/client/petstore/java/retrofit2-play26/src/main/java/org/openapitools/client/model/Dog.java new file mode 100644 index 0000000000..29210dd068 --- /dev/null +++ b/samples/client/petstore/java/retrofit2-play26/src/main/java/org/openapitools/client/model/Dog.java @@ -0,0 +1,95 @@ +/* + * 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 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import java.util.Objects; +import java.util.Arrays; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import org.openapitools.client.model.Animal; +import javax.validation.constraints.*; +import javax.validation.Valid; + +/** + * Dog + */ + +public class Dog extends Animal { + @JsonProperty("breed") + private String breed = null; + + public Dog breed(String breed) { + this.breed = breed; + return this; + } + + /** + * Get breed + * @return breed + **/ + @ApiModelProperty(value = "") + public String getBreed() { + return breed; + } + + public void setBreed(String breed) { + this.breed = breed; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + Dog dog = (Dog) o; + return Objects.equals(this.breed, dog.breed) && + super.equals(o); + } + + @Override + public int hashCode() { + return Objects.hash(breed, super.hashCode()); + } + + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Dog {\n"); + sb.append(" ").append(toIndentedString(super.toString())).append("\n"); + sb.append(" breed: ").append(toIndentedString(breed)).append("\n"); + 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 "); + } + +} + diff --git a/samples/client/petstore/java/retrofit2-play26/src/main/java/org/openapitools/client/model/EnumArrays.java b/samples/client/petstore/java/retrofit2-play26/src/main/java/org/openapitools/client/model/EnumArrays.java new file mode 100644 index 0000000000..32a694a4de --- /dev/null +++ b/samples/client/petstore/java/retrofit2-play26/src/main/java/org/openapitools/client/model/EnumArrays.java @@ -0,0 +1,196 @@ +/* + * 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 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import java.util.Objects; +import java.util.Arrays; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import java.util.ArrayList; +import java.util.List; +import javax.validation.constraints.*; +import javax.validation.Valid; + +/** + * EnumArrays + */ + +public class EnumArrays { + /** + * Gets or Sets justSymbol + */ + public enum JustSymbolEnum { + GREATER_THAN_OR_EQUAL_TO(">="), + + DOLLAR("$"); + + private String value; + + JustSymbolEnum(String value) { + this.value = value; + } + + @JsonValue + public String getValue() { + return value; + } + + @Override + public String toString() { + return String.valueOf(value); + } + + @JsonCreator + public static JustSymbolEnum fromValue(String text) { + for (JustSymbolEnum b : JustSymbolEnum.values()) { + if (String.valueOf(b.value).equals(text)) { + return b; + } + } + throw new IllegalArgumentException("Unexpected value '" + text + "'"); + } + } + + @JsonProperty("just_symbol") + private JustSymbolEnum justSymbol = null; + + /** + * Gets or Sets arrayEnum + */ + public enum ArrayEnumEnum { + FISH("fish"), + + CRAB("crab"); + + private String value; + + ArrayEnumEnum(String value) { + this.value = value; + } + + @JsonValue + public String getValue() { + return value; + } + + @Override + public String toString() { + return String.valueOf(value); + } + + @JsonCreator + public static ArrayEnumEnum fromValue(String text) { + for (ArrayEnumEnum b : ArrayEnumEnum.values()) { + if (String.valueOf(b.value).equals(text)) { + return b; + } + } + throw new IllegalArgumentException("Unexpected value '" + text + "'"); + } + } + + @JsonProperty("array_enum") + private List arrayEnum = null; + + public EnumArrays justSymbol(JustSymbolEnum justSymbol) { + this.justSymbol = justSymbol; + return this; + } + + /** + * Get justSymbol + * @return justSymbol + **/ + @ApiModelProperty(value = "") + public JustSymbolEnum getJustSymbol() { + return justSymbol; + } + + public void setJustSymbol(JustSymbolEnum justSymbol) { + this.justSymbol = justSymbol; + } + + public EnumArrays arrayEnum(List arrayEnum) { + this.arrayEnum = arrayEnum; + return this; + } + + public EnumArrays addArrayEnumItem(ArrayEnumEnum arrayEnumItem) { + if (this.arrayEnum == null) { + this.arrayEnum = new ArrayList<>(); + } + this.arrayEnum.add(arrayEnumItem); + return this; + } + + /** + * Get arrayEnum + * @return arrayEnum + **/ + @ApiModelProperty(value = "") + public List getArrayEnum() { + return arrayEnum; + } + + public void setArrayEnum(List arrayEnum) { + this.arrayEnum = arrayEnum; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + EnumArrays enumArrays = (EnumArrays) o; + return Objects.equals(this.justSymbol, enumArrays.justSymbol) && + Objects.equals(this.arrayEnum, enumArrays.arrayEnum); + } + + @Override + public int hashCode() { + return Objects.hash(justSymbol, arrayEnum); + } + + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class EnumArrays {\n"); + + sb.append(" justSymbol: ").append(toIndentedString(justSymbol)).append("\n"); + sb.append(" arrayEnum: ").append(toIndentedString(arrayEnum)).append("\n"); + 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 "); + } + +} + diff --git a/samples/client/petstore/java/retrofit2-play26/src/main/java/org/openapitools/client/model/EnumClass.java b/samples/client/petstore/java/retrofit2-play26/src/main/java/org/openapitools/client/model/EnumClass.java new file mode 100644 index 0000000000..5ba02415fc --- /dev/null +++ b/samples/client/petstore/java/retrofit2-play26/src/main/java/org/openapitools/client/model/EnumClass.java @@ -0,0 +1,61 @@ +/* + * 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 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import java.util.Objects; +import java.util.Arrays; +import javax.validation.constraints.*; +import javax.validation.Valid; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; + +/** + * Gets or Sets EnumClass + */ +public enum EnumClass { + + _ABC("_abc"), + + _EFG("-efg"), + + _XYZ_("(xyz)"); + + private String value; + + EnumClass(String value) { + this.value = value; + } + + @JsonValue + public String getValue() { + return value; + } + + @Override + public String toString() { + return String.valueOf(value); + } + + @JsonCreator + public static EnumClass fromValue(String text) { + for (EnumClass b : EnumClass.values()) { + if (String.valueOf(b.value).equals(text)) { + return b; + } + } + throw new IllegalArgumentException("Unexpected value '" + text + "'"); + } +} + diff --git a/samples/client/petstore/java/retrofit2-play26/src/main/java/org/openapitools/client/model/EnumTest.java b/samples/client/petstore/java/retrofit2-play26/src/main/java/org/openapitools/client/model/EnumTest.java new file mode 100644 index 0000000000..2d835a86ed --- /dev/null +++ b/samples/client/petstore/java/retrofit2-play26/src/main/java/org/openapitools/client/model/EnumTest.java @@ -0,0 +1,332 @@ +/* + * 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 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import java.util.Objects; +import java.util.Arrays; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import org.openapitools.client.model.OuterEnum; +import javax.validation.constraints.*; +import javax.validation.Valid; + +/** + * EnumTest + */ + +public class EnumTest { + /** + * Gets or Sets enumString + */ + public enum EnumStringEnum { + UPPER("UPPER"), + + LOWER("lower"), + + EMPTY(""); + + private String value; + + EnumStringEnum(String value) { + this.value = value; + } + + @JsonValue + public String getValue() { + return value; + } + + @Override + public String toString() { + return String.valueOf(value); + } + + @JsonCreator + public static EnumStringEnum fromValue(String text) { + for (EnumStringEnum b : EnumStringEnum.values()) { + if (String.valueOf(b.value).equals(text)) { + return b; + } + } + throw new IllegalArgumentException("Unexpected value '" + text + "'"); + } + } + + @JsonProperty("enum_string") + private EnumStringEnum enumString = null; + + /** + * Gets or Sets enumStringRequired + */ + public enum EnumStringRequiredEnum { + UPPER("UPPER"), + + LOWER("lower"), + + EMPTY(""); + + private String value; + + EnumStringRequiredEnum(String value) { + this.value = value; + } + + @JsonValue + public String getValue() { + return value; + } + + @Override + public String toString() { + return String.valueOf(value); + } + + @JsonCreator + public static EnumStringRequiredEnum fromValue(String text) { + for (EnumStringRequiredEnum b : EnumStringRequiredEnum.values()) { + if (String.valueOf(b.value).equals(text)) { + return b; + } + } + throw new IllegalArgumentException("Unexpected value '" + text + "'"); + } + } + + @JsonProperty("enum_string_required") + private EnumStringRequiredEnum enumStringRequired = null; + + /** + * Gets or Sets enumInteger + */ + public enum EnumIntegerEnum { + NUMBER_1(1), + + NUMBER_MINUS_1(-1); + + private Integer value; + + EnumIntegerEnum(Integer value) { + this.value = value; + } + + @JsonValue + public Integer getValue() { + return value; + } + + @Override + public String toString() { + return String.valueOf(value); + } + + @JsonCreator + public static EnumIntegerEnum fromValue(String text) { + for (EnumIntegerEnum b : EnumIntegerEnum.values()) { + if (String.valueOf(b.value).equals(text)) { + return b; + } + } + throw new IllegalArgumentException("Unexpected value '" + text + "'"); + } + } + + @JsonProperty("enum_integer") + private EnumIntegerEnum enumInteger = null; + + /** + * Gets or Sets enumNumber + */ + public enum EnumNumberEnum { + NUMBER_1_DOT_1(1.1), + + NUMBER_MINUS_1_DOT_2(-1.2); + + private Double value; + + EnumNumberEnum(Double value) { + this.value = value; + } + + @JsonValue + public Double getValue() { + return value; + } + + @Override + public String toString() { + return String.valueOf(value); + } + + @JsonCreator + public static EnumNumberEnum fromValue(String text) { + for (EnumNumberEnum b : EnumNumberEnum.values()) { + if (String.valueOf(b.value).equals(text)) { + return b; + } + } + throw new IllegalArgumentException("Unexpected value '" + text + "'"); + } + } + + @JsonProperty("enum_number") + private EnumNumberEnum enumNumber = null; + + @JsonProperty("outerEnum") + private OuterEnum outerEnum = null; + + public EnumTest enumString(EnumStringEnum enumString) { + this.enumString = enumString; + return this; + } + + /** + * Get enumString + * @return enumString + **/ + @ApiModelProperty(value = "") + public EnumStringEnum getEnumString() { + return enumString; + } + + public void setEnumString(EnumStringEnum enumString) { + this.enumString = enumString; + } + + public EnumTest enumStringRequired(EnumStringRequiredEnum enumStringRequired) { + this.enumStringRequired = enumStringRequired; + return this; + } + + /** + * Get enumStringRequired + * @return enumStringRequired + **/ + @NotNull + @ApiModelProperty(required = true, value = "") + public EnumStringRequiredEnum getEnumStringRequired() { + return enumStringRequired; + } + + public void setEnumStringRequired(EnumStringRequiredEnum enumStringRequired) { + this.enumStringRequired = enumStringRequired; + } + + public EnumTest enumInteger(EnumIntegerEnum enumInteger) { + this.enumInteger = enumInteger; + return this; + } + + /** + * Get enumInteger + * @return enumInteger + **/ + @ApiModelProperty(value = "") + public EnumIntegerEnum getEnumInteger() { + return enumInteger; + } + + public void setEnumInteger(EnumIntegerEnum enumInteger) { + this.enumInteger = enumInteger; + } + + public EnumTest enumNumber(EnumNumberEnum enumNumber) { + this.enumNumber = enumNumber; + return this; + } + + /** + * Get enumNumber + * @return enumNumber + **/ + @ApiModelProperty(value = "") + public EnumNumberEnum getEnumNumber() { + return enumNumber; + } + + public void setEnumNumber(EnumNumberEnum enumNumber) { + this.enumNumber = enumNumber; + } + + public EnumTest outerEnum(OuterEnum outerEnum) { + this.outerEnum = outerEnum; + return this; + } + + /** + * Get outerEnum + * @return outerEnum + **/ + @Valid + @ApiModelProperty(value = "") + public OuterEnum getOuterEnum() { + return outerEnum; + } + + public void setOuterEnum(OuterEnum outerEnum) { + this.outerEnum = outerEnum; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + EnumTest enumTest = (EnumTest) o; + return Objects.equals(this.enumString, enumTest.enumString) && + Objects.equals(this.enumStringRequired, enumTest.enumStringRequired) && + Objects.equals(this.enumInteger, enumTest.enumInteger) && + Objects.equals(this.enumNumber, enumTest.enumNumber) && + Objects.equals(this.outerEnum, enumTest.outerEnum); + } + + @Override + public int hashCode() { + return Objects.hash(enumString, enumStringRequired, enumInteger, enumNumber, outerEnum); + } + + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class EnumTest {\n"); + + sb.append(" enumString: ").append(toIndentedString(enumString)).append("\n"); + sb.append(" enumStringRequired: ").append(toIndentedString(enumStringRequired)).append("\n"); + sb.append(" enumInteger: ").append(toIndentedString(enumInteger)).append("\n"); + sb.append(" enumNumber: ").append(toIndentedString(enumNumber)).append("\n"); + sb.append(" outerEnum: ").append(toIndentedString(outerEnum)).append("\n"); + 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 "); + } + +} + diff --git a/samples/client/petstore/java/retrofit2-play26/src/main/java/org/openapitools/client/model/FileSchemaTestClass.java b/samples/client/petstore/java/retrofit2-play26/src/main/java/org/openapitools/client/model/FileSchemaTestClass.java new file mode 100644 index 0000000000..0733417b91 --- /dev/null +++ b/samples/client/petstore/java/retrofit2-play26/src/main/java/org/openapitools/client/model/FileSchemaTestClass.java @@ -0,0 +1,128 @@ +/* + * 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 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import java.util.Objects; +import java.util.Arrays; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import java.util.ArrayList; +import java.util.List; +import javax.validation.constraints.*; +import javax.validation.Valid; + +/** + * FileSchemaTestClass + */ + +public class FileSchemaTestClass { + @JsonProperty("file") + private java.io.File file = null; + + @JsonProperty("files") + private List files = null; + + public FileSchemaTestClass file(java.io.File file) { + this.file = file; + return this; + } + + /** + * Get file + * @return file + **/ + @Valid + @ApiModelProperty(value = "") + public java.io.File getFile() { + return file; + } + + public void setFile(java.io.File file) { + this.file = file; + } + + public FileSchemaTestClass files(List files) { + this.files = files; + return this; + } + + public FileSchemaTestClass addFilesItem(java.io.File filesItem) { + if (this.files == null) { + this.files = new ArrayList<>(); + } + this.files.add(filesItem); + return this; + } + + /** + * Get files + * @return files + **/ + @Valid + @ApiModelProperty(value = "") + public List getFiles() { + return files; + } + + public void setFiles(List files) { + this.files = files; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + FileSchemaTestClass fileSchemaTestClass = (FileSchemaTestClass) o; + return Objects.equals(this.file, fileSchemaTestClass.file) && + Objects.equals(this.files, fileSchemaTestClass.files); + } + + @Override + public int hashCode() { + return Objects.hash(file, files); + } + + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class FileSchemaTestClass {\n"); + + sb.append(" file: ").append(toIndentedString(file)).append("\n"); + sb.append(" files: ").append(toIndentedString(files)).append("\n"); + 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 "); + } + +} + diff --git a/samples/client/petstore/java/retrofit2-play26/src/main/java/org/openapitools/client/model/FormatTest.java b/samples/client/petstore/java/retrofit2-play26/src/main/java/org/openapitools/client/model/FormatTest.java new file mode 100644 index 0000000000..0b0d291563 --- /dev/null +++ b/samples/client/petstore/java/retrofit2-play26/src/main/java/org/openapitools/client/model/FormatTest.java @@ -0,0 +1,393 @@ +/* + * 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 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import java.util.Objects; +import java.util.Arrays; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import java.io.File; +import java.math.BigDecimal; +import java.util.UUID; +import org.threeten.bp.LocalDate; +import org.threeten.bp.OffsetDateTime; +import javax.validation.constraints.*; +import javax.validation.Valid; + +/** + * FormatTest + */ + +public class FormatTest { + @JsonProperty("integer") + private Integer integer = null; + + @JsonProperty("int32") + private Integer int32 = null; + + @JsonProperty("int64") + private Long int64 = null; + + @JsonProperty("number") + private BigDecimal number = null; + + @JsonProperty("float") + private Float _float = null; + + @JsonProperty("double") + private Double _double = null; + + @JsonProperty("string") + private String string = null; + + @JsonProperty("byte") + private byte[] _byte = null; + + @JsonProperty("binary") + private File binary = null; + + @JsonProperty("date") + private LocalDate date = null; + + @JsonProperty("dateTime") + private OffsetDateTime dateTime = null; + + @JsonProperty("uuid") + private UUID uuid = null; + + @JsonProperty("password") + private String password = null; + + public FormatTest integer(Integer integer) { + this.integer = integer; + return this; + } + + /** + * Get integer + * minimum: 10 + * maximum: 100 + * @return integer + **/ + @Min(10) @Max(100) @ApiModelProperty(value = "") + public Integer getInteger() { + return integer; + } + + public void setInteger(Integer integer) { + this.integer = integer; + } + + public FormatTest int32(Integer int32) { + this.int32 = int32; + return this; + } + + /** + * Get int32 + * minimum: 20 + * maximum: 200 + * @return int32 + **/ + @Min(20) @Max(200) @ApiModelProperty(value = "") + public Integer getInt32() { + return int32; + } + + public void setInt32(Integer int32) { + this.int32 = int32; + } + + public FormatTest int64(Long int64) { + this.int64 = int64; + return this; + } + + /** + * Get int64 + * @return int64 + **/ + @ApiModelProperty(value = "") + public Long getInt64() { + return int64; + } + + public void setInt64(Long int64) { + this.int64 = int64; + } + + public FormatTest number(BigDecimal number) { + this.number = number; + return this; + } + + /** + * Get number + * minimum: 32.1 + * maximum: 543.2 + * @return number + **/ + @NotNull + @Valid + @DecimalMin("32.1") @DecimalMax("543.2") @ApiModelProperty(required = true, value = "") + public BigDecimal getNumber() { + return number; + } + + public void setNumber(BigDecimal number) { + this.number = number; + } + + public FormatTest _float(Float _float) { + this._float = _float; + return this; + } + + /** + * Get _float + * minimum: 54.3 + * maximum: 987.6 + * @return _float + **/ + @DecimalMin("54.3") @DecimalMax("987.6") @ApiModelProperty(value = "") + public Float getFloat() { + return _float; + } + + public void setFloat(Float _float) { + this._float = _float; + } + + public FormatTest _double(Double _double) { + this._double = _double; + return this; + } + + /** + * Get _double + * minimum: 67.8 + * maximum: 123.4 + * @return _double + **/ + @DecimalMin("67.8") @DecimalMax("123.4") @ApiModelProperty(value = "") + public Double getDouble() { + return _double; + } + + public void setDouble(Double _double) { + this._double = _double; + } + + public FormatTest string(String string) { + this.string = string; + return this; + } + + /** + * Get string + * @return string + **/ + @Pattern(regexp="/[a-z]/i") @ApiModelProperty(value = "") + public String getString() { + return string; + } + + public void setString(String string) { + this.string = string; + } + + public FormatTest _byte(byte[] _byte) { + this._byte = _byte; + return this; + } + + /** + * Get _byte + * @return _byte + **/ + @NotNull + @Pattern(regexp="^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$") @ApiModelProperty(required = true, value = "") + public byte[] getByte() { + return _byte; + } + + public void setByte(byte[] _byte) { + this._byte = _byte; + } + + public FormatTest binary(File binary) { + this.binary = binary; + return this; + } + + /** + * Get binary + * @return binary + **/ + @Valid + @ApiModelProperty(value = "") + public File getBinary() { + return binary; + } + + public void setBinary(File binary) { + this.binary = binary; + } + + public FormatTest date(LocalDate date) { + this.date = date; + return this; + } + + /** + * Get date + * @return date + **/ + @NotNull + @Valid + @ApiModelProperty(required = true, value = "") + public LocalDate getDate() { + return date; + } + + public void setDate(LocalDate date) { + this.date = date; + } + + public FormatTest dateTime(OffsetDateTime dateTime) { + this.dateTime = dateTime; + return this; + } + + /** + * Get dateTime + * @return dateTime + **/ + @Valid + @ApiModelProperty(value = "") + public OffsetDateTime getDateTime() { + return dateTime; + } + + public void setDateTime(OffsetDateTime dateTime) { + this.dateTime = dateTime; + } + + public FormatTest uuid(UUID uuid) { + this.uuid = uuid; + return this; + } + + /** + * Get uuid + * @return uuid + **/ + @Valid + @ApiModelProperty(value = "") + public UUID getUuid() { + return uuid; + } + + public void setUuid(UUID uuid) { + this.uuid = uuid; + } + + public FormatTest password(String password) { + this.password = password; + return this; + } + + /** + * Get password + * @return password + **/ + @NotNull + @Size(min=10,max=64) @ApiModelProperty(required = true, value = "") + public String getPassword() { + return password; + } + + public void setPassword(String password) { + this.password = password; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + FormatTest formatTest = (FormatTest) o; + return Objects.equals(this.integer, formatTest.integer) && + Objects.equals(this.int32, formatTest.int32) && + Objects.equals(this.int64, formatTest.int64) && + Objects.equals(this.number, formatTest.number) && + Objects.equals(this._float, formatTest._float) && + Objects.equals(this._double, formatTest._double) && + Objects.equals(this.string, formatTest.string) && + Arrays.equals(this._byte, formatTest._byte) && + Objects.equals(this.binary, formatTest.binary) && + Objects.equals(this.date, formatTest.date) && + Objects.equals(this.dateTime, formatTest.dateTime) && + Objects.equals(this.uuid, formatTest.uuid) && + Objects.equals(this.password, formatTest.password); + } + + @Override + public int hashCode() { + return Objects.hash(integer, int32, int64, number, _float, _double, string, Arrays.hashCode(_byte), binary, date, dateTime, uuid, password); + } + + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class FormatTest {\n"); + + sb.append(" integer: ").append(toIndentedString(integer)).append("\n"); + sb.append(" int32: ").append(toIndentedString(int32)).append("\n"); + sb.append(" int64: ").append(toIndentedString(int64)).append("\n"); + sb.append(" number: ").append(toIndentedString(number)).append("\n"); + sb.append(" _float: ").append(toIndentedString(_float)).append("\n"); + sb.append(" _double: ").append(toIndentedString(_double)).append("\n"); + sb.append(" string: ").append(toIndentedString(string)).append("\n"); + sb.append(" _byte: ").append(toIndentedString(_byte)).append("\n"); + sb.append(" binary: ").append(toIndentedString(binary)).append("\n"); + sb.append(" date: ").append(toIndentedString(date)).append("\n"); + sb.append(" dateTime: ").append(toIndentedString(dateTime)).append("\n"); + sb.append(" uuid: ").append(toIndentedString(uuid)).append("\n"); + sb.append(" password: ").append(toIndentedString(password)).append("\n"); + 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 "); + } + +} + diff --git a/samples/client/petstore/java/retrofit2-play26/src/main/java/org/openapitools/client/model/HasOnlyReadOnly.java b/samples/client/petstore/java/retrofit2-play26/src/main/java/org/openapitools/client/model/HasOnlyReadOnly.java new file mode 100644 index 0000000000..dee87cf7fb --- /dev/null +++ b/samples/client/petstore/java/retrofit2-play26/src/main/java/org/openapitools/client/model/HasOnlyReadOnly.java @@ -0,0 +1,98 @@ +/* + * 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 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import java.util.Objects; +import java.util.Arrays; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import javax.validation.constraints.*; +import javax.validation.Valid; + +/** + * HasOnlyReadOnly + */ + +public class HasOnlyReadOnly { + @JsonProperty("bar") + private String bar = null; + + @JsonProperty("foo") + private String foo = null; + + /** + * Get bar + * @return bar + **/ + @ApiModelProperty(value = "") + public String getBar() { + return bar; + } + + /** + * Get foo + * @return foo + **/ + @ApiModelProperty(value = "") + public String getFoo() { + return foo; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + HasOnlyReadOnly hasOnlyReadOnly = (HasOnlyReadOnly) o; + return Objects.equals(this.bar, hasOnlyReadOnly.bar) && + Objects.equals(this.foo, hasOnlyReadOnly.foo); + } + + @Override + public int hashCode() { + return Objects.hash(bar, foo); + } + + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class HasOnlyReadOnly {\n"); + + sb.append(" bar: ").append(toIndentedString(bar)).append("\n"); + sb.append(" foo: ").append(toIndentedString(foo)).append("\n"); + 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 "); + } + +} + diff --git a/samples/client/petstore/java/retrofit2-play26/src/main/java/org/openapitools/client/model/MapTest.java b/samples/client/petstore/java/retrofit2-play26/src/main/java/org/openapitools/client/model/MapTest.java new file mode 100644 index 0000000000..aca072ecc7 --- /dev/null +++ b/samples/client/petstore/java/retrofit2-play26/src/main/java/org/openapitools/client/model/MapTest.java @@ -0,0 +1,227 @@ +/* + * 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 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import java.util.Objects; +import java.util.Arrays; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import org.openapitools.client.model.StringBooleanMap; +import javax.validation.constraints.*; +import javax.validation.Valid; + +/** + * MapTest + */ + +public class MapTest { + @JsonProperty("map_map_of_string") + private Map> mapMapOfString = null; + + /** + * Gets or Sets inner + */ + public enum InnerEnum { + UPPER("UPPER"), + + LOWER("lower"); + + private String value; + + InnerEnum(String value) { + this.value = value; + } + + @JsonValue + public String getValue() { + return value; + } + + @Override + public String toString() { + return String.valueOf(value); + } + + @JsonCreator + public static InnerEnum fromValue(String text) { + for (InnerEnum b : InnerEnum.values()) { + if (String.valueOf(b.value).equals(text)) { + return b; + } + } + throw new IllegalArgumentException("Unexpected value '" + text + "'"); + } + } + + @JsonProperty("map_of_enum_string") + private Map mapOfEnumString = null; + + @JsonProperty("direct_map") + private Map directMap = null; + + @JsonProperty("indirect_map") + private StringBooleanMap indirectMap = null; + + public MapTest mapMapOfString(Map> mapMapOfString) { + this.mapMapOfString = mapMapOfString; + return this; + } + + public MapTest putMapMapOfStringItem(String key, Map mapMapOfStringItem) { + if (this.mapMapOfString == null) { + this.mapMapOfString = new HashMap<>(); + } + this.mapMapOfString.put(key, mapMapOfStringItem); + return this; + } + + /** + * Get mapMapOfString + * @return mapMapOfString + **/ + @Valid + @ApiModelProperty(value = "") + public Map> getMapMapOfString() { + return mapMapOfString; + } + + public void setMapMapOfString(Map> mapMapOfString) { + this.mapMapOfString = mapMapOfString; + } + + public MapTest mapOfEnumString(Map mapOfEnumString) { + this.mapOfEnumString = mapOfEnumString; + return this; + } + + public MapTest putMapOfEnumStringItem(String key, InnerEnum mapOfEnumStringItem) { + if (this.mapOfEnumString == null) { + this.mapOfEnumString = new HashMap<>(); + } + this.mapOfEnumString.put(key, mapOfEnumStringItem); + return this; + } + + /** + * Get mapOfEnumString + * @return mapOfEnumString + **/ + @ApiModelProperty(value = "") + public Map getMapOfEnumString() { + return mapOfEnumString; + } + + public void setMapOfEnumString(Map mapOfEnumString) { + this.mapOfEnumString = mapOfEnumString; + } + + public MapTest directMap(Map directMap) { + this.directMap = directMap; + return this; + } + + public MapTest putDirectMapItem(String key, Boolean directMapItem) { + if (this.directMap == null) { + this.directMap = new HashMap<>(); + } + this.directMap.put(key, directMapItem); + return this; + } + + /** + * Get directMap + * @return directMap + **/ + @ApiModelProperty(value = "") + public Map getDirectMap() { + return directMap; + } + + public void setDirectMap(Map directMap) { + this.directMap = directMap; + } + + public MapTest indirectMap(StringBooleanMap indirectMap) { + this.indirectMap = indirectMap; + return this; + } + + /** + * Get indirectMap + * @return indirectMap + **/ + @Valid + @ApiModelProperty(value = "") + public StringBooleanMap getIndirectMap() { + return indirectMap; + } + + public void setIndirectMap(StringBooleanMap indirectMap) { + this.indirectMap = indirectMap; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + MapTest mapTest = (MapTest) o; + return Objects.equals(this.mapMapOfString, mapTest.mapMapOfString) && + Objects.equals(this.mapOfEnumString, mapTest.mapOfEnumString) && + Objects.equals(this.directMap, mapTest.directMap) && + Objects.equals(this.indirectMap, mapTest.indirectMap); + } + + @Override + public int hashCode() { + return Objects.hash(mapMapOfString, mapOfEnumString, directMap, indirectMap); + } + + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class MapTest {\n"); + + sb.append(" mapMapOfString: ").append(toIndentedString(mapMapOfString)).append("\n"); + sb.append(" mapOfEnumString: ").append(toIndentedString(mapOfEnumString)).append("\n"); + sb.append(" directMap: ").append(toIndentedString(directMap)).append("\n"); + sb.append(" indirectMap: ").append(toIndentedString(indirectMap)).append("\n"); + 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 "); + } + +} + diff --git a/samples/client/petstore/java/retrofit2-play26/src/main/java/org/openapitools/client/model/MixedPropertiesAndAdditionalPropertiesClass.java b/samples/client/petstore/java/retrofit2-play26/src/main/java/org/openapitools/client/model/MixedPropertiesAndAdditionalPropertiesClass.java new file mode 100644 index 0000000000..212fd13d41 --- /dev/null +++ b/samples/client/petstore/java/retrofit2-play26/src/main/java/org/openapitools/client/model/MixedPropertiesAndAdditionalPropertiesClass.java @@ -0,0 +1,156 @@ +/* + * 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 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import java.util.Objects; +import java.util.Arrays; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import org.openapitools.client.model.Animal; +import org.threeten.bp.OffsetDateTime; +import javax.validation.constraints.*; +import javax.validation.Valid; + +/** + * MixedPropertiesAndAdditionalPropertiesClass + */ + +public class MixedPropertiesAndAdditionalPropertiesClass { + @JsonProperty("uuid") + private UUID uuid = null; + + @JsonProperty("dateTime") + private OffsetDateTime dateTime = null; + + @JsonProperty("map") + private Map map = null; + + public MixedPropertiesAndAdditionalPropertiesClass uuid(UUID uuid) { + this.uuid = uuid; + return this; + } + + /** + * Get uuid + * @return uuid + **/ + @Valid + @ApiModelProperty(value = "") + public UUID getUuid() { + return uuid; + } + + public void setUuid(UUID uuid) { + this.uuid = uuid; + } + + public MixedPropertiesAndAdditionalPropertiesClass dateTime(OffsetDateTime dateTime) { + this.dateTime = dateTime; + return this; + } + + /** + * Get dateTime + * @return dateTime + **/ + @Valid + @ApiModelProperty(value = "") + public OffsetDateTime getDateTime() { + return dateTime; + } + + public void setDateTime(OffsetDateTime dateTime) { + this.dateTime = dateTime; + } + + public MixedPropertiesAndAdditionalPropertiesClass map(Map map) { + this.map = map; + return this; + } + + public MixedPropertiesAndAdditionalPropertiesClass putMapItem(String key, Animal mapItem) { + if (this.map == null) { + this.map = new HashMap<>(); + } + this.map.put(key, mapItem); + return this; + } + + /** + * Get map + * @return map + **/ + @Valid + @ApiModelProperty(value = "") + public Map getMap() { + return map; + } + + public void setMap(Map map) { + this.map = map; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + MixedPropertiesAndAdditionalPropertiesClass mixedPropertiesAndAdditionalPropertiesClass = (MixedPropertiesAndAdditionalPropertiesClass) o; + return Objects.equals(this.uuid, mixedPropertiesAndAdditionalPropertiesClass.uuid) && + Objects.equals(this.dateTime, mixedPropertiesAndAdditionalPropertiesClass.dateTime) && + Objects.equals(this.map, mixedPropertiesAndAdditionalPropertiesClass.map); + } + + @Override + public int hashCode() { + return Objects.hash(uuid, dateTime, map); + } + + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class MixedPropertiesAndAdditionalPropertiesClass {\n"); + + sb.append(" uuid: ").append(toIndentedString(uuid)).append("\n"); + sb.append(" dateTime: ").append(toIndentedString(dateTime)).append("\n"); + sb.append(" map: ").append(toIndentedString(map)).append("\n"); + 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 "); + } + +} + diff --git a/samples/client/petstore/java/retrofit2-play26/src/main/java/org/openapitools/client/model/Model200Response.java b/samples/client/petstore/java/retrofit2-play26/src/main/java/org/openapitools/client/model/Model200Response.java new file mode 100644 index 0000000000..bcdb67df9d --- /dev/null +++ b/samples/client/petstore/java/retrofit2-play26/src/main/java/org/openapitools/client/model/Model200Response.java @@ -0,0 +1,117 @@ +/* + * 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 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import java.util.Objects; +import java.util.Arrays; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import javax.validation.constraints.*; +import javax.validation.Valid; + +/** + * Model for testing model name starting with number + */ +@ApiModel(description = "Model for testing model name starting with number") + +public class Model200Response { + @JsonProperty("name") + private Integer name = null; + + @JsonProperty("class") + private String propertyClass = null; + + public Model200Response name(Integer name) { + this.name = name; + return this; + } + + /** + * Get name + * @return name + **/ + @ApiModelProperty(value = "") + public Integer getName() { + return name; + } + + public void setName(Integer name) { + this.name = name; + } + + public Model200Response propertyClass(String propertyClass) { + this.propertyClass = propertyClass; + return this; + } + + /** + * Get propertyClass + * @return propertyClass + **/ + @ApiModelProperty(value = "") + public String getPropertyClass() { + return propertyClass; + } + + public void setPropertyClass(String propertyClass) { + this.propertyClass = propertyClass; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + Model200Response _200response = (Model200Response) o; + return Objects.equals(this.name, _200response.name) && + Objects.equals(this.propertyClass, _200response.propertyClass); + } + + @Override + public int hashCode() { + return Objects.hash(name, propertyClass); + } + + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Model200Response {\n"); + + sb.append(" name: ").append(toIndentedString(name)).append("\n"); + sb.append(" propertyClass: ").append(toIndentedString(propertyClass)).append("\n"); + 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 "); + } + +} + diff --git a/samples/client/petstore/java/retrofit2-play26/src/main/java/org/openapitools/client/model/ModelApiResponse.java b/samples/client/petstore/java/retrofit2-play26/src/main/java/org/openapitools/client/model/ModelApiResponse.java new file mode 100644 index 0000000000..8eb69f7d46 --- /dev/null +++ b/samples/client/petstore/java/retrofit2-play26/src/main/java/org/openapitools/client/model/ModelApiResponse.java @@ -0,0 +1,139 @@ +/* + * 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 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import java.util.Objects; +import java.util.Arrays; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import javax.validation.constraints.*; +import javax.validation.Valid; + +/** + * ModelApiResponse + */ + +public class ModelApiResponse { + @JsonProperty("code") + private Integer code = null; + + @JsonProperty("type") + private String type = null; + + @JsonProperty("message") + private String message = null; + + public ModelApiResponse code(Integer code) { + this.code = code; + return this; + } + + /** + * Get code + * @return code + **/ + @ApiModelProperty(value = "") + public Integer getCode() { + return code; + } + + public void setCode(Integer code) { + this.code = code; + } + + public ModelApiResponse type(String type) { + this.type = type; + return this; + } + + /** + * Get type + * @return type + **/ + @ApiModelProperty(value = "") + public String getType() { + return type; + } + + public void setType(String type) { + this.type = type; + } + + public ModelApiResponse message(String message) { + this.message = message; + return this; + } + + /** + * Get message + * @return message + **/ + @ApiModelProperty(value = "") + public String getMessage() { + return message; + } + + public void setMessage(String message) { + this.message = message; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + ModelApiResponse _apiResponse = (ModelApiResponse) o; + return Objects.equals(this.code, _apiResponse.code) && + Objects.equals(this.type, _apiResponse.type) && + Objects.equals(this.message, _apiResponse.message); + } + + @Override + public int hashCode() { + return Objects.hash(code, type, message); + } + + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class ModelApiResponse {\n"); + + sb.append(" code: ").append(toIndentedString(code)).append("\n"); + sb.append(" type: ").append(toIndentedString(type)).append("\n"); + sb.append(" message: ").append(toIndentedString(message)).append("\n"); + 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 "); + } + +} + diff --git a/samples/client/petstore/java/retrofit2-play26/src/main/java/org/openapitools/client/model/ModelReturn.java b/samples/client/petstore/java/retrofit2-play26/src/main/java/org/openapitools/client/model/ModelReturn.java new file mode 100644 index 0000000000..7fd7e7c0cb --- /dev/null +++ b/samples/client/petstore/java/retrofit2-play26/src/main/java/org/openapitools/client/model/ModelReturn.java @@ -0,0 +1,94 @@ +/* + * 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 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import java.util.Objects; +import java.util.Arrays; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import javax.validation.constraints.*; +import javax.validation.Valid; + +/** + * Model for testing reserved words + */ +@ApiModel(description = "Model for testing reserved words") + +public class ModelReturn { + @JsonProperty("return") + private Integer _return = null; + + public ModelReturn _return(Integer _return) { + this._return = _return; + return this; + } + + /** + * Get _return + * @return _return + **/ + @ApiModelProperty(value = "") + public Integer getReturn() { + return _return; + } + + public void setReturn(Integer _return) { + this._return = _return; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + ModelReturn _return = (ModelReturn) o; + return Objects.equals(this._return, _return._return); + } + + @Override + public int hashCode() { + return Objects.hash(_return); + } + + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class ModelReturn {\n"); + + sb.append(" _return: ").append(toIndentedString(_return)).append("\n"); + 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 "); + } + +} + diff --git a/samples/client/petstore/java/retrofit2-play26/src/main/java/org/openapitools/client/model/Name.java b/samples/client/petstore/java/retrofit2-play26/src/main/java/org/openapitools/client/model/Name.java new file mode 100644 index 0000000000..16a25a54a2 --- /dev/null +++ b/samples/client/petstore/java/retrofit2-play26/src/main/java/org/openapitools/client/model/Name.java @@ -0,0 +1,146 @@ +/* + * 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 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import java.util.Objects; +import java.util.Arrays; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import javax.validation.constraints.*; +import javax.validation.Valid; + +/** + * Model for testing model name same as property name + */ +@ApiModel(description = "Model for testing model name same as property name") + +public class Name { + @JsonProperty("name") + private Integer name = null; + + @JsonProperty("snake_case") + private Integer snakeCase = null; + + @JsonProperty("property") + private String property = null; + + @JsonProperty("123Number") + private Integer _123number = null; + + public Name name(Integer name) { + this.name = name; + return this; + } + + /** + * Get name + * @return name + **/ + @NotNull + @ApiModelProperty(required = true, value = "") + public Integer getName() { + return name; + } + + public void setName(Integer name) { + this.name = name; + } + + /** + * Get snakeCase + * @return snakeCase + **/ + @ApiModelProperty(value = "") + public Integer getSnakeCase() { + return snakeCase; + } + + public Name property(String property) { + this.property = property; + return this; + } + + /** + * Get property + * @return property + **/ + @ApiModelProperty(value = "") + public String getProperty() { + return property; + } + + public void setProperty(String property) { + this.property = property; + } + + /** + * Get _123number + * @return _123number + **/ + @ApiModelProperty(value = "") + public Integer get123number() { + return _123number; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + Name name = (Name) o; + return Objects.equals(this.name, name.name) && + Objects.equals(this.snakeCase, name.snakeCase) && + Objects.equals(this.property, name.property) && + Objects.equals(this._123number, name._123number); + } + + @Override + public int hashCode() { + return Objects.hash(name, snakeCase, property, _123number); + } + + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Name {\n"); + + sb.append(" name: ").append(toIndentedString(name)).append("\n"); + sb.append(" snakeCase: ").append(toIndentedString(snakeCase)).append("\n"); + sb.append(" property: ").append(toIndentedString(property)).append("\n"); + sb.append(" _123number: ").append(toIndentedString(_123number)).append("\n"); + 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 "); + } + +} + diff --git a/samples/client/petstore/java/retrofit2-play26/src/main/java/org/openapitools/client/model/NumberOnly.java b/samples/client/petstore/java/retrofit2-play26/src/main/java/org/openapitools/client/model/NumberOnly.java new file mode 100644 index 0000000000..c3bada4d06 --- /dev/null +++ b/samples/client/petstore/java/retrofit2-play26/src/main/java/org/openapitools/client/model/NumberOnly.java @@ -0,0 +1,95 @@ +/* + * 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 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import java.util.Objects; +import java.util.Arrays; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import java.math.BigDecimal; +import javax.validation.constraints.*; +import javax.validation.Valid; + +/** + * NumberOnly + */ + +public class NumberOnly { + @JsonProperty("JustNumber") + private BigDecimal justNumber = null; + + public NumberOnly justNumber(BigDecimal justNumber) { + this.justNumber = justNumber; + return this; + } + + /** + * Get justNumber + * @return justNumber + **/ + @Valid + @ApiModelProperty(value = "") + public BigDecimal getJustNumber() { + return justNumber; + } + + public void setJustNumber(BigDecimal justNumber) { + this.justNumber = justNumber; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + NumberOnly numberOnly = (NumberOnly) o; + return Objects.equals(this.justNumber, numberOnly.justNumber); + } + + @Override + public int hashCode() { + return Objects.hash(justNumber); + } + + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class NumberOnly {\n"); + + sb.append(" justNumber: ").append(toIndentedString(justNumber)).append("\n"); + 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 "); + } + +} + diff --git a/samples/client/petstore/java/retrofit2-play26/src/main/java/org/openapitools/client/model/Order.java b/samples/client/petstore/java/retrofit2-play26/src/main/java/org/openapitools/client/model/Order.java new file mode 100644 index 0000000000..e109aaa7cb --- /dev/null +++ b/samples/client/petstore/java/retrofit2-play26/src/main/java/org/openapitools/client/model/Order.java @@ -0,0 +1,247 @@ +/* + * 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 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import java.util.Objects; +import java.util.Arrays; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import org.threeten.bp.OffsetDateTime; +import javax.validation.constraints.*; +import javax.validation.Valid; + +/** + * Order + */ + +public class Order { + @JsonProperty("id") + private Long id = null; + + @JsonProperty("petId") + private Long petId = null; + + @JsonProperty("quantity") + private Integer quantity = null; + + @JsonProperty("shipDate") + private OffsetDateTime shipDate = null; + + /** + * Order Status + */ + public enum StatusEnum { + PLACED("placed"), + + APPROVED("approved"), + + DELIVERED("delivered"); + + private String value; + + StatusEnum(String value) { + this.value = value; + } + + @JsonValue + public String getValue() { + return value; + } + + @Override + public String toString() { + return String.valueOf(value); + } + + @JsonCreator + public static StatusEnum fromValue(String text) { + for (StatusEnum b : StatusEnum.values()) { + if (String.valueOf(b.value).equals(text)) { + return b; + } + } + throw new IllegalArgumentException("Unexpected value '" + text + "'"); + } + } + + @JsonProperty("status") + private StatusEnum status = null; + + @JsonProperty("complete") + private Boolean complete = false; + + public Order id(Long id) { + this.id = id; + return this; + } + + /** + * Get id + * @return id + **/ + @ApiModelProperty(value = "") + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public Order petId(Long petId) { + this.petId = petId; + return this; + } + + /** + * Get petId + * @return petId + **/ + @ApiModelProperty(value = "") + public Long getPetId() { + return petId; + } + + public void setPetId(Long petId) { + this.petId = petId; + } + + public Order quantity(Integer quantity) { + this.quantity = quantity; + return this; + } + + /** + * Get quantity + * @return quantity + **/ + @ApiModelProperty(value = "") + public Integer getQuantity() { + return quantity; + } + + public void setQuantity(Integer quantity) { + this.quantity = quantity; + } + + public Order shipDate(OffsetDateTime shipDate) { + this.shipDate = shipDate; + return this; + } + + /** + * Get shipDate + * @return shipDate + **/ + @Valid + @ApiModelProperty(value = "") + public OffsetDateTime getShipDate() { + return shipDate; + } + + public void setShipDate(OffsetDateTime shipDate) { + this.shipDate = shipDate; + } + + public Order status(StatusEnum status) { + this.status = status; + return this; + } + + /** + * Order Status + * @return status + **/ + @ApiModelProperty(value = "Order Status") + public StatusEnum getStatus() { + return status; + } + + public void setStatus(StatusEnum status) { + this.status = status; + } + + public Order complete(Boolean complete) { + this.complete = complete; + return this; + } + + /** + * Get complete + * @return complete + **/ + @ApiModelProperty(value = "") + public Boolean getComplete() { + return complete; + } + + public void setComplete(Boolean complete) { + this.complete = complete; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + Order order = (Order) o; + return Objects.equals(this.id, order.id) && + Objects.equals(this.petId, order.petId) && + Objects.equals(this.quantity, order.quantity) && + Objects.equals(this.shipDate, order.shipDate) && + Objects.equals(this.status, order.status) && + Objects.equals(this.complete, order.complete); + } + + @Override + public int hashCode() { + return Objects.hash(id, petId, quantity, shipDate, status, complete); + } + + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Order {\n"); + + sb.append(" id: ").append(toIndentedString(id)).append("\n"); + sb.append(" petId: ").append(toIndentedString(petId)).append("\n"); + sb.append(" quantity: ").append(toIndentedString(quantity)).append("\n"); + sb.append(" shipDate: ").append(toIndentedString(shipDate)).append("\n"); + sb.append(" status: ").append(toIndentedString(status)).append("\n"); + sb.append(" complete: ").append(toIndentedString(complete)).append("\n"); + 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 "); + } + +} + diff --git a/samples/client/petstore/java/retrofit2-play26/src/main/java/org/openapitools/client/model/OuterComposite.java b/samples/client/petstore/java/retrofit2-play26/src/main/java/org/openapitools/client/model/OuterComposite.java new file mode 100644 index 0000000000..f0bf1fbaab --- /dev/null +++ b/samples/client/petstore/java/retrofit2-play26/src/main/java/org/openapitools/client/model/OuterComposite.java @@ -0,0 +1,141 @@ +/* + * 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 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import java.util.Objects; +import java.util.Arrays; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import java.math.BigDecimal; +import javax.validation.constraints.*; +import javax.validation.Valid; + +/** + * OuterComposite + */ + +public class OuterComposite { + @JsonProperty("my_number") + private BigDecimal myNumber = null; + + @JsonProperty("my_string") + private String myString = null; + + @JsonProperty("my_boolean") + private Boolean myBoolean = null; + + public OuterComposite myNumber(BigDecimal myNumber) { + this.myNumber = myNumber; + return this; + } + + /** + * Get myNumber + * @return myNumber + **/ + @Valid + @ApiModelProperty(value = "") + public BigDecimal getMyNumber() { + return myNumber; + } + + public void setMyNumber(BigDecimal myNumber) { + this.myNumber = myNumber; + } + + public OuterComposite myString(String myString) { + this.myString = myString; + return this; + } + + /** + * Get myString + * @return myString + **/ + @ApiModelProperty(value = "") + public String getMyString() { + return myString; + } + + public void setMyString(String myString) { + this.myString = myString; + } + + public OuterComposite myBoolean(Boolean myBoolean) { + this.myBoolean = myBoolean; + return this; + } + + /** + * Get myBoolean + * @return myBoolean + **/ + @ApiModelProperty(value = "") + public Boolean getMyBoolean() { + return myBoolean; + } + + public void setMyBoolean(Boolean myBoolean) { + this.myBoolean = myBoolean; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + OuterComposite outerComposite = (OuterComposite) o; + return Objects.equals(this.myNumber, outerComposite.myNumber) && + Objects.equals(this.myString, outerComposite.myString) && + Objects.equals(this.myBoolean, outerComposite.myBoolean); + } + + @Override + public int hashCode() { + return Objects.hash(myNumber, myString, myBoolean); + } + + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class OuterComposite {\n"); + + sb.append(" myNumber: ").append(toIndentedString(myNumber)).append("\n"); + sb.append(" myString: ").append(toIndentedString(myString)).append("\n"); + sb.append(" myBoolean: ").append(toIndentedString(myBoolean)).append("\n"); + 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 "); + } + +} + diff --git a/samples/client/petstore/java/retrofit2-play26/src/main/java/org/openapitools/client/model/OuterEnum.java b/samples/client/petstore/java/retrofit2-play26/src/main/java/org/openapitools/client/model/OuterEnum.java new file mode 100644 index 0000000000..7a9fbfc01f --- /dev/null +++ b/samples/client/petstore/java/retrofit2-play26/src/main/java/org/openapitools/client/model/OuterEnum.java @@ -0,0 +1,61 @@ +/* + * 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 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import java.util.Objects; +import java.util.Arrays; +import javax.validation.constraints.*; +import javax.validation.Valid; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; + +/** + * Gets or Sets OuterEnum + */ +public enum OuterEnum { + + PLACED("placed"), + + APPROVED("approved"), + + DELIVERED("delivered"); + + private String value; + + OuterEnum(String value) { + this.value = value; + } + + @JsonValue + public String getValue() { + return value; + } + + @Override + public String toString() { + return String.valueOf(value); + } + + @JsonCreator + public static OuterEnum fromValue(String text) { + for (OuterEnum b : OuterEnum.values()) { + if (String.valueOf(b.value).equals(text)) { + return b; + } + } + throw new IllegalArgumentException("Unexpected value '" + text + "'"); + } +} + diff --git a/samples/client/petstore/java/retrofit2-play26/src/main/java/org/openapitools/client/model/Pet.java b/samples/client/petstore/java/retrofit2-play26/src/main/java/org/openapitools/client/model/Pet.java new file mode 100644 index 0000000000..eda15f833c --- /dev/null +++ b/samples/client/petstore/java/retrofit2-play26/src/main/java/org/openapitools/client/model/Pet.java @@ -0,0 +1,266 @@ +/* + * 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 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import java.util.Objects; +import java.util.Arrays; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import java.util.ArrayList; +import java.util.List; +import org.openapitools.client.model.Category; +import org.openapitools.client.model.Tag; +import javax.validation.constraints.*; +import javax.validation.Valid; + +/** + * Pet + */ + +public class Pet { + @JsonProperty("id") + private Long id = null; + + @JsonProperty("category") + private Category category = null; + + @JsonProperty("name") + private String name = null; + + @JsonProperty("photoUrls") + private List photoUrls = new ArrayList<>(); + + @JsonProperty("tags") + private List tags = null; + + /** + * pet status in the store + */ + public enum StatusEnum { + AVAILABLE("available"), + + PENDING("pending"), + + SOLD("sold"); + + private String value; + + StatusEnum(String value) { + this.value = value; + } + + @JsonValue + public String getValue() { + return value; + } + + @Override + public String toString() { + return String.valueOf(value); + } + + @JsonCreator + public static StatusEnum fromValue(String text) { + for (StatusEnum b : StatusEnum.values()) { + if (String.valueOf(b.value).equals(text)) { + return b; + } + } + throw new IllegalArgumentException("Unexpected value '" + text + "'"); + } + } + + @JsonProperty("status") + private StatusEnum status = null; + + public Pet id(Long id) { + this.id = id; + return this; + } + + /** + * Get id + * @return id + **/ + @ApiModelProperty(value = "") + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public Pet category(Category category) { + this.category = category; + return this; + } + + /** + * Get category + * @return category + **/ + @Valid + @ApiModelProperty(value = "") + public Category getCategory() { + return category; + } + + public void setCategory(Category category) { + this.category = category; + } + + public Pet name(String name) { + this.name = name; + return this; + } + + /** + * Get name + * @return name + **/ + @NotNull + @ApiModelProperty(example = "doggie", required = true, value = "") + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public Pet photoUrls(List photoUrls) { + this.photoUrls = photoUrls; + return this; + } + + public Pet addPhotoUrlsItem(String photoUrlsItem) { + this.photoUrls.add(photoUrlsItem); + return this; + } + + /** + * Get photoUrls + * @return photoUrls + **/ + @NotNull + @ApiModelProperty(required = true, value = "") + public List getPhotoUrls() { + return photoUrls; + } + + public void setPhotoUrls(List photoUrls) { + this.photoUrls = photoUrls; + } + + public Pet tags(List tags) { + this.tags = tags; + return this; + } + + public Pet addTagsItem(Tag tagsItem) { + if (this.tags == null) { + this.tags = new ArrayList<>(); + } + this.tags.add(tagsItem); + return this; + } + + /** + * Get tags + * @return tags + **/ + @Valid + @ApiModelProperty(value = "") + public List getTags() { + return tags; + } + + public void setTags(List tags) { + this.tags = tags; + } + + public Pet status(StatusEnum status) { + this.status = status; + return this; + } + + /** + * pet status in the store + * @return status + **/ + @ApiModelProperty(value = "pet status in the store") + public StatusEnum getStatus() { + return status; + } + + public void setStatus(StatusEnum status) { + this.status = status; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + Pet pet = (Pet) o; + return Objects.equals(this.id, pet.id) && + Objects.equals(this.category, pet.category) && + Objects.equals(this.name, pet.name) && + Objects.equals(this.photoUrls, pet.photoUrls) && + Objects.equals(this.tags, pet.tags) && + Objects.equals(this.status, pet.status); + } + + @Override + public int hashCode() { + return Objects.hash(id, category, name, photoUrls, tags, status); + } + + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Pet {\n"); + + sb.append(" id: ").append(toIndentedString(id)).append("\n"); + sb.append(" category: ").append(toIndentedString(category)).append("\n"); + sb.append(" name: ").append(toIndentedString(name)).append("\n"); + sb.append(" photoUrls: ").append(toIndentedString(photoUrls)).append("\n"); + sb.append(" tags: ").append(toIndentedString(tags)).append("\n"); + sb.append(" status: ").append(toIndentedString(status)).append("\n"); + 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 "); + } + +} + diff --git a/samples/client/petstore/java/retrofit2-play26/src/main/java/org/openapitools/client/model/ReadOnlyFirst.java b/samples/client/petstore/java/retrofit2-play26/src/main/java/org/openapitools/client/model/ReadOnlyFirst.java new file mode 100644 index 0000000000..882a50757a --- /dev/null +++ b/samples/client/petstore/java/retrofit2-play26/src/main/java/org/openapitools/client/model/ReadOnlyFirst.java @@ -0,0 +1,107 @@ +/* + * 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 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import java.util.Objects; +import java.util.Arrays; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import javax.validation.constraints.*; +import javax.validation.Valid; + +/** + * ReadOnlyFirst + */ + +public class ReadOnlyFirst { + @JsonProperty("bar") + private String bar = null; + + @JsonProperty("baz") + private String baz = null; + + /** + * Get bar + * @return bar + **/ + @ApiModelProperty(value = "") + public String getBar() { + return bar; + } + + public ReadOnlyFirst baz(String baz) { + this.baz = baz; + return this; + } + + /** + * Get baz + * @return baz + **/ + @ApiModelProperty(value = "") + public String getBaz() { + return baz; + } + + public void setBaz(String baz) { + this.baz = baz; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + ReadOnlyFirst readOnlyFirst = (ReadOnlyFirst) o; + return Objects.equals(this.bar, readOnlyFirst.bar) && + Objects.equals(this.baz, readOnlyFirst.baz); + } + + @Override + public int hashCode() { + return Objects.hash(bar, baz); + } + + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class ReadOnlyFirst {\n"); + + sb.append(" bar: ").append(toIndentedString(bar)).append("\n"); + sb.append(" baz: ").append(toIndentedString(baz)).append("\n"); + 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 "); + } + +} + diff --git a/samples/client/petstore/java/retrofit2-play26/src/main/java/org/openapitools/client/model/SpecialModelName.java b/samples/client/petstore/java/retrofit2-play26/src/main/java/org/openapitools/client/model/SpecialModelName.java new file mode 100644 index 0000000000..0a73668a0e --- /dev/null +++ b/samples/client/petstore/java/retrofit2-play26/src/main/java/org/openapitools/client/model/SpecialModelName.java @@ -0,0 +1,93 @@ +/* + * 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 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import java.util.Objects; +import java.util.Arrays; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import javax.validation.constraints.*; +import javax.validation.Valid; + +/** + * SpecialModelName + */ + +public class SpecialModelName { + @JsonProperty("$special[property.name]") + private Long $specialPropertyName = null; + + public SpecialModelName $specialPropertyName(Long $specialPropertyName) { + this.$specialPropertyName = $specialPropertyName; + return this; + } + + /** + * Get $specialPropertyName + * @return $specialPropertyName + **/ + @ApiModelProperty(value = "") + public Long get$SpecialPropertyName() { + return $specialPropertyName; + } + + public void set$SpecialPropertyName(Long $specialPropertyName) { + this.$specialPropertyName = $specialPropertyName; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + SpecialModelName $specialModelName = (SpecialModelName) o; + return Objects.equals(this.$specialPropertyName, $specialModelName.$specialPropertyName); + } + + @Override + public int hashCode() { + return Objects.hash($specialPropertyName); + } + + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class SpecialModelName {\n"); + + sb.append(" $specialPropertyName: ").append(toIndentedString($specialPropertyName)).append("\n"); + 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 "); + } + +} + diff --git a/samples/client/petstore/java/retrofit2-play26/src/main/java/org/openapitools/client/model/StringBooleanMap.java b/samples/client/petstore/java/retrofit2-play26/src/main/java/org/openapitools/client/model/StringBooleanMap.java new file mode 100644 index 0000000000..c651556f7d --- /dev/null +++ b/samples/client/petstore/java/retrofit2-play26/src/main/java/org/openapitools/client/model/StringBooleanMap.java @@ -0,0 +1,67 @@ +/* + * 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 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import java.util.Objects; +import java.util.Arrays; +import java.util.HashMap; +import java.util.Map; +import javax.validation.constraints.*; +import javax.validation.Valid; + +/** + * StringBooleanMap + */ + +public class StringBooleanMap extends HashMap { + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + return super.equals(o); + } + + @Override + public int hashCode() { + return Objects.hash(super.hashCode()); + } + + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class StringBooleanMap {\n"); + sb.append(" ").append(toIndentedString(super.toString())).append("\n"); + 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 "); + } + +} + diff --git a/samples/client/petstore/java/retrofit2-play26/src/main/java/org/openapitools/client/model/Tag.java b/samples/client/petstore/java/retrofit2-play26/src/main/java/org/openapitools/client/model/Tag.java new file mode 100644 index 0000000000..ea23d8f46c --- /dev/null +++ b/samples/client/petstore/java/retrofit2-play26/src/main/java/org/openapitools/client/model/Tag.java @@ -0,0 +1,116 @@ +/* + * 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 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import java.util.Objects; +import java.util.Arrays; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import javax.validation.constraints.*; +import javax.validation.Valid; + +/** + * Tag + */ + +public class Tag { + @JsonProperty("id") + private Long id = null; + + @JsonProperty("name") + private String name = null; + + public Tag id(Long id) { + this.id = id; + return this; + } + + /** + * Get id + * @return id + **/ + @ApiModelProperty(value = "") + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public Tag name(String name) { + this.name = name; + return this; + } + + /** + * Get name + * @return name + **/ + @ApiModelProperty(value = "") + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + Tag tag = (Tag) o; + return Objects.equals(this.id, tag.id) && + Objects.equals(this.name, tag.name); + } + + @Override + public int hashCode() { + return Objects.hash(id, name); + } + + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Tag {\n"); + + sb.append(" id: ").append(toIndentedString(id)).append("\n"); + sb.append(" name: ").append(toIndentedString(name)).append("\n"); + 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 "); + } + +} + diff --git a/samples/client/petstore/java/retrofit2-play26/src/main/java/org/openapitools/client/model/User.java b/samples/client/petstore/java/retrofit2-play26/src/main/java/org/openapitools/client/model/User.java new file mode 100644 index 0000000000..5173076477 --- /dev/null +++ b/samples/client/petstore/java/retrofit2-play26/src/main/java/org/openapitools/client/model/User.java @@ -0,0 +1,254 @@ +/* + * 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 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import java.util.Objects; +import java.util.Arrays; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import javax.validation.constraints.*; +import javax.validation.Valid; + +/** + * User + */ + +public class User { + @JsonProperty("id") + private Long id = null; + + @JsonProperty("username") + private String username = null; + + @JsonProperty("firstName") + private String firstName = null; + + @JsonProperty("lastName") + private String lastName = null; + + @JsonProperty("email") + private String email = null; + + @JsonProperty("password") + private String password = null; + + @JsonProperty("phone") + private String phone = null; + + @JsonProperty("userStatus") + private Integer userStatus = null; + + public User id(Long id) { + this.id = id; + return this; + } + + /** + * Get id + * @return id + **/ + @ApiModelProperty(value = "") + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public User username(String username) { + this.username = username; + return this; + } + + /** + * Get username + * @return username + **/ + @ApiModelProperty(value = "") + public String getUsername() { + return username; + } + + public void setUsername(String username) { + this.username = username; + } + + public User firstName(String firstName) { + this.firstName = firstName; + return this; + } + + /** + * Get firstName + * @return firstName + **/ + @ApiModelProperty(value = "") + public String getFirstName() { + return firstName; + } + + public void setFirstName(String firstName) { + this.firstName = firstName; + } + + public User lastName(String lastName) { + this.lastName = lastName; + return this; + } + + /** + * Get lastName + * @return lastName + **/ + @ApiModelProperty(value = "") + public String getLastName() { + return lastName; + } + + public void setLastName(String lastName) { + this.lastName = lastName; + } + + public User email(String email) { + this.email = email; + return this; + } + + /** + * Get email + * @return email + **/ + @ApiModelProperty(value = "") + public String getEmail() { + return email; + } + + public void setEmail(String email) { + this.email = email; + } + + public User password(String password) { + this.password = password; + return this; + } + + /** + * Get password + * @return password + **/ + @ApiModelProperty(value = "") + public String getPassword() { + return password; + } + + public void setPassword(String password) { + this.password = password; + } + + public User phone(String phone) { + this.phone = phone; + return this; + } + + /** + * Get phone + * @return phone + **/ + @ApiModelProperty(value = "") + public String getPhone() { + return phone; + } + + public void setPhone(String phone) { + this.phone = phone; + } + + public User userStatus(Integer userStatus) { + this.userStatus = userStatus; + return this; + } + + /** + * User Status + * @return userStatus + **/ + @ApiModelProperty(value = "User Status") + public Integer getUserStatus() { + return userStatus; + } + + public void setUserStatus(Integer userStatus) { + this.userStatus = userStatus; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + User user = (User) o; + return Objects.equals(this.id, user.id) && + Objects.equals(this.username, user.username) && + Objects.equals(this.firstName, user.firstName) && + Objects.equals(this.lastName, user.lastName) && + Objects.equals(this.email, user.email) && + Objects.equals(this.password, user.password) && + Objects.equals(this.phone, user.phone) && + Objects.equals(this.userStatus, user.userStatus); + } + + @Override + public int hashCode() { + return Objects.hash(id, username, firstName, lastName, email, password, phone, userStatus); + } + + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class User {\n"); + + sb.append(" id: ").append(toIndentedString(id)).append("\n"); + sb.append(" username: ").append(toIndentedString(username)).append("\n"); + sb.append(" firstName: ").append(toIndentedString(firstName)).append("\n"); + sb.append(" lastName: ").append(toIndentedString(lastName)).append("\n"); + sb.append(" email: ").append(toIndentedString(email)).append("\n"); + sb.append(" password: ").append(toIndentedString(password)).append("\n"); + sb.append(" phone: ").append(toIndentedString(phone)).append("\n"); + sb.append(" userStatus: ").append(toIndentedString(userStatus)).append("\n"); + 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 "); + } + +} + diff --git a/samples/client/petstore/java/retrofit2-play26/src/test/java/org/openapitools/client/api/AnotherFakeApiTest.java b/samples/client/petstore/java/retrofit2-play26/src/test/java/org/openapitools/client/api/AnotherFakeApiTest.java new file mode 100644 index 0000000000..0307ed1777 --- /dev/null +++ b/samples/client/petstore/java/retrofit2-play26/src/test/java/org/openapitools/client/api/AnotherFakeApiTest.java @@ -0,0 +1,32 @@ +package org.openapitools.client.api; + +import org.junit.Before; +import org.junit.Test; +import org.openapitools.client.ApiClient; +import org.openapitools.client.model.Client; + +/** + * API tests for AnotherFakeApi + */ +public class AnotherFakeApiTest { + + private AnotherFakeApi api; + + @Before + public void setup() { + api = new ApiClient().createService(AnotherFakeApi.class); + } + + /** + * To test special tags + * + * To test special tags and operation ID starting with number + */ + @Test + public void call123testSpecialTagsTest() { + Client client = null; + // Client response = api.call123testSpecialTags(client); + + // TODO: test validations + } +} diff --git a/samples/client/petstore/java/retrofit2-play26/src/test/java/org/openapitools/client/api/FakeApiTest.java b/samples/client/petstore/java/retrofit2-play26/src/test/java/org/openapitools/client/api/FakeApiTest.java new file mode 100644 index 0000000000..4889e92772 --- /dev/null +++ b/samples/client/petstore/java/retrofit2-play26/src/test/java/org/openapitools/client/api/FakeApiTest.java @@ -0,0 +1,184 @@ +package org.openapitools.client.api; + +import org.junit.Before; +import org.junit.Test; +import org.openapitools.client.ApiClient; +import org.openapitools.client.model.Client; +import org.openapitools.client.model.FileSchemaTestClass; +import org.openapitools.client.model.OuterComposite; +import org.openapitools.client.model.User; +import org.threeten.bp.LocalDate; +import org.threeten.bp.OffsetDateTime; + +import java.io.File; +import java.math.BigDecimal; +import java.util.List; +import java.util.Map; + +/** + * API tests for FakeApi + */ +public class FakeApiTest { + + private FakeApi api; + + @Before + public void setup() { + api = new ApiClient().createService(FakeApi.class); + } + + /** + * + * + * Test serialization of outer boolean types + */ + @Test + public void fakeOuterBooleanSerializeTest() { + Boolean body = null; + // Boolean response = api.fakeOuterBooleanSerialize(body); + + // TODO: test validations + } + /** + * + * + * Test serialization of object with outer number type + */ + @Test + public void fakeOuterCompositeSerializeTest() { + OuterComposite outerComposite = null; + // OuterComposite response = api.fakeOuterCompositeSerialize(outerComposite); + + // TODO: test validations + } + /** + * + * + * Test serialization of outer number types + */ + @Test + public void fakeOuterNumberSerializeTest() { + BigDecimal body = null; + // BigDecimal response = api.fakeOuterNumberSerialize(body); + + // TODO: test validations + } + /** + * + * + * Test serialization of outer string types + */ + @Test + public void fakeOuterStringSerializeTest() { + String body = null; + // String response = api.fakeOuterStringSerialize(body); + + // TODO: test validations + } + /** + * + * + * For this test, the body for this request much reference a schema named `File`. + */ + @Test + public void testBodyWithFileSchemaTest() { + FileSchemaTestClass fileSchemaTestClass = null; + // api.testBodyWithFileSchema(fileSchemaTestClass); + + // TODO: test validations + } + /** + * + * + * + */ + @Test + public void testBodyWithQueryParamsTest() { + String query = null; + User user = null; + // api.testBodyWithQueryParams(query, user); + + // TODO: test validations + } + /** + * To test \"client\" model + * + * To test \"client\" model + */ + @Test + public void testClientModelTest() { + Client client = null; + // Client response = api.testClientModel(client); + + // TODO: test validations + } + /** + * Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + * + * Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + */ + @Test + public void testEndpointParametersTest() { + BigDecimal number = null; + Double _double = null; + String patternWithoutDelimiter = null; + byte[] _byte = null; + Integer integer = null; + Integer int32 = null; + Long int64 = null; + Float _float = null; + String string = null; + File binary = null; + LocalDate date = null; + OffsetDateTime dateTime = null; + String password = null; + String paramCallback = null; + // api.testEndpointParameters(number, _double, patternWithoutDelimiter, _byte, integer, int32, int64, _float, string, binary, date, dateTime, password, paramCallback); + + // TODO: test validations + } + /** + * To test enum parameters + * + * To test enum parameters + */ + @Test + public void testEnumParametersTest() { + List enumHeaderStringArray = null; + String enumHeaderString = null; + List enumQueryStringArray = null; + String enumQueryString = null; + Integer enumQueryInteger = null; + Double enumQueryDouble = null; + List enumFormStringArray = null; + String enumFormString = null; + // api.testEnumParameters(enumHeaderStringArray, enumHeaderString, enumQueryStringArray, enumQueryString, enumQueryInteger, enumQueryDouble, enumFormStringArray, enumFormString); + + // TODO: test validations + } + /** + * test inline additionalProperties + * + * + */ + @Test + public void testInlineAdditionalPropertiesTest() { + Map requestBody = null; + // api.testInlineAdditionalProperties(requestBody); + + // TODO: test validations + } + /** + * test json serialization of form data + * + * + */ + @Test + public void testJsonFormDataTest() { + String param = null; + String param2 = null; + // api.testJsonFormData(param, param2); + + // TODO: test validations + } +} diff --git a/samples/client/petstore/java/retrofit2-play26/src/test/java/org/openapitools/client/api/FakeClassnameTags123ApiTest.java b/samples/client/petstore/java/retrofit2-play26/src/test/java/org/openapitools/client/api/FakeClassnameTags123ApiTest.java new file mode 100644 index 0000000000..e615576da2 --- /dev/null +++ b/samples/client/petstore/java/retrofit2-play26/src/test/java/org/openapitools/client/api/FakeClassnameTags123ApiTest.java @@ -0,0 +1,32 @@ +package org.openapitools.client.api; + +import org.junit.Before; +import org.junit.Test; +import org.openapitools.client.ApiClient; +import org.openapitools.client.model.Client; + +/** + * API tests for FakeClassnameTags123Api + */ +public class FakeClassnameTags123ApiTest { + + private FakeClassnameTags123Api api; + + @Before + public void setup() { + api = new ApiClient().createService(FakeClassnameTags123Api.class); + } + + /** + * To test class name in snake case + * + * To test class name in snake case + */ + @Test + public void testClassnameTest() { + Client client = null; + // Client response = api.testClassname(client); + + // TODO: test validations + } +} diff --git a/samples/client/petstore/java/retrofit2-play26/src/test/java/org/openapitools/client/api/PetApiTest.java b/samples/client/petstore/java/retrofit2-play26/src/test/java/org/openapitools/client/api/PetApiTest.java new file mode 100644 index 0000000000..9d7a40be31 --- /dev/null +++ b/samples/client/petstore/java/retrofit2-play26/src/test/java/org/openapitools/client/api/PetApiTest.java @@ -0,0 +1,138 @@ +package org.openapitools.client.api; + +import org.junit.Before; +import org.junit.Test; +import org.openapitools.client.ApiClient; +import org.openapitools.client.model.Pet; + +import java.io.File; +import java.util.List; + +/** + * API tests for PetApi + */ +public class PetApiTest { + + private PetApi api; + + @Before + public void setup() { + api = new ApiClient().createService(PetApi.class); + } + + /** + * Add a new pet to the store + * + * + */ + @Test + public void addPetTest() { + Pet pet = null; + // api.addPet(pet); + + // TODO: test validations + } + /** + * Deletes a pet + * + * + */ + @Test + public void deletePetTest() { + Long petId = null; + String apiKey = null; + // api.deletePet(petId, apiKey); + + // TODO: test validations + } + /** + * Finds Pets by status + * + * Multiple status values can be provided with comma separated strings + */ + @Test + public void findPetsByStatusTest() { + List status = null; + // List response = api.findPetsByStatus(status); + + // TODO: test validations + } + /** + * Finds Pets by tags + * + * Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. + */ + @Test + public void findPetsByTagsTest() { + List tags = null; + // List response = api.findPetsByTags(tags); + + // TODO: test validations + } + /** + * Find pet by ID + * + * Returns a single pet + */ + @Test + public void getPetByIdTest() { + Long petId = null; + // Pet response = api.getPetById(petId); + + // TODO: test validations + } + /** + * Update an existing pet + * + * + */ + @Test + public void updatePetTest() { + Pet pet = null; + // api.updatePet(pet); + + // TODO: test validations + } + /** + * Updates a pet in the store with form data + * + * + */ + @Test + public void updatePetWithFormTest() { + Long petId = null; + String name = null; + String status = null; + // api.updatePetWithForm(petId, name, status); + + // TODO: test validations + } + /** + * uploads an image + * + * + */ + @Test + public void uploadFileTest() { + Long petId = null; + String additionalMetadata = null; + File file = null; + // ModelApiResponse response = api.uploadFile(petId, additionalMetadata, file); + + // TODO: test validations + } + /** + * uploads an image (required) + * + * + */ + @Test + public void uploadFileWithRequiredFileTest() { + Long petId = null; + File requiredFile = null; + String additionalMetadata = null; + // ModelApiResponse response = api.uploadFileWithRequiredFile(petId, requiredFile, additionalMetadata); + + // TODO: test validations + } +} diff --git a/samples/client/petstore/java/retrofit2-play26/src/test/java/org/openapitools/client/api/StoreApiTest.java b/samples/client/petstore/java/retrofit2-play26/src/test/java/org/openapitools/client/api/StoreApiTest.java new file mode 100644 index 0000000000..90c204243b --- /dev/null +++ b/samples/client/petstore/java/retrofit2-play26/src/test/java/org/openapitools/client/api/StoreApiTest.java @@ -0,0 +1,67 @@ +package org.openapitools.client.api; + +import org.junit.Before; +import org.junit.Test; +import org.openapitools.client.ApiClient; +import org.openapitools.client.model.Order; + +/** + * API tests for StoreApi + */ +public class StoreApiTest { + + private StoreApi api; + + @Before + public void setup() { + api = new ApiClient().createService(StoreApi.class); + } + + /** + * Delete purchase order by ID + * + * For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors + */ + @Test + public void deleteOrderTest() { + String orderId = null; + // api.deleteOrder(orderId); + + // TODO: test validations + } + /** + * Returns pet inventories by status + * + * Returns a map of status codes to quantities + */ + @Test + public void getInventoryTest() { + // Map response = api.getInventory(); + + // TODO: test validations + } + /** + * Find purchase order by ID + * + * For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions + */ + @Test + public void getOrderByIdTest() { + Long orderId = null; + // Order response = api.getOrderById(orderId); + + // TODO: test validations + } + /** + * Place an order for a pet + * + * + */ + @Test + public void placeOrderTest() { + Order order = null; + // Order response = api.placeOrder(order); + + // TODO: test validations + } +} diff --git a/samples/client/petstore/java/retrofit2-play26/src/test/java/org/openapitools/client/api/UserApiTest.java b/samples/client/petstore/java/retrofit2-play26/src/test/java/org/openapitools/client/api/UserApiTest.java new file mode 100644 index 0000000000..c64cf2a1a6 --- /dev/null +++ b/samples/client/petstore/java/retrofit2-play26/src/test/java/org/openapitools/client/api/UserApiTest.java @@ -0,0 +1,119 @@ +package org.openapitools.client.api; + +import org.junit.Before; +import org.junit.Test; +import org.openapitools.client.ApiClient; +import org.openapitools.client.model.User; + +import java.util.List; + +/** + * API tests for UserApi + */ +public class UserApiTest { + + private UserApi api; + + @Before + public void setup() { + api = new ApiClient().createService(UserApi.class); + } + + /** + * Create user + * + * This can only be done by the logged in user. + */ + @Test + public void createUserTest() { + User user = null; + // api.createUser(user); + + // TODO: test validations + } + /** + * Creates list of users with given input array + * + * + */ + @Test + public void createUsersWithArrayInputTest() { + List user = null; + // api.createUsersWithArrayInput(user); + + // TODO: test validations + } + /** + * Creates list of users with given input array + * + * + */ + @Test + public void createUsersWithListInputTest() { + List user = null; + // api.createUsersWithListInput(user); + + // TODO: test validations + } + /** + * Delete user + * + * This can only be done by the logged in user. + */ + @Test + public void deleteUserTest() { + String username = null; + // api.deleteUser(username); + + // TODO: test validations + } + /** + * Get user by user name + * + * + */ + @Test + public void getUserByNameTest() { + String username = null; + // User response = api.getUserByName(username); + + // TODO: test validations + } + /** + * Logs user into the system + * + * + */ + @Test + public void loginUserTest() { + String username = null; + String password = null; + // String response = api.loginUser(username, password); + + // TODO: test validations + } + /** + * Logs out current logged in user session + * + * + */ + @Test + public void logoutUserTest() { + // api.logoutUser(); + + // TODO: test validations + } + /** + * Updated user + * + * This can only be done by the logged in user. + */ + @Test + public void updateUserTest() { + String username = null; + User user = null; + // api.updateUser(username, user); + + // TODO: test validations + } +} diff --git a/samples/client/petstore/java/retrofit2/build.gradle b/samples/client/petstore/java/retrofit2/build.gradle index f4017a3f71..5b2dbdafa3 100644 --- a/samples/client/petstore/java/retrofit2/build.gradle +++ b/samples/client/petstore/java/retrofit2/build.gradle @@ -96,7 +96,7 @@ if(hasProperty('target') && target == 'android') { ext { oltu_version = "1.0.1" retrofit_version = "2.3.0" - swagger_annotations_version = "1.5.17" + swagger_annotations_version = "1.5.21" junit_version = "4.12" threetenbp_version = "1.3.5" json_fire_version = "1.8.0" diff --git a/samples/client/petstore/java/retrofit2/build.sbt b/samples/client/petstore/java/retrofit2/build.sbt index ef3a285ecb..32ae300614 100644 --- a/samples/client/petstore/java/retrofit2/build.sbt +++ b/samples/client/petstore/java/retrofit2/build.sbt @@ -12,7 +12,7 @@ lazy val root = (project in file(".")). "com.squareup.retrofit2" % "retrofit" % "2.3.0" % "compile", "com.squareup.retrofit2" % "converter-scalars" % "2.3.0" % "compile", "com.squareup.retrofit2" % "converter-gson" % "2.3.0" % "compile", - "io.swagger" % "swagger-annotations" % "1.5.17" % "compile", + "io.swagger" % "swagger-annotations" % "1.5.21" % "compile", "org.apache.oltu.oauth2" % "org.apache.oltu.oauth2.client" % "1.0.1" % "compile", "org.threeten" % "threetenbp" % "1.3.5" % "compile", "io.gsonfire" % "gson-fire" % "1.8.0" % "compile", diff --git a/samples/client/petstore/java/retrofit2/pom.xml b/samples/client/petstore/java/retrofit2/pom.xml index eefa92c58a..6cba3499f5 100644 --- a/samples/client/petstore/java/retrofit2/pom.xml +++ b/samples/client/petstore/java/retrofit2/pom.xml @@ -114,8 +114,7 @@ - - src/main/java + src/main/java @@ -127,8 +126,7 @@ - - src/test/java + src/test/java @@ -191,7 +189,7 @@ io.swagger swagger-annotations - ${swagger-core-version} + ${swagger-annotations-version} com.squareup.retrofit2 @@ -229,9 +227,6 @@ threetenbp ${threetenbp-version} - - - junit @@ -246,9 +241,9 @@ ${java.version} ${java.version} 1.8.0 - 1.5.18 + 1.5.21 2.3.0 - 1.3.5 + 1.3.5 1.0.1 4.12
diff --git a/samples/client/petstore/java/retrofit2rx/build.gradle b/samples/client/petstore/java/retrofit2rx/build.gradle index 79af8dae49..9ea182cc72 100644 --- a/samples/client/petstore/java/retrofit2rx/build.gradle +++ b/samples/client/petstore/java/retrofit2rx/build.gradle @@ -96,7 +96,7 @@ if(hasProperty('target') && target == 'android') { ext { oltu_version = "1.0.1" retrofit_version = "2.3.0" - swagger_annotations_version = "1.5.17" + swagger_annotations_version = "1.5.21" junit_version = "4.12" rx_java_version = "1.3.0" threetenbp_version = "1.3.5" diff --git a/samples/client/petstore/java/retrofit2rx/build.sbt b/samples/client/petstore/java/retrofit2rx/build.sbt index 023b614314..1cabf93331 100644 --- a/samples/client/petstore/java/retrofit2rx/build.sbt +++ b/samples/client/petstore/java/retrofit2rx/build.sbt @@ -14,7 +14,7 @@ lazy val root = (project in file(".")). "com.squareup.retrofit2" % "converter-gson" % "2.3.0" % "compile", "com.squareup.retrofit2" % "adapter-rxjava" % "2.3.0" % "compile", "io.reactivex" % "rxjava" % "1.3.0" % "compile", - "io.swagger" % "swagger-annotations" % "1.5.17" % "compile", + "io.swagger" % "swagger-annotations" % "1.5.21" % "compile", "org.apache.oltu.oauth2" % "org.apache.oltu.oauth2.client" % "1.0.1" % "compile", "org.threeten" % "threetenbp" % "1.3.5" % "compile", "io.gsonfire" % "gson-fire" % "1.8.0" % "compile", diff --git a/samples/client/petstore/java/retrofit2rx/pom.xml b/samples/client/petstore/java/retrofit2rx/pom.xml index d438ede5b4..d764b2112d 100644 --- a/samples/client/petstore/java/retrofit2rx/pom.xml +++ b/samples/client/petstore/java/retrofit2rx/pom.xml @@ -114,8 +114,7 @@ - - src/main/java + src/main/java @@ -127,8 +126,7 @@ - - src/test/java + src/test/java @@ -191,7 +189,7 @@ io.swagger swagger-annotations - ${swagger-core-version} + ${swagger-annotations-version} com.squareup.retrofit2 @@ -239,9 +237,6 @@ adapter-rxjava ${retrofit-version} - - - junit @@ -256,10 +251,10 @@ ${java.version} ${java.version} 1.8.0 - 1.5.18 + 1.5.21 2.3.0 - 1.3.0 - 1.3.5 + 1.3.0 + 1.3.5 1.0.1 4.12
diff --git a/samples/client/petstore/java/retrofit2rx2/build.gradle b/samples/client/petstore/java/retrofit2rx2/build.gradle index fc7fcf23f4..44233fa581 100644 --- a/samples/client/petstore/java/retrofit2rx2/build.gradle +++ b/samples/client/petstore/java/retrofit2rx2/build.gradle @@ -96,7 +96,7 @@ if(hasProperty('target') && target == 'android') { ext { oltu_version = "1.0.1" retrofit_version = "2.3.0" - swagger_annotations_version = "1.5.17" + swagger_annotations_version = "1.5.21" junit_version = "4.12" rx_java_version = "2.1.1" threetenbp_version = "1.3.5" diff --git a/samples/client/petstore/java/retrofit2rx2/build.sbt b/samples/client/petstore/java/retrofit2rx2/build.sbt index 7385685986..fbdee2f168 100644 --- a/samples/client/petstore/java/retrofit2rx2/build.sbt +++ b/samples/client/petstore/java/retrofit2rx2/build.sbt @@ -14,7 +14,7 @@ lazy val root = (project in file(".")). "com.squareup.retrofit2" % "converter-gson" % "2.3.0" % "compile", "com.squareup.retrofit2" % "adapter-rxjava2" % "2.3.0" % "compile", "io.reactivex.rxjava2" % "rxjava" % "2.1.1" % "compile", - "io.swagger" % "swagger-annotations" % "1.5.17" % "compile", + "io.swagger" % "swagger-annotations" % "1.5.21" % "compile", "org.apache.oltu.oauth2" % "org.apache.oltu.oauth2.client" % "1.0.1" % "compile", "org.threeten" % "threetenbp" % "1.3.5" % "compile", "io.gsonfire" % "gson-fire" % "1.8.0" % "compile", diff --git a/samples/client/petstore/java/retrofit2rx2/pom.xml b/samples/client/petstore/java/retrofit2rx2/pom.xml index 0ffd258fae..316cedb4f2 100644 --- a/samples/client/petstore/java/retrofit2rx2/pom.xml +++ b/samples/client/petstore/java/retrofit2rx2/pom.xml @@ -114,8 +114,7 @@ - - src/main/java + src/main/java @@ -127,8 +126,7 @@ - - src/test/java + src/test/java @@ -191,7 +189,7 @@ io.swagger swagger-annotations - ${swagger-core-version} + ${swagger-annotations-version} com.squareup.retrofit2 @@ -239,9 +237,6 @@ adapter-rxjava2 ${retrofit-version} - - - junit @@ -256,10 +251,10 @@ ${java.version} ${java.version} 1.8.0 - 1.5.18 + 1.5.21 2.3.0 - 2.1.1 - 1.3.5 + 2.1.1 + 1.3.5 1.0.1 4.12
diff --git a/samples/client/petstore/java/vertx/build.gradle b/samples/client/petstore/java/vertx/build.gradle index b10a98e8f1..d55ccac8c3 100644 --- a/samples/client/petstore/java/vertx/build.gradle +++ b/samples/client/petstore/java/vertx/build.gradle @@ -26,7 +26,7 @@ task execute(type:JavaExec) { } ext { - swagger_annotations_version = "1.5.17" + swagger_annotations_version = "1.5.21" jackson_version = "2.6.4" vertx_version = "3.4.2" junit_version = "4.12" diff --git a/samples/client/petstore/java/vertx/pom.xml b/samples/client/petstore/java/vertx/pom.xml index a7e7b8bb4c..754d4660ca 100644 --- a/samples/client/petstore/java/vertx/pom.xml +++ b/samples/client/petstore/java/vertx/pom.xml @@ -114,8 +114,7 @@ - - src/main/java + src/main/java @@ -127,8 +126,7 @@ - - src/test/java + src/test/java @@ -200,7 +198,7 @@ io.swagger swagger-annotations - ${swagger-core-version} + ${swagger-annotations-version} @@ -260,7 +258,7 @@ UTF-8 3.4.2 - 1.5.18 + 1.5.21 2.6.4 4.12 diff --git a/samples/client/petstore/java/webclient/src/main/java/org/openapitools/client/ApiClient.java b/samples/client/petstore/java/webclient/src/main/java/org/openapitools/client/ApiClient.java index ee1885811e..460bd563c0 100644 --- a/samples/client/petstore/java/webclient/src/main/java/org/openapitools/client/ApiClient.java +++ b/samples/client/petstore/java/webclient/src/main/java/org/openapitools/client/ApiClient.java @@ -33,6 +33,7 @@ import org.springframework.web.reactive.function.BodyInserters; import org.springframework.web.reactive.function.client.ExchangeStrategies; import reactor.core.publisher.Mono; import reactor.core.publisher.Flux; +import java.util.Optional; import java.io.BufferedReader; import java.io.IOException; @@ -76,7 +77,7 @@ public class ApiClient { } private HttpHeaders defaultHeaders = new HttpHeaders(); - + private String basePath = "http://petstore.swagger.io:80/v2"; private final WebClient webClient; @@ -87,16 +88,22 @@ public class ApiClient { public ApiClient() { this.dateFormat = createDefaultDateFormat(); - this.webClient = buildWebClient(new ObjectMapper(), this.dateFormat); + this.webClient = buildWebClient(new ObjectMapper(), dateFormat); + this.init(); } public ApiClient(ObjectMapper mapper, DateFormat format) { this(buildWebClient(mapper.copy(), format), format); } + public ApiClient(WebClient webClient, ObjectMapper mapper, DateFormat format) { + this(Optional.ofNullable(webClient).orElseGet(() ->buildWebClient(mapper.copy(), format)), format); + } + private ApiClient(WebClient webClient, DateFormat format) { this.webClient = webClient; this.dateFormat = format; + this.init(); } public DateFormat createDefaultDateFormat() { @@ -104,7 +111,7 @@ public class ApiClient { dateFormat.setTimeZone(TimeZone.getTimeZone("UTC")); return dateFormat; } - + protected void init() { // Setup authentications (key: authentication name, value: authentication). authentications = new HashMap(); @@ -133,7 +140,7 @@ public class ApiClient { return webClient.build(); } - + /** * Get the current base path * @return String the base path @@ -586,7 +593,7 @@ public class ApiClient { auth.applyToParams(queryParams, headerParams); } } - + private class ApiClientHttpRequestInterceptor implements ClientHttpRequestInterceptor { private final Log log = LogFactory.getLog(ApiClientHttpRequestInterceptor.class); @@ -625,7 +632,7 @@ public class ApiClient { builder.setLength(builder.length() - 1); // Get rid of trailing comma return builder.toString(); } - + private String bodyToString(InputStream body) throws IOException { StringBuilder builder = new StringBuilder(); BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(body, StandardCharsets.UTF_8)); diff --git a/samples/client/petstore/python-asyncio/.openapi-generator/VERSION b/samples/client/petstore/python-asyncio/.openapi-generator/VERSION index dde25ef08e..c791c986fb 100644 --- a/samples/client/petstore/python-asyncio/.openapi-generator/VERSION +++ b/samples/client/petstore/python-asyncio/.openapi-generator/VERSION @@ -1 +1 @@ -3.1.1-SNAPSHOT \ No newline at end of file +3.2.3-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/python-asyncio/README.md b/samples/client/petstore/python-asyncio/README.md index b76d6153e8..6e6dbf6180 100644 --- a/samples/client/petstore/python-asyncio/README.md +++ b/samples/client/petstore/python-asyncio/README.md @@ -57,10 +57,10 @@ client = petstore_api.Client() # Client | client model try: # To test special tags - api_response = api_instance.test_special_tags(client) + api_response = api_instance.call_123_test_special_tags(client) pprint(api_response) except ApiException as e: - print("Exception when calling AnotherFakeApi->test_special_tags: %s\n" % e) + print("Exception when calling AnotherFakeApi->call_123_test_special_tags: %s\n" % e) ``` @@ -70,7 +70,7 @@ All URIs are relative to *http://petstore.swagger.io:80/v2* Class | Method | HTTP request | Description ------------ | ------------- | ------------- | ------------- -*AnotherFakeApi* | [**test_special_tags**](docs/AnotherFakeApi.md#test_special_tags) | **PATCH** /another-fake/dummy | To test special tags +*AnotherFakeApi* | [**call_123_test_special_tags**](docs/AnotherFakeApi.md#call_123_test_special_tags) | **PATCH** /another-fake/dummy | To test special tags *FakeApi* | [**fake_outer_boolean_serialize**](docs/FakeApi.md#fake_outer_boolean_serialize) | **POST** /fake/outer/boolean | *FakeApi* | [**fake_outer_composite_serialize**](docs/FakeApi.md#fake_outer_composite_serialize) | **POST** /fake/outer/composite | *FakeApi* | [**fake_outer_number_serialize**](docs/FakeApi.md#fake_outer_number_serialize) | **POST** /fake/outer/number | diff --git a/samples/client/petstore/python-asyncio/docs/AnotherFakeApi.md b/samples/client/petstore/python-asyncio/docs/AnotherFakeApi.md index 32d4fa0696..447ce3edde 100644 --- a/samples/client/petstore/python-asyncio/docs/AnotherFakeApi.md +++ b/samples/client/petstore/python-asyncio/docs/AnotherFakeApi.md @@ -4,15 +4,15 @@ All URIs are relative to *http://petstore.swagger.io:80/v2* Method | HTTP request | Description ------------- | ------------- | ------------- -[**test_special_tags**](AnotherFakeApi.md#test_special_tags) | **PATCH** /another-fake/dummy | To test special tags +[**call_123_test_special_tags**](AnotherFakeApi.md#call_123_test_special_tags) | **PATCH** /another-fake/dummy | To test special tags -# **test_special_tags** -> Client test_special_tags(client) +# **call_123_test_special_tags** +> Client call_123_test_special_tags(client) To test special tags -To test special tags +To test special tags and operation ID starting with number ### Example ```python @@ -28,10 +28,10 @@ client = petstore_api.Client() # Client | client model try: # To test special tags - api_response = api_instance.test_special_tags(client) + api_response = api_instance.call_123_test_special_tags(client) pprint(api_response) except ApiException as e: - print("Exception when calling AnotherFakeApi->test_special_tags: %s\n" % e) + print("Exception when calling AnotherFakeApi->call_123_test_special_tags: %s\n" % e) ``` ### Parameters diff --git a/samples/client/petstore/python-asyncio/petstore_api/api/another_fake_api.py b/samples/client/petstore/python-asyncio/petstore_api/api/another_fake_api.py index b753906b2e..782f7fd07b 100644 --- a/samples/client/petstore/python-asyncio/petstore_api/api/another_fake_api.py +++ b/samples/client/petstore/python-asyncio/petstore_api/api/another_fake_api.py @@ -32,13 +32,13 @@ class AnotherFakeApi(object): api_client = ApiClient() self.api_client = api_client - def test_special_tags(self, client, **kwargs): # noqa: E501 + def call_123_test_special_tags(self, client, **kwargs): # noqa: E501 """To test special tags # noqa: E501 - To test special tags # noqa: E501 + To test special tags and operation ID starting with number # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True - >>> thread = api.test_special_tags(client, async_req=True) + >>> thread = api.call_123_test_special_tags(client, async_req=True) >>> result = thread.get() :param async_req bool @@ -49,18 +49,18 @@ class AnotherFakeApi(object): """ kwargs['_return_http_data_only'] = True if kwargs.get('async_req'): - return self.test_special_tags_with_http_info(client, **kwargs) # noqa: E501 + return self.call_123_test_special_tags_with_http_info(client, **kwargs) # noqa: E501 else: - (data) = self.test_special_tags_with_http_info(client, **kwargs) # noqa: E501 + (data) = self.call_123_test_special_tags_with_http_info(client, **kwargs) # noqa: E501 return data - def test_special_tags_with_http_info(self, client, **kwargs): # noqa: E501 + def call_123_test_special_tags_with_http_info(self, client, **kwargs): # noqa: E501 """To test special tags # noqa: E501 - To test special tags # noqa: E501 + To test special tags and operation ID starting with number # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True - >>> thread = api.test_special_tags_with_http_info(client, async_req=True) + >>> thread = api.call_123_test_special_tags_with_http_info(client, async_req=True) >>> result = thread.get() :param async_req bool @@ -82,14 +82,14 @@ class AnotherFakeApi(object): if key not in all_params: raise TypeError( "Got an unexpected keyword argument '%s'" - " to method test_special_tags" % key + " to method call_123_test_special_tags" % key ) local_var_params[key] = val del local_var_params['kwargs'] # verify the required parameter 'client' is set if ('client' not in local_var_params or local_var_params['client'] is None): - raise ValueError("Missing the required parameter `client` when calling `test_special_tags`") # noqa: E501 + raise ValueError("Missing the required parameter `client` when calling `call_123_test_special_tags`") # noqa: E501 collection_formats = {} diff --git a/samples/client/petstore/python-asyncio/petstore_api/rest.py b/samples/client/petstore/python-asyncio/petstore_api/rest.py index f0ac582a69..ce7eaf118d 100644 --- a/samples/client/petstore/python-asyncio/petstore_api/rest.py +++ b/samples/client/petstore/python-asyncio/petstore_api/rest.py @@ -46,21 +46,24 @@ class RESTClientObject(object): def __init__(self, configuration, pools_size=4, maxsize=4): # maxsize is number of requests to host that are allowed in parallel - # ca_certs vs cert_file vs key_file - # http://stackoverflow.com/a/23957365/2985775 - # ca_certs - if configuration.ssl_ca_cert: - ca_certs = configuration.ssl_ca_cert + if configuration.verify_ssl: + + # ca_certs + if configuration.ssl_ca_cert: + ca_certs = configuration.ssl_ca_cert + else: + # if not set certificate file, use Mozilla's root certificates. + ca_certs = certifi.where() + + ssl_context = ssl.create_default_context(cafile=ca_certs) + + if configuration.cert_file: + ssl_context.load_cert_chain( + configuration.cert_file, keyfile=configuration.key_file + ) else: - # if not set certificate file, use Mozilla's root certificates. - ca_certs = certifi.where() - - ssl_context = ssl.create_default_context(cafile=ca_certs) - if configuration.cert_file: - ssl_context.load_cert_chain( - configuration.cert_file, keyfile=configuration.key_file - ) + ssl_context = None connector = aiohttp.TCPConnector( limit=maxsize, diff --git a/samples/client/petstore/python-tornado/.openapi-generator/VERSION b/samples/client/petstore/python-tornado/.openapi-generator/VERSION index dde25ef08e..c791c986fb 100644 --- a/samples/client/petstore/python-tornado/.openapi-generator/VERSION +++ b/samples/client/petstore/python-tornado/.openapi-generator/VERSION @@ -1 +1 @@ -3.1.1-SNAPSHOT \ No newline at end of file +3.2.3-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/python-tornado/README.md b/samples/client/petstore/python-tornado/README.md index b76d6153e8..6e6dbf6180 100644 --- a/samples/client/petstore/python-tornado/README.md +++ b/samples/client/petstore/python-tornado/README.md @@ -57,10 +57,10 @@ client = petstore_api.Client() # Client | client model try: # To test special tags - api_response = api_instance.test_special_tags(client) + api_response = api_instance.call_123_test_special_tags(client) pprint(api_response) except ApiException as e: - print("Exception when calling AnotherFakeApi->test_special_tags: %s\n" % e) + print("Exception when calling AnotherFakeApi->call_123_test_special_tags: %s\n" % e) ``` @@ -70,7 +70,7 @@ All URIs are relative to *http://petstore.swagger.io:80/v2* Class | Method | HTTP request | Description ------------ | ------------- | ------------- | ------------- -*AnotherFakeApi* | [**test_special_tags**](docs/AnotherFakeApi.md#test_special_tags) | **PATCH** /another-fake/dummy | To test special tags +*AnotherFakeApi* | [**call_123_test_special_tags**](docs/AnotherFakeApi.md#call_123_test_special_tags) | **PATCH** /another-fake/dummy | To test special tags *FakeApi* | [**fake_outer_boolean_serialize**](docs/FakeApi.md#fake_outer_boolean_serialize) | **POST** /fake/outer/boolean | *FakeApi* | [**fake_outer_composite_serialize**](docs/FakeApi.md#fake_outer_composite_serialize) | **POST** /fake/outer/composite | *FakeApi* | [**fake_outer_number_serialize**](docs/FakeApi.md#fake_outer_number_serialize) | **POST** /fake/outer/number | diff --git a/samples/client/petstore/python-tornado/docs/AnotherFakeApi.md b/samples/client/petstore/python-tornado/docs/AnotherFakeApi.md index 32d4fa0696..447ce3edde 100644 --- a/samples/client/petstore/python-tornado/docs/AnotherFakeApi.md +++ b/samples/client/petstore/python-tornado/docs/AnotherFakeApi.md @@ -4,15 +4,15 @@ All URIs are relative to *http://petstore.swagger.io:80/v2* Method | HTTP request | Description ------------- | ------------- | ------------- -[**test_special_tags**](AnotherFakeApi.md#test_special_tags) | **PATCH** /another-fake/dummy | To test special tags +[**call_123_test_special_tags**](AnotherFakeApi.md#call_123_test_special_tags) | **PATCH** /another-fake/dummy | To test special tags -# **test_special_tags** -> Client test_special_tags(client) +# **call_123_test_special_tags** +> Client call_123_test_special_tags(client) To test special tags -To test special tags +To test special tags and operation ID starting with number ### Example ```python @@ -28,10 +28,10 @@ client = petstore_api.Client() # Client | client model try: # To test special tags - api_response = api_instance.test_special_tags(client) + api_response = api_instance.call_123_test_special_tags(client) pprint(api_response) except ApiException as e: - print("Exception when calling AnotherFakeApi->test_special_tags: %s\n" % e) + print("Exception when calling AnotherFakeApi->call_123_test_special_tags: %s\n" % e) ``` ### Parameters diff --git a/samples/client/petstore/python-tornado/petstore_api/api/another_fake_api.py b/samples/client/petstore/python-tornado/petstore_api/api/another_fake_api.py index b753906b2e..782f7fd07b 100644 --- a/samples/client/petstore/python-tornado/petstore_api/api/another_fake_api.py +++ b/samples/client/petstore/python-tornado/petstore_api/api/another_fake_api.py @@ -32,13 +32,13 @@ class AnotherFakeApi(object): api_client = ApiClient() self.api_client = api_client - def test_special_tags(self, client, **kwargs): # noqa: E501 + def call_123_test_special_tags(self, client, **kwargs): # noqa: E501 """To test special tags # noqa: E501 - To test special tags # noqa: E501 + To test special tags and operation ID starting with number # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True - >>> thread = api.test_special_tags(client, async_req=True) + >>> thread = api.call_123_test_special_tags(client, async_req=True) >>> result = thread.get() :param async_req bool @@ -49,18 +49,18 @@ class AnotherFakeApi(object): """ kwargs['_return_http_data_only'] = True if kwargs.get('async_req'): - return self.test_special_tags_with_http_info(client, **kwargs) # noqa: E501 + return self.call_123_test_special_tags_with_http_info(client, **kwargs) # noqa: E501 else: - (data) = self.test_special_tags_with_http_info(client, **kwargs) # noqa: E501 + (data) = self.call_123_test_special_tags_with_http_info(client, **kwargs) # noqa: E501 return data - def test_special_tags_with_http_info(self, client, **kwargs): # noqa: E501 + def call_123_test_special_tags_with_http_info(self, client, **kwargs): # noqa: E501 """To test special tags # noqa: E501 - To test special tags # noqa: E501 + To test special tags and operation ID starting with number # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True - >>> thread = api.test_special_tags_with_http_info(client, async_req=True) + >>> thread = api.call_123_test_special_tags_with_http_info(client, async_req=True) >>> result = thread.get() :param async_req bool @@ -82,14 +82,14 @@ class AnotherFakeApi(object): if key not in all_params: raise TypeError( "Got an unexpected keyword argument '%s'" - " to method test_special_tags" % key + " to method call_123_test_special_tags" % key ) local_var_params[key] = val del local_var_params['kwargs'] # verify the required parameter 'client' is set if ('client' not in local_var_params or local_var_params['client'] is None): - raise ValueError("Missing the required parameter `client` when calling `test_special_tags`") # noqa: E501 + raise ValueError("Missing the required parameter `client` when calling `call_123_test_special_tags`") # noqa: E501 collection_formats = {} diff --git a/samples/client/petstore/python/.openapi-generator/VERSION b/samples/client/petstore/python/.openapi-generator/VERSION index 4395ff5923..c791c986fb 100644 --- a/samples/client/petstore/python/.openapi-generator/VERSION +++ b/samples/client/petstore/python/.openapi-generator/VERSION @@ -1 +1 @@ -3.2.0-SNAPSHOT \ No newline at end of file +3.2.3-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/python/README.md b/samples/client/petstore/python/README.md index b76d6153e8..6e6dbf6180 100644 --- a/samples/client/petstore/python/README.md +++ b/samples/client/petstore/python/README.md @@ -57,10 +57,10 @@ client = petstore_api.Client() # Client | client model try: # To test special tags - api_response = api_instance.test_special_tags(client) + api_response = api_instance.call_123_test_special_tags(client) pprint(api_response) except ApiException as e: - print("Exception when calling AnotherFakeApi->test_special_tags: %s\n" % e) + print("Exception when calling AnotherFakeApi->call_123_test_special_tags: %s\n" % e) ``` @@ -70,7 +70,7 @@ All URIs are relative to *http://petstore.swagger.io:80/v2* Class | Method | HTTP request | Description ------------ | ------------- | ------------- | ------------- -*AnotherFakeApi* | [**test_special_tags**](docs/AnotherFakeApi.md#test_special_tags) | **PATCH** /another-fake/dummy | To test special tags +*AnotherFakeApi* | [**call_123_test_special_tags**](docs/AnotherFakeApi.md#call_123_test_special_tags) | **PATCH** /another-fake/dummy | To test special tags *FakeApi* | [**fake_outer_boolean_serialize**](docs/FakeApi.md#fake_outer_boolean_serialize) | **POST** /fake/outer/boolean | *FakeApi* | [**fake_outer_composite_serialize**](docs/FakeApi.md#fake_outer_composite_serialize) | **POST** /fake/outer/composite | *FakeApi* | [**fake_outer_number_serialize**](docs/FakeApi.md#fake_outer_number_serialize) | **POST** /fake/outer/number | diff --git a/samples/client/petstore/python/docs/AnotherFakeApi.md b/samples/client/petstore/python/docs/AnotherFakeApi.md index 32d4fa0696..447ce3edde 100644 --- a/samples/client/petstore/python/docs/AnotherFakeApi.md +++ b/samples/client/petstore/python/docs/AnotherFakeApi.md @@ -4,15 +4,15 @@ All URIs are relative to *http://petstore.swagger.io:80/v2* Method | HTTP request | Description ------------- | ------------- | ------------- -[**test_special_tags**](AnotherFakeApi.md#test_special_tags) | **PATCH** /another-fake/dummy | To test special tags +[**call_123_test_special_tags**](AnotherFakeApi.md#call_123_test_special_tags) | **PATCH** /another-fake/dummy | To test special tags -# **test_special_tags** -> Client test_special_tags(client) +# **call_123_test_special_tags** +> Client call_123_test_special_tags(client) To test special tags -To test special tags +To test special tags and operation ID starting with number ### Example ```python @@ -28,10 +28,10 @@ client = petstore_api.Client() # Client | client model try: # To test special tags - api_response = api_instance.test_special_tags(client) + api_response = api_instance.call_123_test_special_tags(client) pprint(api_response) except ApiException as e: - print("Exception when calling AnotherFakeApi->test_special_tags: %s\n" % e) + print("Exception when calling AnotherFakeApi->call_123_test_special_tags: %s\n" % e) ``` ### Parameters diff --git a/samples/client/petstore/python/petstore_api/api/another_fake_api.py b/samples/client/petstore/python/petstore_api/api/another_fake_api.py index b753906b2e..782f7fd07b 100644 --- a/samples/client/petstore/python/petstore_api/api/another_fake_api.py +++ b/samples/client/petstore/python/petstore_api/api/another_fake_api.py @@ -32,13 +32,13 @@ class AnotherFakeApi(object): api_client = ApiClient() self.api_client = api_client - def test_special_tags(self, client, **kwargs): # noqa: E501 + def call_123_test_special_tags(self, client, **kwargs): # noqa: E501 """To test special tags # noqa: E501 - To test special tags # noqa: E501 + To test special tags and operation ID starting with number # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True - >>> thread = api.test_special_tags(client, async_req=True) + >>> thread = api.call_123_test_special_tags(client, async_req=True) >>> result = thread.get() :param async_req bool @@ -49,18 +49,18 @@ class AnotherFakeApi(object): """ kwargs['_return_http_data_only'] = True if kwargs.get('async_req'): - return self.test_special_tags_with_http_info(client, **kwargs) # noqa: E501 + return self.call_123_test_special_tags_with_http_info(client, **kwargs) # noqa: E501 else: - (data) = self.test_special_tags_with_http_info(client, **kwargs) # noqa: E501 + (data) = self.call_123_test_special_tags_with_http_info(client, **kwargs) # noqa: E501 return data - def test_special_tags_with_http_info(self, client, **kwargs): # noqa: E501 + def call_123_test_special_tags_with_http_info(self, client, **kwargs): # noqa: E501 """To test special tags # noqa: E501 - To test special tags # noqa: E501 + To test special tags and operation ID starting with number # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True - >>> thread = api.test_special_tags_with_http_info(client, async_req=True) + >>> thread = api.call_123_test_special_tags_with_http_info(client, async_req=True) >>> result = thread.get() :param async_req bool @@ -82,14 +82,14 @@ class AnotherFakeApi(object): if key not in all_params: raise TypeError( "Got an unexpected keyword argument '%s'" - " to method test_special_tags" % key + " to method call_123_test_special_tags" % key ) local_var_params[key] = val del local_var_params['kwargs'] # verify the required parameter 'client' is set if ('client' not in local_var_params or local_var_params['client'] is None): - raise ValueError("Missing the required parameter `client` when calling `test_special_tags`") # noqa: E501 + raise ValueError("Missing the required parameter `client` when calling `call_123_test_special_tags`") # noqa: E501 collection_formats = {} diff --git a/samples/meta-codegen/lib/README.md b/samples/meta-codegen/lib/README.md index e970d9f068..9490713343 100644 --- a/samples/meta-codegen/lib/README.md +++ b/samples/meta-codegen/lib/README.md @@ -1,15 +1,16 @@ # OpenAPI Generator for the myClientCodegen library ## Overview -This is a boiler-plate project to generate your own client library with Swagger. Its goal is -to get you started with the basic plumbing so you can put in your own logic. It won't work without -your changes applied. +This is a boiler-plate project to generate your own project derived from an OpenAPI specification. +Its goal is to get you started with the basic plumbing so you can put in your own logic. +It won't work without your changes applied. -## What's Swagger? -The goal of Swagger™ is to define a standard, language-agnostic interface to REST APIs which allows both humans and computers to discover and understand the capabilities of the service without access to source code, documentation, or through network traffic inspection. When properly defined via Swagger, a consumer can understand and interact with the remote service with a minimal amount of implementation logic. Similar to what interfaces have done for lower-level programming, Swagger removes the guesswork in calling the service. +## What's OpenAPI +The goal of OpenAPI is to define a standard, language-agnostic interface to REST APIs which allows both humans and computers to discover and understand the capabilities of the service without access to source code, documentation, or through network traffic inspection. +When properly described with OpenAPI, a consumer can understand and interact with the remote service with a minimal amount of implementation logic. +Similar to what interfaces have done for lower-level programming, OpenAPI removes the guesswork in calling the service. - -Check out [OpenAPI-Spec](https://github.com/OAI/OpenAPI-Specification) for additional information about the Swagger project, including additional libraries with support for other languages and more. +Check out [OpenAPI-Spec](https://github.com/OAI/OpenAPI-Specification) for additional information about the OpenAPI project, including additional libraries with support for other languages and more. ## How do I use this? At this point, you've likely generated a client setup. It will include something along these lines: @@ -43,10 +44,17 @@ Once modified, you can run this: mvn package ``` -In your generator project. A single jar file will be produced in `target`. You can now use that with codegen: +In your generator project. A single jar file will be produced in `target`. You can now use that with [OpenAPI Generator](https://openapi-generator.tech): +For mac/linux: ``` -java -cp /path/to/openapi-generator-cli.jar:/path/to/your.jar org.openapitools.codegen.Codegen -g myClientCodegen -i /path/to/openapi.yaml -o ./test +java -cp /path/to/openapi-generator-cli.jar:/path/to/your.jar org.openapitools.codegen.OpenAPIGenerator generate -g myClientCodegen -i /path/to/openapi.yaml -o ./test +``` +(Do not forget to replace the values `/path/to/openapi-generator-cli.jar`, `/path/to/your.jar` and `/path/to/openapi.yaml` in the previous command) + +For Windows users, you will need to use `;` instead of `:` in the classpath, e.g. +``` +java -cp /path/to/openapi-generator-cli.jar;/path/to/your.jar org.openapitools.codegen.OpenAPIGenerator generate -g myClientCodegen -i /path/to/openapi.yaml -o ./test ``` Now your templates are available to the client generator and you can write output values @@ -62,13 +70,13 @@ the object you have available during client generation: ``` # The following additional debug options are available for all codegen targets: -# -DdebugSwagger prints the OpenAPI Specification as interpreted by the codegen +# -DdebugOpenAPI prints the OpenAPI Specification as interpreted by the codegen # -DdebugModels prints models passed to the template engine # -DdebugOperations prints operations passed to the template engine # -DdebugSupportingFiles prints additional data passed to the template engine -java -DdebugOperations -cp /path/to/openapi-generator-cli.jar:/path/to/your.jar org.openapitools.codegen.Codegen -g myClientCodegen -i /path/to/swagger.yaml -o ./test +java -DdebugOperations -cp /path/to/openapi-generator-cli.jar:/path/to/your.jar org.openapitools.codegen.OpenAPIGenerator generate -g myClientCodegen -i /path/to/openapi.yaml -o ./test ``` -Will, for example, output the debug info for operations. You can use this info -in the `api.mustache` file. \ No newline at end of file +Will, for example, output the debug info for operations. +You can use this info in the `api.mustache` file. \ No newline at end of file diff --git a/samples/meta-codegen/lib/pom.xml b/samples/meta-codegen/lib/pom.xml index dd8dcf14fe..b2d69d5251 100644 --- a/samples/meta-codegen/lib/pom.xml +++ b/samples/meta-codegen/lib/pom.xml @@ -100,8 +100,8 @@ maven-compiler-plugin 3.6.1 - 1.7 - 1.7 + 1.8 + 1.8 @@ -116,7 +116,7 @@ UTF-8 - 3.0.0-SNAPSHOT + 3.2.3 1.0.0 4.8.1 diff --git a/samples/meta-codegen/lib/src/main/java/com/my/company/codegen/MyclientcodegenGenerator.java b/samples/meta-codegen/lib/src/main/java/com/my/company/codegen/MyclientcodegenGenerator.java index 877b577838..fd43a34251 100644 --- a/samples/meta-codegen/lib/src/main/java/com/my/company/codegen/MyclientcodegenGenerator.java +++ b/samples/meta-codegen/lib/src/main/java/com/my/company/codegen/MyclientcodegenGenerator.java @@ -19,7 +19,7 @@ public class MyclientcodegenGenerator extends DefaultCodegen implements CodegenC * @see org.openapitools.codegen.CodegenType */ public CodegenType getTag() { - return CodegenType.CLIENT; + return CodegenType.DOCUMENTATION; } /** diff --git a/samples/meta-codegen/pom.xml b/samples/meta-codegen/pom.xml new file mode 100644 index 0000000000..fc3ad25673 --- /dev/null +++ b/samples/meta-codegen/pom.xml @@ -0,0 +1,12 @@ + + 4.0.0 + org.openapitools + meta-codegen + 1.0.0 + pom + + lib/ + ../../modules/openapi-generator + + diff --git a/samples/meta-codegen/usage/.openapi-generator/VERSION b/samples/meta-codegen/usage/.openapi-generator/VERSION index 096bf47efe..c791c986fb 100644 --- a/samples/meta-codegen/usage/.openapi-generator/VERSION +++ b/samples/meta-codegen/usage/.openapi-generator/VERSION @@ -1 +1 @@ -3.0.0-SNAPSHOT \ No newline at end of file +3.2.3-SNAPSHOT \ No newline at end of file diff --git a/samples/server/openapi3/petstore/kotlin-springboot/.openapi-generator-ignore b/samples/server/openapi3/petstore/kotlin-springboot/.openapi-generator-ignore new file mode 100644 index 0000000000..7484ee590a --- /dev/null +++ b/samples/server/openapi3/petstore/kotlin-springboot/.openapi-generator-ignore @@ -0,0 +1,23 @@ +# OpenAPI Generator Ignore +# Generated by openapi-generator https://github.com/openapitools/openapi-generator + +# Use this file to prevent files from being overwritten by the generator. +# The patterns follow closely to .gitignore or .dockerignore. + +# As an example, the C# client generator defines ApiClient.cs. +# You can make changes and tell OpenAPI Generator to ignore just this file by uncommenting the following line: +#ApiClient.cs + +# You can match any string of characters against a directory, file or extension with a single asterisk (*): +#foo/*/qux +# The above matches foo/bar/qux and foo/baz/qux, but not foo/bar/baz/qux + +# You can recursively match patterns against a directory, file or extension with a double asterisk (**): +#foo/**/qux +# This matches foo/bar/qux, foo/baz/qux, and foo/bar/baz/qux + +# You can also negate patterns with an exclamation (!). +# For example, you can ignore all files in a docs folder with the file extension .md: +#docs/*.md +# Then explicitly reverse the ignore rule for a single file: +#!docs/README.md diff --git a/samples/server/openapi3/petstore/kotlin-springboot/.openapi-generator/VERSION b/samples/server/openapi3/petstore/kotlin-springboot/.openapi-generator/VERSION new file mode 100644 index 0000000000..c791c986fb --- /dev/null +++ b/samples/server/openapi3/petstore/kotlin-springboot/.openapi-generator/VERSION @@ -0,0 +1 @@ +3.2.3-SNAPSHOT \ No newline at end of file diff --git a/samples/server/openapi3/petstore/kotlin-springboot/README.md b/samples/server/openapi3/petstore/kotlin-springboot/README.md new file mode 100644 index 0000000000..b6865a0811 --- /dev/null +++ b/samples/server/openapi3/petstore/kotlin-springboot/README.md @@ -0,0 +1,21 @@ +# openAPIPetstore + +This Kotlin based [Spring Boot](https://spring.io/projects/spring-boot) application has been generated using the [OpenAPI Generator](https://github.com/OpenAPITools/openapi-generator). + +## Getting Started + +This document assumes you have either maven or gradle available, either via the wrapper or otherwise. This does not come with a gradle / maven wrapper checked in. + +By default a [`pom.xml`](pom.xml) file will be generated. If you specified `gradleBuildFile=true` when generating this project, a `build.gradle.kts` will also be generated. Note this uses [Gradle Kotlin DSL](https://github.com/gradle/kotlin-dsl). + +To build the project using maven, run: +```bash +mvn package && java -jar target/openapi-spring-1.0.0.jar +``` + +To build the project using gradle, run: +```bash +gradle build && java -jar build/libs/openapi-spring-1.0.0.jar +``` + +If all builds successfully, the server should run on [http://localhost:8080/](http://localhost:8080/) diff --git a/samples/server/openapi3/petstore/kotlin-springboot/build.gradle.kts b/samples/server/openapi3/petstore/kotlin-springboot/build.gradle.kts new file mode 100644 index 0000000000..b5a8fef745 --- /dev/null +++ b/samples/server/openapi3/petstore/kotlin-springboot/build.gradle.kts @@ -0,0 +1,45 @@ +import org.jetbrains.kotlin.gradle.tasks.KotlinCompile + +buildscript { + repositories { + jcenter() + mavenCentral() + } + dependencies { + classpath("org.springframework.boot:spring-boot-gradle-plugin:2.0.3.RELEASE") + } +} + +group = "org.openapitools" +version = "1.0.0" + +repositories { + jcenter() + mavenCentral() +} + +tasks.withType { + kotlinOptions.jvmTarget = "1.8" +} + +plugins { + val kotlinVersion = "1.2.60" + id("org.jetbrains.kotlin.jvm") version kotlinVersion + id("org.jetbrains.kotlin.plugin.jpa") version kotlinVersion + id("org.jetbrains.kotlin.plugin.spring") version kotlinVersion + id("org.springframework.boot") version "2.0.3.RELEASE" + id("io.spring.dependency-management") version "1.0.5.RELEASE" +} + +dependencies { + compile("org.jetbrains.kotlin:kotlin-stdlib-jdk8") + compile("org.jetbrains.kotlin:kotlin-reflect") + compile("org.springframework.boot:spring-boot-starter-web") + compile("io.swagger:swagger-annotations:1.5.21") + compile("com.fasterxml.jackson.dataformat:jackson-dataformat-yaml") + compile("com.fasterxml.jackson.dataformat:jackson-dataformat-xml") + + testCompile("org.springframework.boot:spring-boot-starter-test") { + exclude(module = "junit") + } +} diff --git a/samples/server/openapi3/petstore/kotlin-springboot/pom.xml b/samples/server/openapi3/petstore/kotlin-springboot/pom.xml new file mode 100644 index 0000000000..fb79c82cca --- /dev/null +++ b/samples/server/openapi3/petstore/kotlin-springboot/pom.xml @@ -0,0 +1,105 @@ + + 4.0.0 + org.openapitools + openapi-spring + jar + openapi-spring + 1.0.0 + + 1.2.60 + + + org.springframework.boot + spring-boot-starter-parent + 2.0.3.RELEASE + + + ${project.basedir}/src/main/kotlin + ${project.basedir}/src/test/kotlin + + + org.springframework.boot + spring-boot-maven-plugin + + + + repackage + + + + + + kotlin-maven-plugin + org.jetbrains.kotlin + ${kotlin.version} + + + spring + + 1.8 + + + + compile + compile + + compile + + + + test-compile + test-compile + + test-compile + + + + + + org.jetbrains.kotlin + kotlin-maven-allopen + ${kotlin.version} + + + + + + + + org.jetbrains.kotlin + kotlin-stdlib-jdk8 + ${kotlin.version} + + + org.jetbrains.kotlin + kotlin-reflect + ${kotlin.version} + + + org.springframework.boot + spring-boot-starter-web + + + io.swagger + swagger-annotations + 1.5.21 + + + com.fasterxml.jackson.dataformat + jackson-dataformat-yaml + + + com.fasterxml.jackson.dataformat + jackson-dataformat-xml + + + com.fasterxml.jackson.datatype + jackson-datatype-jsr310 + + + + javax.validation + validation-api + + + diff --git a/samples/server/openapi3/petstore/kotlin-springboot/settings.gradle b/samples/server/openapi3/petstore/kotlin-springboot/settings.gradle new file mode 100644 index 0000000000..f0dd035311 --- /dev/null +++ b/samples/server/openapi3/petstore/kotlin-springboot/settings.gradle @@ -0,0 +1 @@ +rootProject.name = "openapi-spring" \ No newline at end of file diff --git a/samples/server/openapi3/petstore/kotlin-springboot/src/main/kotlin/org/openapitools/Application.kt b/samples/server/openapi3/petstore/kotlin-springboot/src/main/kotlin/org/openapitools/Application.kt new file mode 100644 index 0000000000..f2ee49d476 --- /dev/null +++ b/samples/server/openapi3/petstore/kotlin-springboot/src/main/kotlin/org/openapitools/Application.kt @@ -0,0 +1,14 @@ +package org.openapitools + +import org.springframework.boot.runApplication +import org.springframework.context.annotation.ComponentScan +import org.springframework.boot.autoconfigure.SpringBootApplication + + +@SpringBootApplication +@ComponentScan(basePackages = ["org.openapitools", "org.openapitools.api", "org.openapitools.model"]) +class Application + +fun main(args: Array) { + runApplication(*args) +} diff --git a/samples/server/openapi3/petstore/kotlin-springboot/src/main/kotlin/org/openapitools/api/Exceptions.kt b/samples/server/openapi3/petstore/kotlin-springboot/src/main/kotlin/org/openapitools/api/Exceptions.kt new file mode 100644 index 0000000000..4d8400902a --- /dev/null +++ b/samples/server/openapi3/petstore/kotlin-springboot/src/main/kotlin/org/openapitools/api/Exceptions.kt @@ -0,0 +1,29 @@ +package org.openapitools.api + +import org.springframework.http.HttpStatus +import org.springframework.web.bind.annotation.ControllerAdvice +import org.springframework.web.bind.annotation.ExceptionHandler +import javax.servlet.http.HttpServletResponse +import javax.validation.ConstraintViolationException + +// TODO Extend ApiException for custom exception handling, e.g. the below NotFound exception +sealed class ApiException(msg: String, val code: Int) : Exception(msg) + +class NotFoundException(msg: String, code: Int = HttpStatus.NOT_FOUND.value()) : ApiException(msg, code) + + +@ControllerAdvice +class DefaultExceptionHandler { + + @ExceptionHandler(value = [ApiException::class]) + fun onApiException(ex: ApiException, response: HttpServletResponse): Unit = + response.sendError(ex.code, ex.message) + + @ExceptionHandler(value = [NotImplementedError::class]) + fun onNotImplemented(ex: NotImplementedError, response: HttpServletResponse): Unit = + response.sendError(HttpStatus.NOT_IMPLEMENTED.value()) + + @ExceptionHandler(value = [ConstraintViolationException::class]) + fun onConstraintViolation(ex: ConstraintViolationException, response: HttpServletResponse): Unit = + response.sendError(HttpStatus.BAD_REQUEST.value(), ex.constraintViolations.joinToString(", ") { it.message }) +} diff --git a/samples/server/openapi3/petstore/kotlin-springboot/src/main/kotlin/org/openapitools/api/PetApi.kt b/samples/server/openapi3/petstore/kotlin-springboot/src/main/kotlin/org/openapitools/api/PetApi.kt new file mode 100644 index 0000000000..05aee6becb --- /dev/null +++ b/samples/server/openapi3/petstore/kotlin-springboot/src/main/kotlin/org/openapitools/api/PetApi.kt @@ -0,0 +1,159 @@ +package org.openapitools.api + +import org.openapitools.model.ModelApiResponse +import org.openapitools.model.Pet +import io.swagger.annotations.* +import org.springframework.http.HttpStatus +import org.springframework.http.MediaType +import org.springframework.http.ResponseEntity +import org.springframework.stereotype.Controller +import org.springframework.web.bind.annotation.RequestBody +import org.springframework.web.bind.annotation.RequestPart +import org.springframework.web.bind.annotation.RequestParam +import org.springframework.web.bind.annotation.PathVariable +import org.springframework.web.bind.annotation.RequestHeader +import org.springframework.web.bind.annotation.RequestMethod +import org.springframework.web.bind.annotation.RequestMapping +import org.springframework.validation.annotation.Validated +import org.springframework.web.context.request.NativeWebRequest +import org.springframework.web.multipart.MultipartFile +import org.springframework.beans.factory.annotation.Autowired + +import javax.validation.Valid +import javax.validation.constraints.* + +import kotlin.collections.List +import kotlin.collections.Map + +@Controller +@Validated +@Api(value = "Pet", description = "The Pet API") +@RequestMapping("\${openapi.openAPIPetstore.base-path:/v2}") +class PetApiController(@Autowired(required = true) val service: PetApiService) { + + @ApiOperation( + value = "Add a new pet to the store", + nickname = "addPet", + notes = "", + authorizations = [Authorization(value = "petstore_auth", scopes = [AuthorizationScope(scope = "write:pets", description = "modify pets in your account"), AuthorizationScope(scope = "read:pets", description = "read your pets")])]) + @ApiResponses( + value = [ApiResponse(code = 405, message = "Invalid input")]) + @RequestMapping( + value = ["/pet"], + consumes = ["application/json", "application/xml"], + method = [RequestMethod.POST]) + fun addPet(@ApiParam(value = "Pet object that needs to be added to the store" ,required=true ) @Valid @RequestBody pet: Pet): ResponseEntity { + return ResponseEntity(service.addPet(pet), HttpStatus.OK) + } + + @ApiOperation( + value = "Deletes a pet", + nickname = "deletePet", + notes = "", + authorizations = [Authorization(value = "petstore_auth", scopes = [AuthorizationScope(scope = "write:pets", description = "modify pets in your account"), AuthorizationScope(scope = "read:pets", description = "read your pets")])]) + @ApiResponses( + value = [ApiResponse(code = 400, message = "Invalid pet value")]) + @RequestMapping( + value = ["/pet/{petId}"], + method = [RequestMethod.DELETE]) + fun deletePet(@ApiParam(value = "Pet id to delete", required=true) @PathVariable("petId") petId: kotlin.Long,@ApiParam(value = "" ) @RequestHeader(value="api_key", required=false) apiKey: kotlin.String): ResponseEntity { + return ResponseEntity(service.deletePet(petId, apiKey), HttpStatus.OK) + } + + @ApiOperation( + value = "Finds Pets by status", + nickname = "findPetsByStatus", + notes = "Multiple status values can be provided with comma separated strings", + response = Pet::class, + responseContainer = "List", + authorizations = [Authorization(value = "petstore_auth", scopes = [AuthorizationScope(scope = "write:pets", description = "modify pets in your account"), AuthorizationScope(scope = "read:pets", description = "read your pets")])]) + @ApiResponses( + value = [ApiResponse(code = 200, message = "successful operation", response = Pet::class, responseContainer = "List"),ApiResponse(code = 400, message = "Invalid status value")]) + @RequestMapping( + value = ["/pet/findByStatus"], + produces = ["application/xml", "application/json"], + method = [RequestMethod.GET]) + fun findPetsByStatus(@NotNull @ApiParam(value = "Status values that need to be considered for filter", required = true, allowableValues = "available, pending, sold") @Valid @RequestParam(value = "status", required = true) status: kotlin.Array): ResponseEntity> { + return ResponseEntity(service.findPetsByStatus(status), HttpStatus.OK) + } + + @ApiOperation( + value = "Finds Pets by tags", + nickname = "findPetsByTags", + notes = "Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing.", + response = Pet::class, + responseContainer = "List", + authorizations = [Authorization(value = "petstore_auth", scopes = [AuthorizationScope(scope = "write:pets", description = "modify pets in your account"), AuthorizationScope(scope = "read:pets", description = "read your pets")])]) + @ApiResponses( + value = [ApiResponse(code = 200, message = "successful operation", response = Pet::class, responseContainer = "List"),ApiResponse(code = 400, message = "Invalid tag value")]) + @RequestMapping( + value = ["/pet/findByTags"], + produces = ["application/xml", "application/json"], + method = [RequestMethod.GET]) + fun findPetsByTags(@NotNull @ApiParam(value = "Tags to filter by", required = true) @Valid @RequestParam(value = "tags", required = true) tags: kotlin.Array): ResponseEntity> { + return ResponseEntity(service.findPetsByTags(tags), HttpStatus.OK) + } + + @ApiOperation( + value = "Find pet by ID", + nickname = "getPetById", + notes = "Returns a single pet", + response = Pet::class, + authorizations = [Authorization(value = "api_key")]) + @ApiResponses( + value = [ApiResponse(code = 200, message = "successful operation", response = Pet::class),ApiResponse(code = 400, message = "Invalid ID supplied"),ApiResponse(code = 404, message = "Pet not found")]) + @RequestMapping( + value = ["/pet/{petId}"], + produces = ["application/xml", "application/json"], + method = [RequestMethod.GET]) + fun getPetById(@ApiParam(value = "ID of pet to return", required=true) @PathVariable("petId") petId: kotlin.Long): ResponseEntity { + return ResponseEntity(service.getPetById(petId), HttpStatus.OK) + } + + @ApiOperation( + value = "Update an existing pet", + nickname = "updatePet", + notes = "", + authorizations = [Authorization(value = "petstore_auth", scopes = [AuthorizationScope(scope = "write:pets", description = "modify pets in your account"), AuthorizationScope(scope = "read:pets", description = "read your pets")])]) + @ApiResponses( + value = [ApiResponse(code = 400, message = "Invalid ID supplied"),ApiResponse(code = 404, message = "Pet not found"),ApiResponse(code = 405, message = "Validation exception")]) + @RequestMapping( + value = ["/pet"], + consumes = ["application/json", "application/xml"], + method = [RequestMethod.PUT]) + fun updatePet(@ApiParam(value = "Pet object that needs to be added to the store" ,required=true ) @Valid @RequestBody pet: Pet): ResponseEntity { + return ResponseEntity(service.updatePet(pet), HttpStatus.OK) + } + + @ApiOperation( + value = "Updates a pet in the store with form data", + nickname = "updatePetWithForm", + notes = "", + authorizations = [Authorization(value = "petstore_auth", scopes = [AuthorizationScope(scope = "write:pets", description = "modify pets in your account"), AuthorizationScope(scope = "read:pets", description = "read your pets")])]) + @ApiResponses( + value = [ApiResponse(code = 405, message = "Invalid input")]) + @RequestMapping( + value = ["/pet/{petId}"], + consumes = ["application/x-www-form-urlencoded"], + method = [RequestMethod.POST]) + fun updatePetWithForm(@ApiParam(value = "ID of pet that needs to be updated", required=true) @PathVariable("petId") petId: kotlin.Long,@ApiParam(value = "Updated name of the pet", defaultValue="null") @RequestParam(value="name", required=false) name: kotlin.String ,@ApiParam(value = "Updated status of the pet", defaultValue="null") @RequestParam(value="status", required=false) status: kotlin.String ): ResponseEntity { + return ResponseEntity(service.updatePetWithForm(petId, name, status), HttpStatus.OK) + } + + @ApiOperation( + value = "uploads an image", + nickname = "uploadFile", + notes = "", + response = ModelApiResponse::class, + authorizations = [Authorization(value = "petstore_auth", scopes = [AuthorizationScope(scope = "write:pets", description = "modify pets in your account"), AuthorizationScope(scope = "read:pets", description = "read your pets")])]) + @ApiResponses( + value = [ApiResponse(code = 200, message = "successful operation", response = ModelApiResponse::class)]) + @RequestMapping( + value = ["/pet/{petId}/uploadImage"], + produces = ["application/json"], + consumes = ["multipart/form-data"], + method = [RequestMethod.POST]) + fun uploadFile(@ApiParam(value = "ID of pet to update", required=true) @PathVariable("petId") petId: kotlin.Long,@ApiParam(value = "Additional data to pass to server", defaultValue="null") @RequestParam(value="additionalMetadata", required=false) additionalMetadata: kotlin.String ,@ApiParam(value = "file detail") @Valid @RequestPart("file") file: MultipartFile): ResponseEntity { + return ResponseEntity(service.uploadFile(petId, additionalMetadata, file), HttpStatus.OK) + } +} diff --git a/samples/server/openapi3/petstore/kotlin-springboot/src/main/kotlin/org/openapitools/api/PetApiService.kt b/samples/server/openapi3/petstore/kotlin-springboot/src/main/kotlin/org/openapitools/api/PetApiService.kt new file mode 100644 index 0000000000..e7bd7fae34 --- /dev/null +++ b/samples/server/openapi3/petstore/kotlin-springboot/src/main/kotlin/org/openapitools/api/PetApiService.kt @@ -0,0 +1,23 @@ +package org.openapitools.api + +import org.openapitools.model.ModelApiResponse +import org.openapitools.model.Pet + +interface PetApiService { + + fun addPet(pet: Pet): Unit + + fun deletePet(petId: kotlin.Long,apiKey: kotlin.String): Unit + + fun findPetsByStatus(status: kotlin.Array): List + + fun findPetsByTags(tags: kotlin.Array): List + + fun getPetById(petId: kotlin.Long): Pet + + fun updatePet(pet: Pet): Unit + + fun updatePetWithForm(petId: kotlin.Long,name: kotlin.String,status: kotlin.String): Unit + + fun uploadFile(petId: kotlin.Long,additionalMetadata: kotlin.String,file: org.springframework.web.multipart.MultipartFile): ModelApiResponse +} diff --git a/samples/server/openapi3/petstore/kotlin-springboot/src/main/kotlin/org/openapitools/api/PetApiServiceImpl.kt b/samples/server/openapi3/petstore/kotlin-springboot/src/main/kotlin/org/openapitools/api/PetApiServiceImpl.kt new file mode 100644 index 0000000000..e898ab9892 --- /dev/null +++ b/samples/server/openapi3/petstore/kotlin-springboot/src/main/kotlin/org/openapitools/api/PetApiServiceImpl.kt @@ -0,0 +1,41 @@ +package org.openapitools.api + +import org.openapitools.model.ModelApiResponse +import org.openapitools.model.Pet +import org.springframework.stereotype.Service + +@Service +class PetApiServiceImpl : PetApiService { + + override fun addPet(pet: Pet): Unit { + TODO("Implement me") + } + + override fun deletePet(petId: kotlin.Long,apiKey: kotlin.String): Unit { + TODO("Implement me") + } + + override fun findPetsByStatus(status: kotlin.Array): List { + TODO("Implement me") + } + + override fun findPetsByTags(tags: kotlin.Array): List { + TODO("Implement me") + } + + override fun getPetById(petId: kotlin.Long): Pet { + TODO("Implement me") + } + + override fun updatePet(pet: Pet): Unit { + TODO("Implement me") + } + + override fun updatePetWithForm(petId: kotlin.Long,name: kotlin.String,status: kotlin.String): Unit { + TODO("Implement me") + } + + override fun uploadFile(petId: kotlin.Long,additionalMetadata: kotlin.String,file: org.springframework.web.multipart.MultipartFile): ModelApiResponse { + TODO("Implement me") + } +} diff --git a/samples/server/openapi3/petstore/kotlin-springboot/src/main/kotlin/org/openapitools/api/StoreApi.kt b/samples/server/openapi3/petstore/kotlin-springboot/src/main/kotlin/org/openapitools/api/StoreApi.kt new file mode 100644 index 0000000000..fb6c7cb9a3 --- /dev/null +++ b/samples/server/openapi3/petstore/kotlin-springboot/src/main/kotlin/org/openapitools/api/StoreApi.kt @@ -0,0 +1,93 @@ +package org.openapitools.api + +import org.openapitools.model.Order +import io.swagger.annotations.* +import org.springframework.http.HttpStatus +import org.springframework.http.MediaType +import org.springframework.http.ResponseEntity +import org.springframework.stereotype.Controller +import org.springframework.web.bind.annotation.RequestBody +import org.springframework.web.bind.annotation.RequestPart +import org.springframework.web.bind.annotation.RequestParam +import org.springframework.web.bind.annotation.PathVariable +import org.springframework.web.bind.annotation.RequestHeader +import org.springframework.web.bind.annotation.RequestMethod +import org.springframework.web.bind.annotation.RequestMapping +import org.springframework.validation.annotation.Validated +import org.springframework.web.context.request.NativeWebRequest +import org.springframework.web.multipart.MultipartFile +import org.springframework.beans.factory.annotation.Autowired + +import javax.validation.Valid +import javax.validation.constraints.* + +import kotlin.collections.List +import kotlin.collections.Map + +@Controller +@Validated +@Api(value = "Store", description = "The Store API") +@RequestMapping("\${openapi.openAPIPetstore.base-path:/v2}") +class StoreApiController(@Autowired(required = true) val service: StoreApiService) { + + @ApiOperation( + value = "Delete purchase order by ID", + nickname = "deleteOrder", + notes = "For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors") + @ApiResponses( + value = [ApiResponse(code = 400, message = "Invalid ID supplied"),ApiResponse(code = 404, message = "Order not found")]) + @RequestMapping( + value = ["/store/order/{orderId}"], + method = [RequestMethod.DELETE]) + fun deleteOrder(@ApiParam(value = "ID of the order that needs to be deleted", required=true) @PathVariable("orderId") orderId: kotlin.String): ResponseEntity { + return ResponseEntity(service.deleteOrder(orderId), HttpStatus.OK) + } + + @ApiOperation( + value = "Returns pet inventories by status", + nickname = "getInventory", + notes = "Returns a map of status codes to quantities", + response = kotlin.Int::class, + responseContainer = "Map", + authorizations = [Authorization(value = "api_key")]) + @ApiResponses( + value = [ApiResponse(code = 200, message = "successful operation", response = kotlin.collections.Map::class, responseContainer = "Map")]) + @RequestMapping( + value = ["/store/inventory"], + produces = ["application/json"], + method = [RequestMethod.GET]) + fun getInventory(): ResponseEntity> { + return ResponseEntity(service.getInventory(), HttpStatus.OK) + } + + @ApiOperation( + value = "Find purchase order by ID", + nickname = "getOrderById", + notes = "For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions", + response = Order::class) + @ApiResponses( + value = [ApiResponse(code = 200, message = "successful operation", response = Order::class),ApiResponse(code = 400, message = "Invalid ID supplied"),ApiResponse(code = 404, message = "Order not found")]) + @RequestMapping( + value = ["/store/order/{orderId}"], + produces = ["application/xml", "application/json"], + method = [RequestMethod.GET]) + fun getOrderById(@Min(1L) @Max(5L) @ApiParam(value = "ID of pet that needs to be fetched", required=true) @PathVariable("orderId") orderId: kotlin.Long): ResponseEntity { + return ResponseEntity(service.getOrderById(orderId), HttpStatus.OK) + } + + @ApiOperation( + value = "Place an order for a pet", + nickname = "placeOrder", + notes = "", + response = Order::class) + @ApiResponses( + value = [ApiResponse(code = 200, message = "successful operation", response = Order::class),ApiResponse(code = 400, message = "Invalid Order")]) + @RequestMapping( + value = ["/store/order"], + produces = ["application/xml", "application/json"], + consumes = ["application/json"], + method = [RequestMethod.POST]) + fun placeOrder(@ApiParam(value = "order placed for purchasing the pet" ,required=true ) @Valid @RequestBody order: Order): ResponseEntity { + return ResponseEntity(service.placeOrder(order), HttpStatus.OK) + } +} diff --git a/samples/server/openapi3/petstore/kotlin-springboot/src/main/kotlin/org/openapitools/api/StoreApiService.kt b/samples/server/openapi3/petstore/kotlin-springboot/src/main/kotlin/org/openapitools/api/StoreApiService.kt new file mode 100644 index 0000000000..5eb379cb18 --- /dev/null +++ b/samples/server/openapi3/petstore/kotlin-springboot/src/main/kotlin/org/openapitools/api/StoreApiService.kt @@ -0,0 +1,14 @@ +package org.openapitools.api + +import org.openapitools.model.Order + +interface StoreApiService { + + fun deleteOrder(orderId: kotlin.String): Unit + + fun getInventory(): Map + + fun getOrderById(orderId: kotlin.Long): Order + + fun placeOrder(order: Order): Order +} diff --git a/samples/server/openapi3/petstore/kotlin-springboot/src/main/kotlin/org/openapitools/api/StoreApiServiceImpl.kt b/samples/server/openapi3/petstore/kotlin-springboot/src/main/kotlin/org/openapitools/api/StoreApiServiceImpl.kt new file mode 100644 index 0000000000..87d2551740 --- /dev/null +++ b/samples/server/openapi3/petstore/kotlin-springboot/src/main/kotlin/org/openapitools/api/StoreApiServiceImpl.kt @@ -0,0 +1,24 @@ +package org.openapitools.api + +import org.openapitools.model.Order +import org.springframework.stereotype.Service + +@Service +class StoreApiServiceImpl : StoreApiService { + + override fun deleteOrder(orderId: kotlin.String): Unit { + TODO("Implement me") + } + + override fun getInventory(): Map { + TODO("Implement me") + } + + override fun getOrderById(orderId: kotlin.Long): Order { + TODO("Implement me") + } + + override fun placeOrder(order: Order): Order { + TODO("Implement me") + } +} diff --git a/samples/server/openapi3/petstore/kotlin-springboot/src/main/kotlin/org/openapitools/api/UserApi.kt b/samples/server/openapi3/petstore/kotlin-springboot/src/main/kotlin/org/openapitools/api/UserApi.kt new file mode 100644 index 0000000000..4b88b867b1 --- /dev/null +++ b/samples/server/openapi3/petstore/kotlin-springboot/src/main/kotlin/org/openapitools/api/UserApi.kt @@ -0,0 +1,144 @@ +package org.openapitools.api + +import org.openapitools.model.User +import io.swagger.annotations.* +import org.springframework.http.HttpStatus +import org.springframework.http.MediaType +import org.springframework.http.ResponseEntity +import org.springframework.stereotype.Controller +import org.springframework.web.bind.annotation.RequestBody +import org.springframework.web.bind.annotation.RequestPart +import org.springframework.web.bind.annotation.RequestParam +import org.springframework.web.bind.annotation.PathVariable +import org.springframework.web.bind.annotation.RequestHeader +import org.springframework.web.bind.annotation.RequestMethod +import org.springframework.web.bind.annotation.RequestMapping +import org.springframework.validation.annotation.Validated +import org.springframework.web.context.request.NativeWebRequest +import org.springframework.web.multipart.MultipartFile +import org.springframework.beans.factory.annotation.Autowired + +import javax.validation.Valid +import javax.validation.constraints.* + +import kotlin.collections.List +import kotlin.collections.Map + +@Controller +@Validated +@Api(value = "User", description = "The User API") +@RequestMapping("\${openapi.openAPIPetstore.base-path:/v2}") +class UserApiController(@Autowired(required = true) val service: UserApiService) { + + @ApiOperation( + value = "Create user", + nickname = "createUser", + notes = "This can only be done by the logged in user.") + @ApiResponses( + value = [ApiResponse(code = 200, message = "successful operation")]) + @RequestMapping( + value = ["/user"], + consumes = ["application/json"], + method = [RequestMethod.POST]) + fun createUser(@ApiParam(value = "Created user object" ,required=true ) @Valid @RequestBody user: User): ResponseEntity { + return ResponseEntity(service.createUser(user), HttpStatus.OK) + } + + @ApiOperation( + value = "Creates list of users with given input array", + nickname = "createUsersWithArrayInput", + notes = "") + @ApiResponses( + value = [ApiResponse(code = 200, message = "successful operation")]) + @RequestMapping( + value = ["/user/createWithArray"], + consumes = ["application/json"], + method = [RequestMethod.POST]) + fun createUsersWithArrayInput(@ApiParam(value = "List of user object" ,required=true ) @Valid @RequestBody user: kotlin.Array): ResponseEntity { + return ResponseEntity(service.createUsersWithArrayInput(user), HttpStatus.OK) + } + + @ApiOperation( + value = "Creates list of users with given input array", + nickname = "createUsersWithListInput", + notes = "") + @ApiResponses( + value = [ApiResponse(code = 200, message = "successful operation")]) + @RequestMapping( + value = ["/user/createWithList"], + consumes = ["application/json"], + method = [RequestMethod.POST]) + fun createUsersWithListInput(@ApiParam(value = "List of user object" ,required=true ) @Valid @RequestBody user: kotlin.Array): ResponseEntity { + return ResponseEntity(service.createUsersWithListInput(user), HttpStatus.OK) + } + + @ApiOperation( + value = "Delete user", + nickname = "deleteUser", + notes = "This can only be done by the logged in user.") + @ApiResponses( + value = [ApiResponse(code = 400, message = "Invalid username supplied"),ApiResponse(code = 404, message = "User not found")]) + @RequestMapping( + value = ["/user/{username}"], + method = [RequestMethod.DELETE]) + fun deleteUser(@ApiParam(value = "The name that needs to be deleted", required=true) @PathVariable("username") username: kotlin.String): ResponseEntity { + return ResponseEntity(service.deleteUser(username), HttpStatus.OK) + } + + @ApiOperation( + value = "Get user by user name", + nickname = "getUserByName", + notes = "", + response = User::class) + @ApiResponses( + value = [ApiResponse(code = 200, message = "successful operation", response = User::class),ApiResponse(code = 400, message = "Invalid username supplied"),ApiResponse(code = 404, message = "User not found")]) + @RequestMapping( + value = ["/user/{username}"], + produces = ["application/xml", "application/json"], + method = [RequestMethod.GET]) + fun getUserByName(@ApiParam(value = "The name that needs to be fetched. Use user1 for testing.", required=true) @PathVariable("username") username: kotlin.String): ResponseEntity { + return ResponseEntity(service.getUserByName(username), HttpStatus.OK) + } + + @ApiOperation( + value = "Logs user into the system", + nickname = "loginUser", + notes = "", + response = kotlin.String::class) + @ApiResponses( + value = [ApiResponse(code = 200, message = "successful operation", response = kotlin.String::class),ApiResponse(code = 400, message = "Invalid username/password supplied")]) + @RequestMapping( + value = ["/user/login"], + produces = ["application/xml", "application/json"], + method = [RequestMethod.GET]) + fun loginUser(@NotNull @ApiParam(value = "The user name for login", required = true) @Valid @RequestParam(value = "username", required = true) username: kotlin.String,@NotNull @ApiParam(value = "The password for login in clear text", required = true) @Valid @RequestParam(value = "password", required = true) password: kotlin.String): ResponseEntity { + return ResponseEntity(service.loginUser(username, password), HttpStatus.OK) + } + + @ApiOperation( + value = "Logs out current logged in user session", + nickname = "logoutUser", + notes = "") + @ApiResponses( + value = [ApiResponse(code = 200, message = "successful operation")]) + @RequestMapping( + value = ["/user/logout"], + method = [RequestMethod.GET]) + fun logoutUser(): ResponseEntity { + return ResponseEntity(service.logoutUser(), HttpStatus.OK) + } + + @ApiOperation( + value = "Updated user", + nickname = "updateUser", + notes = "This can only be done by the logged in user.") + @ApiResponses( + value = [ApiResponse(code = 400, message = "Invalid user supplied"),ApiResponse(code = 404, message = "User not found")]) + @RequestMapping( + value = ["/user/{username}"], + consumes = ["application/json"], + method = [RequestMethod.PUT]) + fun updateUser(@ApiParam(value = "name that need to be deleted", required=true) @PathVariable("username") username: kotlin.String,@ApiParam(value = "Updated user object" ,required=true ) @Valid @RequestBody user: User): ResponseEntity { + return ResponseEntity(service.updateUser(username, user), HttpStatus.OK) + } +} diff --git a/samples/server/openapi3/petstore/kotlin-springboot/src/main/kotlin/org/openapitools/api/UserApiService.kt b/samples/server/openapi3/petstore/kotlin-springboot/src/main/kotlin/org/openapitools/api/UserApiService.kt new file mode 100644 index 0000000000..4b913ace3d --- /dev/null +++ b/samples/server/openapi3/petstore/kotlin-springboot/src/main/kotlin/org/openapitools/api/UserApiService.kt @@ -0,0 +1,22 @@ +package org.openapitools.api + +import org.openapitools.model.User + +interface UserApiService { + + fun createUser(user: User): Unit + + fun createUsersWithArrayInput(user: kotlin.Array): Unit + + fun createUsersWithListInput(user: kotlin.Array): Unit + + fun deleteUser(username: kotlin.String): Unit + + fun getUserByName(username: kotlin.String): User + + fun loginUser(username: kotlin.String,password: kotlin.String): kotlin.String + + fun logoutUser(): Unit + + fun updateUser(username: kotlin.String,user: User): Unit +} diff --git a/samples/server/openapi3/petstore/kotlin-springboot/src/main/kotlin/org/openapitools/api/UserApiServiceImpl.kt b/samples/server/openapi3/petstore/kotlin-springboot/src/main/kotlin/org/openapitools/api/UserApiServiceImpl.kt new file mode 100644 index 0000000000..9600f60768 --- /dev/null +++ b/samples/server/openapi3/petstore/kotlin-springboot/src/main/kotlin/org/openapitools/api/UserApiServiceImpl.kt @@ -0,0 +1,40 @@ +package org.openapitools.api + +import org.openapitools.model.User +import org.springframework.stereotype.Service + +@Service +class UserApiServiceImpl : UserApiService { + + override fun createUser(user: User): Unit { + TODO("Implement me") + } + + override fun createUsersWithArrayInput(user: kotlin.Array): Unit { + TODO("Implement me") + } + + override fun createUsersWithListInput(user: kotlin.Array): Unit { + TODO("Implement me") + } + + override fun deleteUser(username: kotlin.String): Unit { + TODO("Implement me") + } + + override fun getUserByName(username: kotlin.String): User { + TODO("Implement me") + } + + override fun loginUser(username: kotlin.String,password: kotlin.String): kotlin.String { + TODO("Implement me") + } + + override fun logoutUser(): Unit { + TODO("Implement me") + } + + override fun updateUser(username: kotlin.String,user: User): Unit { + TODO("Implement me") + } +} diff --git a/samples/server/openapi3/petstore/kotlin-springboot/src/main/kotlin/org/openapitools/model/Body.kt b/samples/server/openapi3/petstore/kotlin-springboot/src/main/kotlin/org/openapitools/model/Body.kt new file mode 100644 index 0000000000..440495ed85 --- /dev/null +++ b/samples/server/openapi3/petstore/kotlin-springboot/src/main/kotlin/org/openapitools/model/Body.kt @@ -0,0 +1,24 @@ +package org.openapitools.model + +import java.util.Objects +import com.fasterxml.jackson.annotation.JsonProperty +import javax.validation.Valid +import javax.validation.constraints.* +import io.swagger.annotations.ApiModelProperty + +/** + * + * @param name Updated name of the pet + * @param status Updated status of the pet + */ +data class Body ( + + @ApiModelProperty(value = "Updated name of the pet") + @JsonProperty("name") val name: kotlin.String? = null, + + @ApiModelProperty(value = "Updated status of the pet") + @JsonProperty("status") val status: kotlin.String? = null +) { + +} + diff --git a/samples/server/openapi3/petstore/kotlin-springboot/src/main/kotlin/org/openapitools/model/Body1.kt b/samples/server/openapi3/petstore/kotlin-springboot/src/main/kotlin/org/openapitools/model/Body1.kt new file mode 100644 index 0000000000..0b7b3dc891 --- /dev/null +++ b/samples/server/openapi3/petstore/kotlin-springboot/src/main/kotlin/org/openapitools/model/Body1.kt @@ -0,0 +1,24 @@ +package org.openapitools.model + +import java.util.Objects +import com.fasterxml.jackson.annotation.JsonProperty +import javax.validation.Valid +import javax.validation.constraints.* +import io.swagger.annotations.ApiModelProperty + +/** + * + * @param additionalMetadata Additional data to pass to server + * @param file file to upload + */ +data class Body1 ( + + @ApiModelProperty(value = "Additional data to pass to server") + @JsonProperty("additionalMetadata") val additionalMetadata: kotlin.String? = null, + + @ApiModelProperty(value = "file to upload") + @JsonProperty("file") val file: java.io.File? = null +) { + +} + diff --git a/samples/server/openapi3/petstore/kotlin-springboot/src/main/kotlin/org/openapitools/model/Category.kt b/samples/server/openapi3/petstore/kotlin-springboot/src/main/kotlin/org/openapitools/model/Category.kt new file mode 100644 index 0000000000..36d48aa093 --- /dev/null +++ b/samples/server/openapi3/petstore/kotlin-springboot/src/main/kotlin/org/openapitools/model/Category.kt @@ -0,0 +1,24 @@ +package org.openapitools.model + +import java.util.Objects +import com.fasterxml.jackson.annotation.JsonProperty +import javax.validation.Valid +import javax.validation.constraints.* +import io.swagger.annotations.ApiModelProperty + +/** + * A category for a pet + * @param id + * @param name + */ +data class Category ( + + @ApiModelProperty(value = "") + @JsonProperty("id") val id: kotlin.Long? = null, + + @ApiModelProperty(value = "") + @JsonProperty("name") val name: kotlin.String? = null +) { + +} + diff --git a/samples/server/openapi3/petstore/kotlin-springboot/src/main/kotlin/org/openapitools/model/ModelApiResponse.kt b/samples/server/openapi3/petstore/kotlin-springboot/src/main/kotlin/org/openapitools/model/ModelApiResponse.kt new file mode 100644 index 0000000000..9a259e9baa --- /dev/null +++ b/samples/server/openapi3/petstore/kotlin-springboot/src/main/kotlin/org/openapitools/model/ModelApiResponse.kt @@ -0,0 +1,28 @@ +package org.openapitools.model + +import java.util.Objects +import com.fasterxml.jackson.annotation.JsonProperty +import javax.validation.Valid +import javax.validation.constraints.* +import io.swagger.annotations.ApiModelProperty + +/** + * Describes the result of uploading an image resource + * @param code + * @param type + * @param message + */ +data class ModelApiResponse ( + + @ApiModelProperty(value = "") + @JsonProperty("code") val code: kotlin.Int? = null, + + @ApiModelProperty(value = "") + @JsonProperty("type") val type: kotlin.String? = null, + + @ApiModelProperty(value = "") + @JsonProperty("message") val message: kotlin.String? = null +) { + +} + diff --git a/samples/server/openapi3/petstore/kotlin-springboot/src/main/kotlin/org/openapitools/model/Order.kt b/samples/server/openapi3/petstore/kotlin-springboot/src/main/kotlin/org/openapitools/model/Order.kt new file mode 100644 index 0000000000..2a7a639a9c --- /dev/null +++ b/samples/server/openapi3/petstore/kotlin-springboot/src/main/kotlin/org/openapitools/model/Order.kt @@ -0,0 +1,55 @@ +package org.openapitools.model + +import java.util.Objects +import com.fasterxml.jackson.annotation.JsonProperty +import com.fasterxml.jackson.annotation.JsonValue +import javax.validation.Valid +import javax.validation.constraints.* +import io.swagger.annotations.ApiModelProperty + +/** + * An order for a pets from the pet store + * @param id + * @param petId + * @param quantity + * @param shipDate + * @param status Order Status + * @param complete + */ +data class Order ( + + @ApiModelProperty(value = "") + @JsonProperty("id") val id: kotlin.Long? = null, + + @ApiModelProperty(value = "") + @JsonProperty("petId") val petId: kotlin.Long? = null, + + @ApiModelProperty(value = "") + @JsonProperty("quantity") val quantity: kotlin.Int? = null, + + @ApiModelProperty(value = "") + @JsonProperty("shipDate") val shipDate: java.time.OffsetDateTime? = null, + + @ApiModelProperty(value = "Order Status") + @JsonProperty("status") val status: Order.Status? = null, + + @ApiModelProperty(value = "") + @JsonProperty("complete") val complete: kotlin.Boolean? = null +) { + + /** + * Order Status + * Values: placed,approved,delivered + */ + enum class Status(val value: kotlin.String) { + + @JsonProperty("placed") placed("placed"), + + @JsonProperty("approved") approved("approved"), + + @JsonProperty("delivered") delivered("delivered"); + + } + +} + diff --git a/samples/server/openapi3/petstore/kotlin-springboot/src/main/kotlin/org/openapitools/model/Pet.kt b/samples/server/openapi3/petstore/kotlin-springboot/src/main/kotlin/org/openapitools/model/Pet.kt new file mode 100644 index 0000000000..29665f1779 --- /dev/null +++ b/samples/server/openapi3/petstore/kotlin-springboot/src/main/kotlin/org/openapitools/model/Pet.kt @@ -0,0 +1,59 @@ +package org.openapitools.model + +import java.util.Objects +import com.fasterxml.jackson.annotation.JsonProperty +import com.fasterxml.jackson.annotation.JsonValue +import org.openapitools.model.Category +import org.openapitools.model.Tag +import javax.validation.Valid +import javax.validation.constraints.* +import io.swagger.annotations.ApiModelProperty + +/** + * A pet for sale in the pet store + * @param id + * @param category + * @param name + * @param photoUrls + * @param tags + * @param status pet status in the store + */ +data class Pet ( + + @get:NotNull + @ApiModelProperty(example = "doggie", required = true, value = "") + @JsonProperty("name") val name: kotlin.String, + + @get:NotNull + @ApiModelProperty(required = true, value = "") + @JsonProperty("photoUrls") val photoUrls: kotlin.Array, + + @ApiModelProperty(value = "") + @JsonProperty("id") val id: kotlin.Long? = null, + + @ApiModelProperty(value = "") + @JsonProperty("category") val category: Category? = null, + + @ApiModelProperty(value = "") + @JsonProperty("tags") val tags: kotlin.Array? = null, + + @ApiModelProperty(value = "pet status in the store") + @JsonProperty("status") val status: Pet.Status? = null +) { + + /** + * pet status in the store + * Values: available,pending,sold + */ + enum class Status(val value: kotlin.String) { + + @JsonProperty("available") available("available"), + + @JsonProperty("pending") pending("pending"), + + @JsonProperty("sold") sold("sold"); + + } + +} + diff --git a/samples/server/openapi3/petstore/kotlin-springboot/src/main/kotlin/org/openapitools/model/Tag.kt b/samples/server/openapi3/petstore/kotlin-springboot/src/main/kotlin/org/openapitools/model/Tag.kt new file mode 100644 index 0000000000..76b362380b --- /dev/null +++ b/samples/server/openapi3/petstore/kotlin-springboot/src/main/kotlin/org/openapitools/model/Tag.kt @@ -0,0 +1,24 @@ +package org.openapitools.model + +import java.util.Objects +import com.fasterxml.jackson.annotation.JsonProperty +import javax.validation.Valid +import javax.validation.constraints.* +import io.swagger.annotations.ApiModelProperty + +/** + * A tag for a pet + * @param id + * @param name + */ +data class Tag ( + + @ApiModelProperty(value = "") + @JsonProperty("id") val id: kotlin.Long? = null, + + @ApiModelProperty(value = "") + @JsonProperty("name") val name: kotlin.String? = null +) { + +} + diff --git a/samples/server/openapi3/petstore/kotlin-springboot/src/main/kotlin/org/openapitools/model/User.kt b/samples/server/openapi3/petstore/kotlin-springboot/src/main/kotlin/org/openapitools/model/User.kt new file mode 100644 index 0000000000..6ebdab0208 --- /dev/null +++ b/samples/server/openapi3/petstore/kotlin-springboot/src/main/kotlin/org/openapitools/model/User.kt @@ -0,0 +1,48 @@ +package org.openapitools.model + +import java.util.Objects +import com.fasterxml.jackson.annotation.JsonProperty +import javax.validation.Valid +import javax.validation.constraints.* +import io.swagger.annotations.ApiModelProperty + +/** + * A User who is purchasing from the pet store + * @param id + * @param username + * @param firstName + * @param lastName + * @param email + * @param password + * @param phone + * @param userStatus User Status + */ +data class User ( + + @ApiModelProperty(value = "") + @JsonProperty("id") val id: kotlin.Long? = null, + + @ApiModelProperty(value = "") + @JsonProperty("username") val username: kotlin.String? = null, + + @ApiModelProperty(value = "") + @JsonProperty("firstName") val firstName: kotlin.String? = null, + + @ApiModelProperty(value = "") + @JsonProperty("lastName") val lastName: kotlin.String? = null, + + @ApiModelProperty(value = "") + @JsonProperty("email") val email: kotlin.String? = null, + + @ApiModelProperty(value = "") + @JsonProperty("password") val password: kotlin.String? = null, + + @ApiModelProperty(value = "") + @JsonProperty("phone") val phone: kotlin.String? = null, + + @ApiModelProperty(value = "User Status") + @JsonProperty("userStatus") val userStatus: kotlin.Int? = null +) { + +} + diff --git a/samples/server/openapi3/petstore/kotlin-springboot/src/main/resources/application.yaml b/samples/server/openapi3/petstore/kotlin-springboot/src/main/resources/application.yaml new file mode 100644 index 0000000000..366e320d52 --- /dev/null +++ b/samples/server/openapi3/petstore/kotlin-springboot/src/main/resources/application.yaml @@ -0,0 +1,3 @@ +spring.application.name=openAPIPetstore +server.port=8080 +spring.jackson.serialization.WRITE_DATES_AS_TIMESTAMPS=false \ No newline at end of file diff --git a/samples/server/petstore-security-test/php-slim/README.md b/samples/server/petstore-security-test/php-slim/README.md index 337746cd02..caf887a56d 100644 --- a/samples/server/petstore-security-test/php-slim/README.md +++ b/samples/server/petstore-security-test/php-slim/README.md @@ -30,15 +30,17 @@ $ php -S localhost:8888 -t php-slim-server ## Run tests -This package uses PHPUnit 4.8 for unit testing. +This package uses PHPUnit 4.8 for unit testing and PHP Codesniffer to check source code against user defined coding standard(`phpcsStandard` generator config option). [Test folder](test) contains templates which you can fill with real test assertions. How to write tests read at [PHPUnit Manual - Chapter 2. Writing Tests for PHPUnit](https://phpunit.de/manual/4.8/en/writing-tests-for-phpunit.html). +How to configure PHP CodeSniffer read at [PHP CodeSniffer Documentation](https://github.com/squizlabs/PHP_CodeSniffer/wiki). Command | Tool | Target ---- | ---- | ---- `$ composer test` | PHPUnit | All tests `$ composer run test-apis` | PHPUnit | Apis tests `$ composer run test-models` | PHPUnit | Models tests +`$ composer run phpcs` | PHP CodeSniffer | All files ## API Endpoints diff --git a/samples/server/petstore-security-test/php-slim/composer.json b/samples/server/petstore-security-test/php-slim/composer.json index ca19917902..166250643b 100644 --- a/samples/server/petstore-security-test/php-slim/composer.json +++ b/samples/server/petstore-security-test/php-slim/composer.json @@ -6,7 +6,8 @@ "tuupola/slim-basic-auth": "^3.0.0" }, "require-dev": { - "phpunit/phpunit": "^4.8" + "phpunit/phpunit": "^4.8", + "squizlabs/php_codesniffer": "^3.0" }, "autoload": { "psr-4": { "OpenAPIServer\\": "lib/" } @@ -20,6 +21,7 @@ "@test-models" ], "test-apis": "phpunit --testsuite Apis", - "test-models": "phpunit --testsuite Models" + "test-models": "phpunit --testsuite Models", + "phpcs": "phpcs ./ --ignore=vendor --warning-severity=0 --standard=PSR12" } } \ No newline at end of file diff --git a/samples/server/petstore-security-test/php-slim/lib/AbstractApiController.php b/samples/server/petstore-security-test/php-slim/lib/AbstractApiController.php index 03b525eb3e..9d6b899e2d 100644 --- a/samples/server/petstore-security-test/php-slim/lib/AbstractApiController.php +++ b/samples/server/petstore-security-test/php-slim/lib/AbstractApiController.php @@ -36,7 +36,8 @@ namespace OpenAPIServer; * @author OpenAPI Generator team * @link https://github.com/openapitools/openapi-generator */ -abstract class AbstractApiController { +abstract class AbstractApiController +{ /** * @var \Interop\Container\ContainerInterface Slim app container instance @@ -48,8 +49,8 @@ abstract class AbstractApiController { * * @param \Interop\Container\ContainerInterface $container Slim app container instance */ - public function __construct($container) { + public function __construct($container) + { $this->container = $container; } - } diff --git a/samples/server/petstore-security-test/php-slim/lib/Api/FakeApi.php b/samples/server/petstore-security-test/php-slim/lib/Api/FakeApi.php index 464145051c..e5f473ac0a 100644 --- a/samples/server/petstore-security-test/php-slim/lib/Api/FakeApi.php +++ b/samples/server/petstore-security-test/php-slim/lib/Api/FakeApi.php @@ -38,8 +38,9 @@ use OpenAPIServer\AbstractApiController; * @author OpenAPI Generator team * @link https://github.com/openapitools/openapi-generator */ -class FakeApi extends AbstractApiController { - +class FakeApi extends AbstractApiController +{ + /** * PUT testCodeInjectEndRnNR * Summary: To test code injection *_/ ' \" =end -- \\r\\n \\n \\r @@ -49,10 +50,10 @@ class FakeApi extends AbstractApiController { * @param \Psr\Http\Message\ResponseInterface $response Response * @param array|null $args Path arguments */ - public function testCodeInjectEndRnNR($request, $response, $args) { + public function testCodeInjectEndRnNR($request, $response, $args) + { $body = $request->getParsedBody(); $response->write('How about implementing testCodeInjectEndRnNR as a PUT method ?'); return $response; } - } diff --git a/samples/server/petstore-security-test/php-slim/lib/Model/ModelReturn.php b/samples/server/petstore-security-test/php-slim/lib/Model/ModelReturn.php index f070d4efcc..8cf6a29ab8 100644 --- a/samples/server/petstore-security-test/php-slim/lib/Model/ModelReturn.php +++ b/samples/server/petstore-security-test/php-slim/lib/Model/ModelReturn.php @@ -7,9 +7,9 @@ namespace OpenAPIServer\Model; /** * ModelReturn */ -class ModelReturn { - +class ModelReturn +{ + /** @var int $return property description *_/ ' \" =end -- \\r\\n \\n \\r*/ private $return; - } diff --git a/samples/server/petstore-security-test/php-slim/lib/SlimRouter.php b/samples/server/petstore-security-test/php-slim/lib/SlimRouter.php index 794b619238..0b7509aab7 100644 --- a/samples/server/petstore-security-test/php-slim/lib/SlimRouter.php +++ b/samples/server/petstore-security-test/php-slim/lib/SlimRouter.php @@ -10,7 +10,7 @@ * @link https://github.com/openapitools/openapi-generator */ -/** +/** * OpenAPI Petstore *_/ ' \" =end -- \\r\\n \\n \\r * * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ *_/ ' \" =end -- @@ -42,7 +42,8 @@ use Tuupola\Middleware\HttpBasicAuthentication; * @author OpenAPI Generator team * @link https://github.com/openapitools/openapi-generator */ -class SlimRouter { +class SlimRouter +{ /** * @var $slimApp Slim\App instance @@ -55,7 +56,8 @@ class SlimRouter { * @param ContainerInterface|array $container Either a ContainerInterface or an associative array of app settings * @throws InvalidArgumentException when no container is provided that implements ContainerInterface */ - public function __construct($container = []) { + public function __construct($container = []) + { $app = new App($container); $basicAuth = new HttpBasicAuthentication([ @@ -68,7 +70,8 @@ class SlimRouter { ]); $app->PUT( - '/ ' \" =end -- \\r\\n \\n \\r/v2 *_/ ' \" =end -- \\r\\n \\n \\r/fake', FakeApi::class . ':testCodeInjectEndRnNR' + '/ ' \" =end -- \\r\\n \\n \\r/v2 *_/ ' \" =end -- \\r\\n \\n \\r/fake', + FakeApi::class . ':testCodeInjectEndRnNR' ); $this->slimApp = $app; @@ -78,7 +81,8 @@ class SlimRouter { * Returns Slim Framework instance * @return App */ - public function getSlimApp() { + public function getSlimApp() + { return $this->slimApp; } } diff --git a/samples/server/petstore-security-test/php-slim/test/Api/FakeApiTest.php b/samples/server/petstore-security-test/php-slim/test/Api/FakeApiTest.php index 3205216ec9..de4df30629 100644 --- a/samples/server/petstore-security-test/php-slim/test/Api/FakeApiTest.php +++ b/samples/server/petstore-security-test/php-slim/test/Api/FakeApiTest.php @@ -37,34 +37,35 @@ use OpenAPIServer\Api\FakeApi; * @link https://github.com/openapitools/openapi-generator * @coversDefaultClass \OpenAPIServer\Model\FakeApi */ -class FakeApiTest extends \PHPUnit_Framework_TestCase { +class FakeApiTest extends \PHPUnit_Framework_TestCase +{ /** * Setup before running any test cases */ - public static function setUpBeforeClass() { - + public static function setUpBeforeClass() + { } /** * Setup before running each test case */ - public function setUp() { - + public function setUp() + { } /** * Clean up after running each test case */ - public function tearDown() { - + public function tearDown() + { } /** * Clean up after running all test cases */ - public static function tearDownAfterClass() { - + public static function tearDownAfterClass() + { } /** @@ -73,7 +74,7 @@ class FakeApiTest extends \PHPUnit_Framework_TestCase { * To test code injection *_/ ' \" =end -- \\r\\n \\n \\r. * @covers ::testCodeInjectEndRnNR */ - public function testTestCodeInjectEndRnNR() { - + public function testTestCodeInjectEndRnNR() + { } } diff --git a/samples/server/petstore-security-test/php-slim/test/Model/ModelReturnTest.php b/samples/server/petstore-security-test/php-slim/test/Model/ModelReturnTest.php index d535c902fc..036a63c111 100644 --- a/samples/server/petstore-security-test/php-slim/test/Model/ModelReturnTest.php +++ b/samples/server/petstore-security-test/php-slim/test/Model/ModelReturnTest.php @@ -37,48 +37,49 @@ use OpenAPIServer\Model\ModelReturn; * @link https://github.com/openapitools/openapi-generator * @coversDefaultClass \OpenAPIServer\Model\ModelReturn */ -class ModelReturnTest extends \PHPUnit_Framework_TestCase { +class ModelReturnTest extends \PHPUnit_Framework_TestCase +{ /** * Setup before running any test cases */ - public static function setUpBeforeClass() { - + public static function setUpBeforeClass() + { } /** * Setup before running each test case */ - public function setUp() { - + public function setUp() + { } /** * Clean up after running each test case */ - public function tearDown() { - + public function tearDown() + { } /** * Clean up after running all test cases */ - public static function tearDownAfterClass() { - + public static function tearDownAfterClass() + { } /** * Test "ModelReturn" */ - public function testModelReturn() { + public function testModelReturn() + { $testModelReturn = new ModelReturn(); } /** * Test attribute "return" */ - public function testPropertyReturn() { - + public function testPropertyReturn() + { } } - diff --git a/samples/server/petstore/cpp-qt5-qhttpengine-server/server/Dockerfile b/samples/server/petstore/cpp-qt5-qhttpengine-server/server/Dockerfile index b339548297..2cc6d3eba2 100644 --- a/samples/server/petstore/cpp-qt5-qhttpengine-server/server/Dockerfile +++ b/samples/server/petstore/cpp-qt5-qhttpengine-server/server/Dockerfile @@ -1,11 +1,11 @@ FROM alpine:latest AS build -RUN apk add --update \ +RUN apk add --update \ cmake \ alpine-sdk \ - openssl \ - qt5-qtbase-dev \ - qt5-qttools-dev + openssl \ + qt5-qtbase-dev \ + qt5-qttools-dev WORKDIR /usr/server ADD ./src ./src @@ -13,10 +13,10 @@ ADD ./CMakeLists.txt ./ RUN mkdir -p ./build WORKDIR /usr/server/build RUN cmake -DNODEBUG:STRING="ON" .. -RUN make +RUN make FROM alpine:latest AS runtime -RUN apk add --update \ +RUN apk add --update \ libgcc \ libstdc++ \ qt5-qtbase \ diff --git a/samples/server/petstore/cpp-qt5-qhttpengine-server/server/LICENSE.txt b/samples/server/petstore/cpp-qt5-qhttpengine-server/server/LICENSE.txt index 04938f840c..be59130f85 100644 --- a/samples/server/petstore/cpp-qt5-qhttpengine-server/server/LICENSE.txt +++ b/samples/server/petstore/cpp-qt5-qhttpengine-server/server/LICENSE.txt @@ -1,4 +1,4 @@ -QHttpEngine +QHttpEngine The MIT License (MIT) diff --git a/samples/server/petstore/cpp-qt5-qhttpengine-server/server/README.MD b/samples/server/petstore/cpp-qt5-qhttpengine-server/server/README.MD index d354460c63..5be785bda4 100644 --- a/samples/server/petstore/cpp-qt5-qhttpengine-server/server/README.MD +++ b/samples/server/petstore/cpp-qt5-qhttpengine-server/server/README.MD @@ -1,8 +1,9 @@ +# C++ Qt5 Server + ## Qt5 HTTP Server based on the Qhttpengine -This server was generated by the [openapi-generator] -(https://openapi-generator.tech) project. -By using the [OpenAPI-Spec](https://github.com/OAI/OpenAPI-Specification) from a remote server, you can easily generate a server stub. -- + +This server was generated by the [openapi-generator](https://openapi-generator.tech) project. +By using the [OpenAPI-Spec](https://github.com/OAI/OpenAPI-Specification) from a remote server, you can easily generate a server stub. To see how to make this your own, look here: @@ -21,30 +22,36 @@ Simple set of classes for developing HTTP server applications in Qt. To learn more about building and using the library, please visit this page: -https://ci.quickmediasolutions.com/job/qhttpengine-documentation/doxygen/ - +[Link](https://ci.quickmediasolutions.com/job/qhttpengine-documentation/doxygen) ### Viewing the code -You can view the code using an editor like Microsoft Visual Studio Code or you can + +You can view the code using an editor like Microsoft Visual Studio Code or you can Use QtCreator and browse for the root CMakeLists.txt and load it as a project ### Build with make + Install the tools [Linux/Debian] -``` + +```shell sudo apt install cmake build-essential libssl-dev qtbase5-dev qtbase5-dev-tools git curl ``` To build, go to the `server` folder -``` -make + +```shell +make ``` To run the server -``` + +```shell ./build/src/cpp-qt5-server & ``` + #### Invoke an API -``` + +```shell curl -X GET http://localhost:8080/v2/store/inventory curl -X POST http://localhost:8080/v2/store/order -H "Content-Type: application/json" -d "{ \"id\": 22, \"petId\": 1541, \"quantity\": 5, \"shipDate\": \"2018-06-16T18:31:43.870Z\", \"status\": \"placed\", \"complete\": \"true\" }" curl -X GET http://localhost:8080/v2/pet/findByStatus @@ -52,38 +59,50 @@ curl -X GET http://localhost:8080/v2/store/inventory ``` ### Run and build with docker + Building with docker multistage If you dont have docker install [here](https://docs.docker.com/install) Add yourself to the docker group -``` +```shell docker build --network=host -t cpp-qt5-server . ``` -Running with docker -``` -docker run --rm -it --name=server-container cpp-qt5-server + +Running with docker + +```shell +docker run --rm -it --name=server-container cpp-qt5-server ``` #### Invoking an API + Mind the IP here -``` + +```shell curl -X GET http://172.17.0.2:8080/v2/store/inventory curl -X POST http://172.17.0.2:8080/v2/store/order -H "Content-Type: application/json" -d "{ \"id\": 22, \"petId\": 1541, \"quantity\": 5, \"shipDate\": \"2018-06-16T18:31:43.870Z\", \"status\": \"placed\", \"complete\": \"true\" }" ``` use this command to get the container IP -``` + +```shell docker inspect server-container | grep "IPAddress" ``` -To exit from the command line -``` + +To exit from the command line + +```shell Ctrl + p + q ``` + To stop container -``` + +```shell docker stop ``` + or to terminate and quit -``` + +```shell Ctrl+C ``` diff --git a/samples/server/petstore/cpp-qt5-qhttpengine-server/server/src/CMakeLists.txt b/samples/server/petstore/cpp-qt5-qhttpengine-server/server/src/CMakeLists.txt index 9faf5db60e..0311ec2020 100644 --- a/samples/server/petstore/cpp-qt5-qhttpengine-server/server/src/CMakeLists.txt +++ b/samples/server/petstore/cpp-qt5-qhttpengine-server/server/src/CMakeLists.txt @@ -12,7 +12,7 @@ set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -fPIC -std=c++14 -Wall -Wno-unused-varia if(${NODEBUG} STREQUAL "OFF") set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -pg -g3") set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -pg -g3") -else (${NODEBUG} STREQUAL "OFF") +else (${NODEBUG} STREQUAL "OFF") set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -s -O3") set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -s -O3") endif(${NODEBUG} STREQUAL "OFF") diff --git a/samples/server/petstore/cpp-qt5-qhttpengine-server/server/src/handlers/OAIApiRouter.cpp b/samples/server/petstore/cpp-qt5-qhttpengine-server/server/src/handlers/OAIApiRouter.cpp index e45ee72870..2f66594425 100644 --- a/samples/server/petstore/cpp-qt5-qhttpengine-server/server/src/handlers/OAIApiRouter.cpp +++ b/samples/server/petstore/cpp-qt5-qhttpengine-server/server/src/handlers/OAIApiRouter.cpp @@ -24,270 +24,241 @@ namespace OpenAPI { -inline QHttpEngine::Socket::Method toQHttpEngineMethod(QString method){ - - if( method == QString("OPTIONS")) - return QHttpEngine::Socket::Method::OPTIONS; - if( method == QString("GET")) - return QHttpEngine::Socket::Method::GET; - if( method == QString("HEAD")) - return QHttpEngine::Socket::Method::HEAD; - if( method == QString("POST")) - return QHttpEngine::Socket::Method::POST; - if( method == QString("PUT")) - return QHttpEngine::Socket::Method::PUT; - if( method == QString("DELETE")) - return QHttpEngine::Socket::Method::DELETE; - if( method == QString("TRACE")) - return QHttpEngine::Socket::Method::TRACE; - if( method == QString("CONNECT")) - return QHttpEngine::Socket::Method::CONNECT; - - return static_cast(-1); +OAIApiRouter::OAIApiRouter() { + createApiHandlers(); } -ApiRouter::ApiRouter() { - OAIPetApiApiHandler = new OAIPetApiHandler(); - OAIStoreApiApiHandler = new OAIStoreApiHandler(); - OAIUserApiApiHandler = new OAIUserApiHandler(); - -} - -ApiRouter::~ApiRouter(){ - qDebug() << "~ApiRouter()"; +OAIApiRouter::~OAIApiRouter(){ + qDebug() << "~ApiRouter()"; delete OAIPetApiApiHandler; delete OAIStoreApiApiHandler; delete OAIUserApiApiHandler; - } -void ApiRouter::setUpRoutes() { +void OAIApiRouter::createApiHandlers() { + OAIPetApiApiHandler = new OAIPetApiHandler(); + OAIStoreApiApiHandler = new OAIStoreApiHandler(); + OAIUserApiApiHandler = new OAIUserApiHandler(); +} + +void OAIApiRouter::setUpRoutes() { - Routes.insert("/v2/pet",[this](QHttpEngine::Socket *socket) { - if(toQHttpEngineMethod("POST") == socket->method()){ + Routes.insert(QString("%1 %2").arg("POST").arg("/v2/pet").toLower(), [this](QHttpEngine::Socket *socket) { auto reqObj = new OAIPetApiRequest(socket, OAIPetApiApiHandler); reqObj->addPetRequest(); - } }); - Routes.insert("/v2/pet/findByStatus",[this](QHttpEngine::Socket *socket) { - if(toQHttpEngineMethod("GET") == socket->method()){ + Routes.insert(QString("%1 %2").arg("GET").arg("/v2/pet/findByStatus").toLower(), [this](QHttpEngine::Socket *socket) { auto reqObj = new OAIPetApiRequest(socket, OAIPetApiApiHandler); reqObj->findPetsByStatusRequest(); - } }); - Routes.insert("/v2/pet/findByTags",[this](QHttpEngine::Socket *socket) { - if(toQHttpEngineMethod("GET") == socket->method()){ + Routes.insert(QString("%1 %2").arg("GET").arg("/v2/pet/findByTags").toLower(), [this](QHttpEngine::Socket *socket) { auto reqObj = new OAIPetApiRequest(socket, OAIPetApiApiHandler); reqObj->findPetsByTagsRequest(); - } }); - Routes.insert("/v2/pet",[this](QHttpEngine::Socket *socket) { - if(toQHttpEngineMethod("PUT") == socket->method()){ + Routes.insert(QString("%1 %2").arg("PUT").arg("/v2/pet").toLower(), [this](QHttpEngine::Socket *socket) { auto reqObj = new OAIPetApiRequest(socket, OAIPetApiApiHandler); reqObj->updatePetRequest(); - } }); - Routes.insert("/v2/store/inventory",[this](QHttpEngine::Socket *socket) { - if(toQHttpEngineMethod("GET") == socket->method()){ + Routes.insert(QString("%1 %2").arg("GET").arg("/v2/store/inventory").toLower(), [this](QHttpEngine::Socket *socket) { auto reqObj = new OAIStoreApiRequest(socket, OAIStoreApiApiHandler); reqObj->getInventoryRequest(); - } }); - Routes.insert("/v2/store/order",[this](QHttpEngine::Socket *socket) { - if(toQHttpEngineMethod("POST") == socket->method()){ + Routes.insert(QString("%1 %2").arg("POST").arg("/v2/store/order").toLower(), [this](QHttpEngine::Socket *socket) { auto reqObj = new OAIStoreApiRequest(socket, OAIStoreApiApiHandler); reqObj->placeOrderRequest(); - } }); - Routes.insert("/v2/user",[this](QHttpEngine::Socket *socket) { - if(toQHttpEngineMethod("POST") == socket->method()){ + Routes.insert(QString("%1 %2").arg("POST").arg("/v2/user").toLower(), [this](QHttpEngine::Socket *socket) { auto reqObj = new OAIUserApiRequest(socket, OAIUserApiApiHandler); reqObj->createUserRequest(); - } }); - Routes.insert("/v2/user/createWithArray",[this](QHttpEngine::Socket *socket) { - if(toQHttpEngineMethod("POST") == socket->method()){ + Routes.insert(QString("%1 %2").arg("POST").arg("/v2/user/createWithArray").toLower(), [this](QHttpEngine::Socket *socket) { auto reqObj = new OAIUserApiRequest(socket, OAIUserApiApiHandler); reqObj->createUsersWithArrayInputRequest(); - } }); - Routes.insert("/v2/user/createWithList",[this](QHttpEngine::Socket *socket) { - if(toQHttpEngineMethod("POST") == socket->method()){ + Routes.insert(QString("%1 %2").arg("POST").arg("/v2/user/createWithList").toLower(), [this](QHttpEngine::Socket *socket) { auto reqObj = new OAIUserApiRequest(socket, OAIUserApiApiHandler); reqObj->createUsersWithListInputRequest(); - } }); - Routes.insert("/v2/user/login",[this](QHttpEngine::Socket *socket) { - if(toQHttpEngineMethod("GET") == socket->method()){ + Routes.insert(QString("%1 %2").arg("GET").arg("/v2/user/login").toLower(), [this](QHttpEngine::Socket *socket) { auto reqObj = new OAIUserApiRequest(socket, OAIUserApiApiHandler); reqObj->loginUserRequest(); - } }); - Routes.insert("/v2/user/logout",[this](QHttpEngine::Socket *socket) { - if(toQHttpEngineMethod("GET") == socket->method()){ + Routes.insert(QString("%1 %2").arg("GET").arg("/v2/user/logout").toLower(), [this](QHttpEngine::Socket *socket) { auto reqObj = new OAIUserApiRequest(socket, OAIUserApiApiHandler); reqObj->logoutUserRequest(); - } - }); + }); } -void ApiRouter::processRequest(QHttpEngine::Socket *socket){ - if (Routes.contains(socket->path())) { - for(auto endpoints : Routes.values(socket->path())) { - endpoints.operator()(socket); - } - } else - { - { - QString completePath("/v2/pet/{petId}"); - QString pet_idPathParam("{"); - pet_idPathParam.append("petId").append("}"); - completePath.replace("/", "\\/"); // replace '/' with '\/' for regex - completePath.replace(pet_idPathParam, "([^\\/]*?)"); // match anything but '/'' - completePath.append("$"); // End of string - QRegularExpression re(completePath, QRegularExpression::CaseInsensitiveOption); - QRegularExpressionMatch match = re.match(socket->path()); - if ((toQHttpEngineMethod("DELETE") == socket->method()) && match.hasMatch() ) { - QString pathparam = match.captured(1); - auto reqObj = new OAIPetApiRequest(socket, OAIPetApiApiHandler); - reqObj->deletePetRequest(pathparam);; - return; - } - } - { - QString completePath("/v2/pet/{petId}"); - QString pet_idPathParam("{"); - pet_idPathParam.append("petId").append("}"); - completePath.replace("/", "\\/"); // replace '/' with '\/' for regex - completePath.replace(pet_idPathParam, "([^\\/]*?)"); // match anything but '/'' - completePath.append("$"); // End of string - QRegularExpression re(completePath, QRegularExpression::CaseInsensitiveOption); - QRegularExpressionMatch match = re.match(socket->path()); - if ((toQHttpEngineMethod("GET") == socket->method()) && match.hasMatch() ) { - QString pathparam = match.captured(1); - auto reqObj = new OAIPetApiRequest(socket, OAIPetApiApiHandler); - reqObj->getPetByIdRequest(pathparam);; - return; - } - } - { - QString completePath("/v2/pet/{petId}"); - QString pet_idPathParam("{"); - pet_idPathParam.append("petId").append("}"); - completePath.replace("/", "\\/"); // replace '/' with '\/' for regex - completePath.replace(pet_idPathParam, "([^\\/]*?)"); // match anything but '/'' - completePath.append("$"); // End of string - QRegularExpression re(completePath, QRegularExpression::CaseInsensitiveOption); - QRegularExpressionMatch match = re.match(socket->path()); - if ((toQHttpEngineMethod("POST") == socket->method()) && match.hasMatch() ) { - QString pathparam = match.captured(1); - auto reqObj = new OAIPetApiRequest(socket, OAIPetApiApiHandler); - reqObj->updatePetWithFormRequest(pathparam);; - return; - } - } - { - QString completePath("/v2/pet/{petId}/uploadImage"); - QString pet_idPathParam("{"); - pet_idPathParam.append("petId").append("}"); - completePath.replace("/", "\\/"); // replace '/' with '\/' for regex - completePath.replace(pet_idPathParam, "([^\\/]*?)"); // match anything but '/'' - completePath.append("$"); // End of string - QRegularExpression re(completePath, QRegularExpression::CaseInsensitiveOption); - QRegularExpressionMatch match = re.match(socket->path()); - if ((toQHttpEngineMethod("POST") == socket->method()) && match.hasMatch() ) { - QString pathparam = match.captured(1); - auto reqObj = new OAIPetApiRequest(socket, OAIPetApiApiHandler); - reqObj->uploadFileRequest(pathparam);; - return; - } - } - { - QString completePath("/v2/store/order/{orderId}"); - QString order_idPathParam("{"); - order_idPathParam.append("orderId").append("}"); - completePath.replace("/", "\\/"); // replace '/' with '\/' for regex - completePath.replace(order_idPathParam, "([^\\/]*?)"); // match anything but '/'' - completePath.append("$"); // End of string - QRegularExpression re(completePath, QRegularExpression::CaseInsensitiveOption); - QRegularExpressionMatch match = re.match(socket->path()); - if ((toQHttpEngineMethod("DELETE") == socket->method()) && match.hasMatch() ) { - QString pathparam = match.captured(1); - auto reqObj = new OAIStoreApiRequest(socket, OAIStoreApiApiHandler); - reqObj->deleteOrderRequest(pathparam);; - return; - } - } - { - QString completePath("/v2/store/order/{orderId}"); - QString order_idPathParam("{"); - order_idPathParam.append("orderId").append("}"); - completePath.replace("/", "\\/"); // replace '/' with '\/' for regex - completePath.replace(order_idPathParam, "([^\\/]*?)"); // match anything but '/'' - completePath.append("$"); // End of string - QRegularExpression re(completePath, QRegularExpression::CaseInsensitiveOption); - QRegularExpressionMatch match = re.match(socket->path()); - if ((toQHttpEngineMethod("GET") == socket->method()) && match.hasMatch() ) { - QString pathparam = match.captured(1); - auto reqObj = new OAIStoreApiRequest(socket, OAIStoreApiApiHandler); - reqObj->getOrderByIdRequest(pathparam);; - return; - } - } - { - QString completePath("/v2/user/{username}"); - QString usernamePathParam("{"); - usernamePathParam.append("username").append("}"); - completePath.replace("/", "\\/"); // replace '/' with '\/' for regex - completePath.replace(usernamePathParam, "([^\\/]*?)"); // match anything but '/'' - completePath.append("$"); // End of string - QRegularExpression re(completePath, QRegularExpression::CaseInsensitiveOption); - QRegularExpressionMatch match = re.match(socket->path()); - if ((toQHttpEngineMethod("DELETE") == socket->method()) && match.hasMatch() ) { - QString pathparam = match.captured(1); - auto reqObj = new OAIUserApiRequest(socket, OAIUserApiApiHandler); - reqObj->deleteUserRequest(pathparam);; - return; - } - } - { - QString completePath("/v2/user/{username}"); - QString usernamePathParam("{"); - usernamePathParam.append("username").append("}"); - completePath.replace("/", "\\/"); // replace '/' with '\/' for regex - completePath.replace(usernamePathParam, "([^\\/]*?)"); // match anything but '/'' - completePath.append("$"); // End of string - QRegularExpression re(completePath, QRegularExpression::CaseInsensitiveOption); - QRegularExpressionMatch match = re.match(socket->path()); - if ((toQHttpEngineMethod("GET") == socket->method()) && match.hasMatch() ) { - QString pathparam = match.captured(1); - auto reqObj = new OAIUserApiRequest(socket, OAIUserApiApiHandler); - reqObj->getUserByNameRequest(pathparam);; - return; - } - } - { - QString completePath("/v2/user/{username}"); - QString usernamePathParam("{"); - usernamePathParam.append("username").append("}"); - completePath.replace("/", "\\/"); // replace '/' with '\/' for regex - completePath.replace(usernamePathParam, "([^\\/]*?)"); // match anything but '/'' - completePath.append("$"); // End of string - QRegularExpression re(completePath, QRegularExpression::CaseInsensitiveOption); - QRegularExpressionMatch match = re.match(socket->path()); - if ((toQHttpEngineMethod("PUT") == socket->method()) && match.hasMatch() ) { - QString pathparam = match.captured(1); - auto reqObj = new OAIUserApiRequest(socket, OAIUserApiApiHandler); - reqObj->updateUserRequest(pathparam);; - return; - } - } +void OAIApiRouter::processRequest(QHttpEngine::Socket *socket){ + if( handleRequest(socket) ){ + return; + } + if( handleRequestAndExtractPathParam(socket) ){ + return; } socket->setStatusCode(QHttpEngine::Socket::NotFound); if(socket->isOpen()){ socket->writeHeaders(); socket->close(); } - return; } + +bool OAIApiRouter::handleRequest(QHttpEngine::Socket *socket){ + auto reqPath = QString("%1 %2").arg(fromQHttpEngineMethod(socket->method())).arg(socket->path()).toLower(); + if ( Routes.contains(reqPath) ) { + Routes.value(reqPath).operator()(socket); + return true; + } + return false; +} + +bool OAIApiRouter::handleRequestAndExtractPathParam(QHttpEngine::Socket *socket){ + auto reqPath = QString("%1 %2").arg(fromQHttpEngineMethod(socket->method())).arg(socket->path()).toLower(); + { + auto completePath = QString("%1 %2").arg("DELETE").arg("/v2/pet/{petId}").toLower(); + if ( reqPath.startsWith(completePath.leftRef( completePath.indexOf(QString("/{")))) ) { + QRegularExpression parExpr( R"(\{([^\/\\s]+)\})" ); + completePath.replace( parExpr, R"((?<\1>[^\/\s]+))" ); + completePath.append("[\\/]?$"); + QRegularExpression pathExpr( completePath ); + QRegularExpressionMatch match = pathExpr.match( reqPath ); + if ( match.hasMatch() ){ + QString petId = match.captured(QString("petId").toLower()); + auto reqObj = new OAIPetApiRequest(socket, OAIPetApiApiHandler); + reqObj->deletePetRequest(petId); + return true; + } + } + } + { + auto completePath = QString("%1 %2").arg("GET").arg("/v2/pet/{petId}").toLower(); + if ( reqPath.startsWith(completePath.leftRef( completePath.indexOf(QString("/{")))) ) { + QRegularExpression parExpr( R"(\{([^\/\\s]+)\})" ); + completePath.replace( parExpr, R"((?<\1>[^\/\s]+))" ); + completePath.append("[\\/]?$"); + QRegularExpression pathExpr( completePath ); + QRegularExpressionMatch match = pathExpr.match( reqPath ); + if ( match.hasMatch() ){ + QString petId = match.captured(QString("petId").toLower()); + auto reqObj = new OAIPetApiRequest(socket, OAIPetApiApiHandler); + reqObj->getPetByIdRequest(petId); + return true; + } + } + } + { + auto completePath = QString("%1 %2").arg("POST").arg("/v2/pet/{petId}").toLower(); + if ( reqPath.startsWith(completePath.leftRef( completePath.indexOf(QString("/{")))) ) { + QRegularExpression parExpr( R"(\{([^\/\\s]+)\})" ); + completePath.replace( parExpr, R"((?<\1>[^\/\s]+))" ); + completePath.append("[\\/]?$"); + QRegularExpression pathExpr( completePath ); + QRegularExpressionMatch match = pathExpr.match( reqPath ); + if ( match.hasMatch() ){ + QString petId = match.captured(QString("petId").toLower()); + auto reqObj = new OAIPetApiRequest(socket, OAIPetApiApiHandler); + reqObj->updatePetWithFormRequest(petId); + return true; + } + } + } + { + auto completePath = QString("%1 %2").arg("POST").arg("/v2/pet/{petId}/uploadImage").toLower(); + if ( reqPath.startsWith(completePath.leftRef( completePath.indexOf(QString("/{")))) ) { + QRegularExpression parExpr( R"(\{([^\/\\s]+)\})" ); + completePath.replace( parExpr, R"((?<\1>[^\/\s]+))" ); + completePath.append("[\\/]?$"); + QRegularExpression pathExpr( completePath ); + QRegularExpressionMatch match = pathExpr.match( reqPath ); + if ( match.hasMatch() ){ + QString petId = match.captured(QString("petId").toLower()); + auto reqObj = new OAIPetApiRequest(socket, OAIPetApiApiHandler); + reqObj->uploadFileRequest(petId); + return true; + } + } + } + { + auto completePath = QString("%1 %2").arg("DELETE").arg("/v2/store/order/{orderId}").toLower(); + if ( reqPath.startsWith(completePath.leftRef( completePath.indexOf(QString("/{")))) ) { + QRegularExpression parExpr( R"(\{([^\/\\s]+)\})" ); + completePath.replace( parExpr, R"((?<\1>[^\/\s]+))" ); + completePath.append("[\\/]?$"); + QRegularExpression pathExpr( completePath ); + QRegularExpressionMatch match = pathExpr.match( reqPath ); + if ( match.hasMatch() ){ + QString orderId = match.captured(QString("orderId").toLower()); + auto reqObj = new OAIStoreApiRequest(socket, OAIStoreApiApiHandler); + reqObj->deleteOrderRequest(orderId); + return true; + } + } + } + { + auto completePath = QString("%1 %2").arg("GET").arg("/v2/store/order/{orderId}").toLower(); + if ( reqPath.startsWith(completePath.leftRef( completePath.indexOf(QString("/{")))) ) { + QRegularExpression parExpr( R"(\{([^\/\\s]+)\})" ); + completePath.replace( parExpr, R"((?<\1>[^\/\s]+))" ); + completePath.append("[\\/]?$"); + QRegularExpression pathExpr( completePath ); + QRegularExpressionMatch match = pathExpr.match( reqPath ); + if ( match.hasMatch() ){ + QString orderId = match.captured(QString("orderId").toLower()); + auto reqObj = new OAIStoreApiRequest(socket, OAIStoreApiApiHandler); + reqObj->getOrderByIdRequest(orderId); + return true; + } + } + } + { + auto completePath = QString("%1 %2").arg("DELETE").arg("/v2/user/{username}").toLower(); + if ( reqPath.startsWith(completePath.leftRef( completePath.indexOf(QString("/{")))) ) { + QRegularExpression parExpr( R"(\{([^\/\\s]+)\})" ); + completePath.replace( parExpr, R"((?<\1>[^\/\s]+))" ); + completePath.append("[\\/]?$"); + QRegularExpression pathExpr( completePath ); + QRegularExpressionMatch match = pathExpr.match( reqPath ); + if ( match.hasMatch() ){ + QString username = match.captured(QString("username").toLower()); + auto reqObj = new OAIUserApiRequest(socket, OAIUserApiApiHandler); + reqObj->deleteUserRequest(username); + return true; + } + } + } + { + auto completePath = QString("%1 %2").arg("GET").arg("/v2/user/{username}").toLower(); + if ( reqPath.startsWith(completePath.leftRef( completePath.indexOf(QString("/{")))) ) { + QRegularExpression parExpr( R"(\{([^\/\\s]+)\})" ); + completePath.replace( parExpr, R"((?<\1>[^\/\s]+))" ); + completePath.append("[\\/]?$"); + QRegularExpression pathExpr( completePath ); + QRegularExpressionMatch match = pathExpr.match( reqPath ); + if ( match.hasMatch() ){ + QString username = match.captured(QString("username").toLower()); + auto reqObj = new OAIUserApiRequest(socket, OAIUserApiApiHandler); + reqObj->getUserByNameRequest(username); + return true; + } + } + } + { + auto completePath = QString("%1 %2").arg("PUT").arg("/v2/user/{username}").toLower(); + if ( reqPath.startsWith(completePath.leftRef( completePath.indexOf(QString("/{")))) ) { + QRegularExpression parExpr( R"(\{([^\/\\s]+)\})" ); + completePath.replace( parExpr, R"((?<\1>[^\/\s]+))" ); + completePath.append("[\\/]?$"); + QRegularExpression pathExpr( completePath ); + QRegularExpressionMatch match = pathExpr.match( reqPath ); + if ( match.hasMatch() ){ + QString username = match.captured(QString("username").toLower()); + auto reqObj = new OAIUserApiRequest(socket, OAIUserApiApiHandler); + reqObj->updateUserRequest(username); + return true; + } + } + } + return false; +} + } diff --git a/samples/server/petstore/cpp-qt5-qhttpengine-server/server/src/handlers/OAIApiRouter.h b/samples/server/petstore/cpp-qt5-qhttpengine-server/server/src/handlers/OAIApiRouter.h index 5f3532b276..35aedba6a8 100644 --- a/samples/server/petstore/cpp-qt5-qhttpengine-server/server/src/handlers/OAIApiRouter.h +++ b/samples/server/petstore/cpp-qt5-qhttpengine-server/server/src/handlers/OAIApiRouter.h @@ -30,7 +30,7 @@ namespace OpenAPI { -class RequestHandler : public QHttpEngine::QObjectHandler +class OAIApiRequestHandler : public QHttpEngine::QObjectHandler { Q_OBJECT signals: @@ -43,21 +43,53 @@ protected: } }; -class ApiRouter : public QObject +class OAIApiRouter : public QObject { Q_OBJECT public: - ApiRouter(); - virtual ~ApiRouter(); + OAIApiRouter(); + virtual ~OAIApiRouter(); void setUpRoutes(); void processRequest(QHttpEngine::Socket *socket); private: - QMultiMap> Routes; + QMap> Routes; + QMultiMap> RoutesWithPathParam; + + bool handleRequest(QHttpEngine::Socket *socket); + bool handleRequestAndExtractPathParam(QHttpEngine::Socket *socket); + OAIPetApiHandler *OAIPetApiApiHandler; OAIStoreApiHandler *OAIStoreApiApiHandler; - OAIUserApiHandler *OAIUserApiApiHandler; + OAIUserApiHandler *OAIUserApiApiHandler; +protected: + // override this method to provide custom class derived from ApiHandler classes + virtual void createApiHandlers(); + +private : + inline QString fromQHttpEngineMethod(QHttpEngine::Socket::Method method){ + switch( method ){ + case QHttpEngine::Socket::Method::OPTIONS: + return QStringLiteral("OPTIONS"); + case QHttpEngine::Socket::Method::GET: + return QStringLiteral("GET"); + case QHttpEngine::Socket::Method::HEAD: + return QStringLiteral("HEAD"); + case QHttpEngine::Socket::Method::POST: + return QStringLiteral("POST"); + case QHttpEngine::Socket::Method::PUT: + return QStringLiteral("PUT"); + case QHttpEngine::Socket::Method::DELETE: + return QStringLiteral("DELETE"); + case QHttpEngine::Socket::Method::TRACE: + return QStringLiteral("TRACE"); + case QHttpEngine::Socket::Method::CONNECT: + return QStringLiteral("CONNECT"); + } + return QStringLiteral(""); + } + }; diff --git a/samples/server/petstore/cpp-qt5-qhttpengine-server/server/src/main.cpp b/samples/server/petstore/cpp-qt5-qhttpengine-server/server/src/main.cpp index db0590c4ed..a2f6aea81d 100644 --- a/samples/server/petstore/cpp-qt5-qhttpengine-server/server/src/main.cpp +++ b/samples/server/petstore/cpp-qt5-qhttpengine-server/server/src/main.cpp @@ -19,43 +19,43 @@ #include #include #include -#ifdef __linux__ +#ifdef __linux__ #include #include -#endif +#endif #include #include "OAIApiRouter.h" -#ifdef __linux__ +#ifdef __linux__ void catchUnixSignals(QList quitSignals) { auto handler = [](int sig) -> void { // blocking and not aysnc-signal-safe func are valid qDebug() << "\nquit the application by signal " << sig; QCoreApplication::quit(); }; - - sigset_t blocking_mask; - sigemptyset(&blocking_mask); - for (auto sig : quitSignals) - sigaddset(&blocking_mask, sig); - - struct sigaction sa; - sa.sa_handler = handler; - sa.sa_mask = blocking_mask; - sa.sa_flags = 0; - - for (auto sig : quitSignals) + + sigset_t blocking_mask; + sigemptyset(&blocking_mask); + for (auto sig : quitSignals) + sigaddset(&blocking_mask, sig); + + struct sigaction sa; + sa.sa_handler = handler; + sa.sa_mask = blocking_mask; + sa.sa_flags = 0; + + for (auto sig : quitSignals) sigaction(sig, &sa, nullptr); } -#endif +#endif int main(int argc, char * argv[]) { QCoreApplication a(argc, argv); -#ifdef __linux__ +#ifdef __linux__ QList sigs({SIGQUIT, SIGINT, SIGTERM, SIGHUP}); catchUnixSignals(sigs); -#endif +#endif // Build the command-line options QCommandLineParser parser; QCommandLineOption addressOption( @@ -80,11 +80,11 @@ int main(int argc, char * argv[]) // Obtain the values QHostAddress address = QHostAddress(parser.value(addressOption)); quint16 port = static_cast(parser.value(portOption).toInt()); - - QSharedPointer handler(new OpenAPI::RequestHandler()); - OpenAPI::ApiRouter router; + + QSharedPointer handler(new OpenAPI::OAIApiRequestHandler()); + OpenAPI::OAIApiRouter router; router.setUpRoutes(); - QObject::connect(handler.data(), &OpenAPI::RequestHandler::requestReceived, [&](QHttpEngine::Socket *socket) { + QObject::connect(handler.data(), &OpenAPI::OAIApiRequestHandler::requestReceived, [&](QHttpEngine::Socket *socket) { router.processRequest(socket); }); @@ -95,6 +95,6 @@ int main(int argc, char * argv[]) qCritical("Unable to listen on the specified port."); return 1; } - + return a.exec(); } diff --git a/samples/server/petstore/cpp-qt5-qhttpengine-server/server/src/models/OAIApiResponse.cpp b/samples/server/petstore/cpp-qt5-qhttpengine-server/server/src/models/OAIApiResponse.cpp index 7bba2a9468..0e57612820 100644 --- a/samples/server/petstore/cpp-qt5-qhttpengine-server/server/src/models/OAIApiResponse.cpp +++ b/samples/server/petstore/cpp-qt5-qhttpengine-server/server/src/models/OAIApiResponse.cpp @@ -31,7 +31,7 @@ OAIApiResponse::OAIApiResponse() { } OAIApiResponse::~OAIApiResponse() { - + } void diff --git a/samples/server/petstore/cpp-qt5-qhttpengine-server/server/src/models/OAICategory.cpp b/samples/server/petstore/cpp-qt5-qhttpengine-server/server/src/models/OAICategory.cpp index c70d263a5a..fb8ec997ce 100644 --- a/samples/server/petstore/cpp-qt5-qhttpengine-server/server/src/models/OAICategory.cpp +++ b/samples/server/petstore/cpp-qt5-qhttpengine-server/server/src/models/OAICategory.cpp @@ -31,7 +31,7 @@ OAICategory::OAICategory() { } OAICategory::~OAICategory() { - + } void diff --git a/samples/server/petstore/cpp-qt5-qhttpengine-server/server/src/models/OAIHelpers.h b/samples/server/petstore/cpp-qt5-qhttpengine-server/server/src/models/OAIHelpers.h index 0172e95377..d904bcc792 100644 --- a/samples/server/petstore/cpp-qt5-qhttpengine-server/server/src/models/OAIHelpers.h +++ b/samples/server/petstore/cpp-qt5-qhttpengine-server/server/src/models/OAIHelpers.h @@ -134,7 +134,7 @@ namespace OpenAPI { for(auto itemkey : varmap.keys() ){ T itemVal; fromJsonValue(itemVal, QJsonValue::fromVariant(varmap.value(itemkey))); - val.insert(itemkey, val); + val.insert(itemkey, itemVal); } } return; diff --git a/samples/server/petstore/cpp-qt5-qhttpengine-server/server/src/models/OAIObject.h b/samples/server/petstore/cpp-qt5-qhttpengine-server/server/src/models/OAIObject.h index 74db802a37..fe37f898f7 100644 --- a/samples/server/petstore/cpp-qt5-qhttpengine-server/server/src/models/OAIObject.h +++ b/samples/server/petstore/cpp-qt5-qhttpengine-server/server/src/models/OAIObject.h @@ -21,9 +21,9 @@ namespace OpenAPI { class OAIObject { public: virtual ~OAIObject(){ - + } - + virtual QJsonObject asJsonObject() const { return jObj; } diff --git a/samples/server/petstore/cpp-qt5-qhttpengine-server/server/src/models/OAIOrder.cpp b/samples/server/petstore/cpp-qt5-qhttpengine-server/server/src/models/OAIOrder.cpp index 7afaa063a2..567533b830 100644 --- a/samples/server/petstore/cpp-qt5-qhttpengine-server/server/src/models/OAIOrder.cpp +++ b/samples/server/petstore/cpp-qt5-qhttpengine-server/server/src/models/OAIOrder.cpp @@ -31,7 +31,7 @@ OAIOrder::OAIOrder() { } OAIOrder::~OAIOrder() { - + } void diff --git a/samples/server/petstore/cpp-qt5-qhttpengine-server/server/src/models/OAIPet.cpp b/samples/server/petstore/cpp-qt5-qhttpengine-server/server/src/models/OAIPet.cpp index 97cb339915..83e4b23f8e 100644 --- a/samples/server/petstore/cpp-qt5-qhttpengine-server/server/src/models/OAIPet.cpp +++ b/samples/server/petstore/cpp-qt5-qhttpengine-server/server/src/models/OAIPet.cpp @@ -31,7 +31,7 @@ OAIPet::OAIPet() { } OAIPet::~OAIPet() { - + } void diff --git a/samples/server/petstore/cpp-qt5-qhttpengine-server/server/src/models/OAITag.cpp b/samples/server/petstore/cpp-qt5-qhttpengine-server/server/src/models/OAITag.cpp index e8f1a69972..d450cc833f 100644 --- a/samples/server/petstore/cpp-qt5-qhttpengine-server/server/src/models/OAITag.cpp +++ b/samples/server/petstore/cpp-qt5-qhttpengine-server/server/src/models/OAITag.cpp @@ -31,7 +31,7 @@ OAITag::OAITag() { } OAITag::~OAITag() { - + } void diff --git a/samples/server/petstore/cpp-qt5-qhttpengine-server/server/src/models/OAIUser.cpp b/samples/server/petstore/cpp-qt5-qhttpengine-server/server/src/models/OAIUser.cpp index 375c8b3220..9f345cf874 100644 --- a/samples/server/petstore/cpp-qt5-qhttpengine-server/server/src/models/OAIUser.cpp +++ b/samples/server/petstore/cpp-qt5-qhttpengine-server/server/src/models/OAIUser.cpp @@ -31,7 +31,7 @@ OAIUser::OAIUser() { } OAIUser::~OAIUser() { - + } void diff --git a/samples/server/petstore/cpp-qt5-qhttpengine-server/server/src/requests/OAIPetApiRequest.cpp b/samples/server/petstore/cpp-qt5-qhttpengine-server/server/src/requests/OAIPetApiRequest.cpp index 1a5953e78b..40ccab593c 100644 --- a/samples/server/petstore/cpp-qt5-qhttpengine-server/server/src/requests/OAIPetApiRequest.cpp +++ b/samples/server/petstore/cpp-qt5-qhttpengine-server/server/src/requests/OAIPetApiRequest.cpp @@ -25,7 +25,7 @@ OAIPetApiRequest::OAIPetApiRequest(QHttpEngine::Socket *s, OAIPetApiHandler* hdl auto headers = s->headers(); for(auto itr = headers.begin(); itr != headers.end(); itr++) { requestHeaders.insert(QString(itr.key()), QString(itr.value())); - } + } } OAIPetApiRequest::~OAIPetApiRequest(){ @@ -33,7 +33,7 @@ OAIPetApiRequest::~OAIPetApiRequest(){ qDebug() << "OAIPetApiRequest::~OAIPetApiRequest()"; } -QMap +QMap OAIPetApiRequest::getRequestHeaders() const { return requestHeaders; } @@ -53,7 +53,7 @@ QHttpEngine::Socket* OAIPetApiRequest::getRawSocket(){ void OAIPetApiRequest::addPetRequest(){ qDebug() << "/v2/pet"; connect(this, &OAIPetApiRequest::addPet, handler, &OAIPetApiHandler::addPet); - + QJsonDocument doc; @@ -63,14 +63,14 @@ void OAIPetApiRequest::addPetRequest(){ ::OpenAPI::fromJsonValue(oai_pet, obj); - emit addPet( oai_pet); + emit addPet(oai_pet); } void OAIPetApiRequest::deletePetRequest(const QString& pet_idstr){ qDebug() << "/v2/pet/{petId}"; connect(this, &OAIPetApiRequest::deletePet, handler, &OAIPetApiHandler::deletePet); - + qint64 pet_id; fromStringValue(pet_idstr, pet_id); @@ -81,59 +81,59 @@ void OAIPetApiRequest::deletePetRequest(const QString& pet_idstr){ } - emit deletePet( pet_id, api_key); + emit deletePet(pet_id, api_key); } void OAIPetApiRequest::findPetsByStatusRequest(){ qDebug() << "/v2/pet/findByStatus"; connect(this, &OAIPetApiRequest::findPetsByStatus, handler, &OAIPetApiHandler::findPetsByStatus); + - - QList status; + QList status; if(socket->queryString().keys().contains("status")){ fromStringValue(socket->queryString().values("status"), status); } - emit findPetsByStatus( status); + emit findPetsByStatus(status); } void OAIPetApiRequest::findPetsByTagsRequest(){ qDebug() << "/v2/pet/findByTags"; connect(this, &OAIPetApiRequest::findPetsByTags, handler, &OAIPetApiHandler::findPetsByTags); + - - QList tags; + QList tags; if(socket->queryString().keys().contains("tags")){ fromStringValue(socket->queryString().values("tags"), tags); } - emit findPetsByTags( tags); + emit findPetsByTags(tags); } void OAIPetApiRequest::getPetByIdRequest(const QString& pet_idstr){ qDebug() << "/v2/pet/{petId}"; connect(this, &OAIPetApiRequest::getPetById, handler, &OAIPetApiHandler::getPetById); - + qint64 pet_id; fromStringValue(pet_idstr, pet_id); - emit getPetById( pet_id); + emit getPetById(pet_id); } void OAIPetApiRequest::updatePetRequest(){ qDebug() << "/v2/pet"; connect(this, &OAIPetApiRequest::updatePet, handler, &OAIPetApiHandler::updatePet); - + QJsonDocument doc; @@ -143,14 +143,14 @@ void OAIPetApiRequest::updatePetRequest(){ ::OpenAPI::fromJsonValue(oai_pet, obj); - emit updatePet( oai_pet); + emit updatePet(oai_pet); } void OAIPetApiRequest::updatePetWithFormRequest(const QString& pet_idstr){ qDebug() << "/v2/pet/{petId}"; connect(this, &OAIPetApiRequest::updatePetWithForm, handler, &OAIPetApiHandler::updatePetWithForm); - + qint64 pet_id; fromStringValue(pet_idstr, pet_id); @@ -158,14 +158,14 @@ void OAIPetApiRequest::updatePetWithFormRequest(const QString& pet_idstr){ QString name; QString status; - emit updatePetWithForm( pet_id, name, status); + emit updatePetWithForm(pet_id, name, status); } void OAIPetApiRequest::uploadFileRequest(const QString& pet_idstr){ qDebug() << "/v2/pet/{petId}/uploadImage"; connect(this, &OAIPetApiRequest::uploadFile, handler, &OAIPetApiHandler::uploadFile); - + qint64 pet_id; fromStringValue(pet_idstr, pet_id); @@ -173,13 +173,13 @@ void OAIPetApiRequest::uploadFileRequest(const QString& pet_idstr){ QString additional_metadata; QIODevice* file; - emit uploadFile( pet_id, additional_metadata, file); + emit uploadFile(pet_id, additional_metadata, file); } - + void OAIPetApiRequest::addPetResponse(){ - writeResponseHeaders(); + writeResponseHeaders(); socket->setStatusCode(QHttpEngine::Socket::OK); if(socket->isOpen()){ socket->close(); @@ -187,7 +187,7 @@ void OAIPetApiRequest::addPetResponse(){ } void OAIPetApiRequest::deletePetResponse(){ - writeResponseHeaders(); + writeResponseHeaders(); socket->setStatusCode(QHttpEngine::Socket::OK); if(socket->isOpen()){ socket->close(); @@ -222,7 +222,7 @@ void OAIPetApiRequest::getPetByIdResponse(const OAIPet& res){ } void OAIPetApiRequest::updatePetResponse(){ - writeResponseHeaders(); + writeResponseHeaders(); socket->setStatusCode(QHttpEngine::Socket::OK); if(socket->isOpen()){ socket->close(); @@ -230,7 +230,7 @@ void OAIPetApiRequest::updatePetResponse(){ } void OAIPetApiRequest::updatePetWithFormResponse(){ - writeResponseHeaders(); + writeResponseHeaders(); socket->setStatusCode(QHttpEngine::Socket::OK); if(socket->isOpen()){ socket->close(); @@ -249,7 +249,7 @@ void OAIPetApiRequest::uploadFileResponse(const OAIApiResponse& res){ void OAIPetApiRequest::addPetError(QNetworkReply::NetworkError error_type, QString& error_str){ Q_UNUSED(error_type); // TODO: Remap error_type to QHttpEngine::Socket errors - writeResponseHeaders(); + writeResponseHeaders(); socket->setStatusCode(QHttpEngine::Socket::NotFound); socket->write(error_str.toUtf8()); if(socket->isOpen()){ @@ -259,7 +259,7 @@ void OAIPetApiRequest::addPetError(QNetworkReply::NetworkError error_type, QStri void OAIPetApiRequest::deletePetError(QNetworkReply::NetworkError error_type, QString& error_str){ Q_UNUSED(error_type); // TODO: Remap error_type to QHttpEngine::Socket errors - writeResponseHeaders(); + writeResponseHeaders(); socket->setStatusCode(QHttpEngine::Socket::NotFound); socket->write(error_str.toUtf8()); if(socket->isOpen()){ @@ -302,7 +302,7 @@ void OAIPetApiRequest::getPetByIdError(const OAIPet& res, QNetworkReply::Network void OAIPetApiRequest::updatePetError(QNetworkReply::NetworkError error_type, QString& error_str){ Q_UNUSED(error_type); // TODO: Remap error_type to QHttpEngine::Socket errors - writeResponseHeaders(); + writeResponseHeaders(); socket->setStatusCode(QHttpEngine::Socket::NotFound); socket->write(error_str.toUtf8()); if(socket->isOpen()){ @@ -312,7 +312,7 @@ void OAIPetApiRequest::updatePetError(QNetworkReply::NetworkError error_type, QS void OAIPetApiRequest::updatePetWithFormError(QNetworkReply::NetworkError error_type, QString& error_str){ Q_UNUSED(error_type); // TODO: Remap error_type to QHttpEngine::Socket errors - writeResponseHeaders(); + writeResponseHeaders(); socket->setStatusCode(QHttpEngine::Socket::NotFound); socket->write(error_str.toUtf8()); if(socket->isOpen()){ @@ -336,7 +336,7 @@ void OAIPetApiRequest::sendCustomResponse(QByteArray & res, QNetworkReply::Netwo Q_UNUSED(res); // TODO Q_UNUSED(error_type); // TODO } - + void OAIPetApiRequest::sendCustomResponse(QIODevice *res, QNetworkReply::NetworkError error_type){ Q_UNUSED(res); // TODO Q_UNUSED(error_type); // TODO diff --git a/samples/server/petstore/cpp-qt5-qhttpengine-server/server/src/requests/OAIPetApiRequest.h b/samples/server/petstore/cpp-qt5-qhttpengine-server/server/src/requests/OAIPetApiRequest.h index aba7871567..da87285e0f 100644 --- a/samples/server/petstore/cpp-qt5-qhttpengine-server/server/src/requests/OAIPetApiRequest.h +++ b/samples/server/petstore/cpp-qt5-qhttpengine-server/server/src/requests/OAIPetApiRequest.h @@ -31,7 +31,7 @@ namespace OpenAPI { class OAIPetApiRequest : public QObject { Q_OBJECT - + public: OAIPetApiRequest(QHttpEngine::Socket *s, OAIPetApiHandler* handler); virtual ~OAIPetApiRequest(); @@ -99,7 +99,7 @@ private: resHeaders.insert(itr.key().toUtf8(), itr.value().toUtf8()); } socket->setHeaders(resHeaders); - socket->writeHeaders(); + socket->writeHeaders(); } }; diff --git a/samples/server/petstore/cpp-qt5-qhttpengine-server/server/src/requests/OAIStoreApiRequest.cpp b/samples/server/petstore/cpp-qt5-qhttpengine-server/server/src/requests/OAIStoreApiRequest.cpp index a383601baa..c770ae2a09 100644 --- a/samples/server/petstore/cpp-qt5-qhttpengine-server/server/src/requests/OAIStoreApiRequest.cpp +++ b/samples/server/petstore/cpp-qt5-qhttpengine-server/server/src/requests/OAIStoreApiRequest.cpp @@ -25,7 +25,7 @@ OAIStoreApiRequest::OAIStoreApiRequest(QHttpEngine::Socket *s, OAIStoreApiHandle auto headers = s->headers(); for(auto itr = headers.begin(); itr != headers.end(); itr++) { requestHeaders.insert(QString(itr.key()), QString(itr.value())); - } + } } OAIStoreApiRequest::~OAIStoreApiRequest(){ @@ -33,7 +33,7 @@ OAIStoreApiRequest::~OAIStoreApiRequest(){ qDebug() << "OAIStoreApiRequest::~OAIStoreApiRequest()"; } -QMap +QMap OAIStoreApiRequest::getRequestHeaders() const { return requestHeaders; } @@ -53,20 +53,20 @@ QHttpEngine::Socket* OAIStoreApiRequest::getRawSocket(){ void OAIStoreApiRequest::deleteOrderRequest(const QString& order_idstr){ qDebug() << "/v2/store/order/{orderId}"; connect(this, &OAIStoreApiRequest::deleteOrder, handler, &OAIStoreApiHandler::deleteOrder); - + QString order_id; fromStringValue(order_idstr, order_id); - emit deleteOrder( order_id); + emit deleteOrder(order_id); } void OAIStoreApiRequest::getInventoryRequest(){ qDebug() << "/v2/store/inventory"; connect(this, &OAIStoreApiRequest::getInventory, handler, &OAIStoreApiHandler::getInventory); - + @@ -77,20 +77,20 @@ void OAIStoreApiRequest::getInventoryRequest(){ void OAIStoreApiRequest::getOrderByIdRequest(const QString& order_idstr){ qDebug() << "/v2/store/order/{orderId}"; connect(this, &OAIStoreApiRequest::getOrderById, handler, &OAIStoreApiHandler::getOrderById); - + qint64 order_id; fromStringValue(order_idstr, order_id); - emit getOrderById( order_id); + emit getOrderById(order_id); } void OAIStoreApiRequest::placeOrderRequest(){ qDebug() << "/v2/store/order"; connect(this, &OAIStoreApiRequest::placeOrder, handler, &OAIStoreApiHandler::placeOrder); - + QJsonDocument doc; @@ -100,13 +100,13 @@ void OAIStoreApiRequest::placeOrderRequest(){ ::OpenAPI::fromJsonValue(oai_order, obj); - emit placeOrder( oai_order); + emit placeOrder(oai_order); } - + void OAIStoreApiRequest::deleteOrderResponse(){ - writeResponseHeaders(); + writeResponseHeaders(); socket->setStatusCode(QHttpEngine::Socket::OK); if(socket->isOpen()){ socket->close(); @@ -143,7 +143,7 @@ void OAIStoreApiRequest::placeOrderResponse(const OAIOrder& res){ void OAIStoreApiRequest::deleteOrderError(QNetworkReply::NetworkError error_type, QString& error_str){ Q_UNUSED(error_type); // TODO: Remap error_type to QHttpEngine::Socket errors - writeResponseHeaders(); + writeResponseHeaders(); socket->setStatusCode(QHttpEngine::Socket::NotFound); socket->write(error_str.toUtf8()); if(socket->isOpen()){ @@ -189,7 +189,7 @@ void OAIStoreApiRequest::sendCustomResponse(QByteArray & res, QNetworkReply::Net Q_UNUSED(res); // TODO Q_UNUSED(error_type); // TODO } - + void OAIStoreApiRequest::sendCustomResponse(QIODevice *res, QNetworkReply::NetworkError error_type){ Q_UNUSED(res); // TODO Q_UNUSED(error_type); // TODO diff --git a/samples/server/petstore/cpp-qt5-qhttpengine-server/server/src/requests/OAIStoreApiRequest.h b/samples/server/petstore/cpp-qt5-qhttpengine-server/server/src/requests/OAIStoreApiRequest.h index b9c6ce1c04..491e27db1f 100644 --- a/samples/server/petstore/cpp-qt5-qhttpengine-server/server/src/requests/OAIStoreApiRequest.h +++ b/samples/server/petstore/cpp-qt5-qhttpengine-server/server/src/requests/OAIStoreApiRequest.h @@ -30,7 +30,7 @@ namespace OpenAPI { class OAIStoreApiRequest : public QObject { Q_OBJECT - + public: OAIStoreApiRequest(QHttpEngine::Socket *s, OAIStoreApiHandler* handler); virtual ~OAIStoreApiRequest(); @@ -82,7 +82,7 @@ private: resHeaders.insert(itr.key().toUtf8(), itr.value().toUtf8()); } socket->setHeaders(resHeaders); - socket->writeHeaders(); + socket->writeHeaders(); } }; diff --git a/samples/server/petstore/cpp-qt5-qhttpengine-server/server/src/requests/OAIUserApiRequest.cpp b/samples/server/petstore/cpp-qt5-qhttpengine-server/server/src/requests/OAIUserApiRequest.cpp index bdc5b0b688..f7162aafad 100644 --- a/samples/server/petstore/cpp-qt5-qhttpengine-server/server/src/requests/OAIUserApiRequest.cpp +++ b/samples/server/petstore/cpp-qt5-qhttpengine-server/server/src/requests/OAIUserApiRequest.cpp @@ -25,7 +25,7 @@ OAIUserApiRequest::OAIUserApiRequest(QHttpEngine::Socket *s, OAIUserApiHandler* auto headers = s->headers(); for(auto itr = headers.begin(); itr != headers.end(); itr++) { requestHeaders.insert(QString(itr.key()), QString(itr.value())); - } + } } OAIUserApiRequest::~OAIUserApiRequest(){ @@ -33,7 +33,7 @@ OAIUserApiRequest::~OAIUserApiRequest(){ qDebug() << "OAIUserApiRequest::~OAIUserApiRequest()"; } -QMap +QMap OAIUserApiRequest::getRequestHeaders() const { return requestHeaders; } @@ -53,7 +53,7 @@ QHttpEngine::Socket* OAIUserApiRequest::getRawSocket(){ void OAIUserApiRequest::createUserRequest(){ qDebug() << "/v2/user"; connect(this, &OAIUserApiRequest::createUser, handler, &OAIUserApiHandler::createUser); - + QJsonDocument doc; @@ -63,18 +63,18 @@ void OAIUserApiRequest::createUserRequest(){ ::OpenAPI::fromJsonValue(oai_user, obj); - emit createUser( oai_user); + emit createUser(oai_user); } void OAIUserApiRequest::createUsersWithArrayInputRequest(){ qDebug() << "/v2/user/createWithArray"; connect(this, &OAIUserApiRequest::createUsersWithArrayInput, handler, &OAIUserApiHandler::createUsersWithArrayInput); - + QJsonDocument doc; - QList oai_user; + QList oai_user; if(socket->readJson(doc)){ QJsonArray jsonArray = doc.array(); foreach(QJsonValue obj, jsonArray) { @@ -85,18 +85,18 @@ void OAIUserApiRequest::createUsersWithArrayInputRequest(){ } - emit createUsersWithArrayInput( oai_user); + emit createUsersWithArrayInput(oai_user); } void OAIUserApiRequest::createUsersWithListInputRequest(){ qDebug() << "/v2/user/createWithList"; connect(this, &OAIUserApiRequest::createUsersWithListInput, handler, &OAIUserApiHandler::createUsersWithListInput); - + QJsonDocument doc; - QList oai_user; + QList oai_user; if(socket->readJson(doc)){ QJsonArray jsonArray = doc.array(); foreach(QJsonValue obj, jsonArray) { @@ -107,61 +107,61 @@ void OAIUserApiRequest::createUsersWithListInputRequest(){ } - emit createUsersWithListInput( oai_user); + emit createUsersWithListInput(oai_user); } void OAIUserApiRequest::deleteUserRequest(const QString& usernamestr){ qDebug() << "/v2/user/{username}"; connect(this, &OAIUserApiRequest::deleteUser, handler, &OAIUserApiHandler::deleteUser); - + QString username; fromStringValue(usernamestr, username); - emit deleteUser( username); + emit deleteUser(username); } void OAIUserApiRequest::getUserByNameRequest(const QString& usernamestr){ qDebug() << "/v2/user/{username}"; connect(this, &OAIUserApiRequest::getUserByName, handler, &OAIUserApiHandler::getUserByName); - + QString username; fromStringValue(usernamestr, username); - emit getUserByName( username); + emit getUserByName(username); } void OAIUserApiRequest::loginUserRequest(){ qDebug() << "/v2/user/login"; connect(this, &OAIUserApiRequest::loginUser, handler, &OAIUserApiHandler::loginUser); + - - QString username; + QString username; if(socket->queryString().keys().contains("username")){ fromStringValue(socket->queryString().value("username"), username); } - QString password; + QString password; if(socket->queryString().keys().contains("password")){ fromStringValue(socket->queryString().value("password"), password); } - emit loginUser( username, password); + emit loginUser(username, password); } void OAIUserApiRequest::logoutUserRequest(){ qDebug() << "/v2/user/logout"; connect(this, &OAIUserApiRequest::logoutUser, handler, &OAIUserApiHandler::logoutUser); - + @@ -172,7 +172,7 @@ void OAIUserApiRequest::logoutUserRequest(){ void OAIUserApiRequest::updateUserRequest(const QString& usernamestr){ qDebug() << "/v2/user/{username}"; connect(this, &OAIUserApiRequest::updateUser, handler, &OAIUserApiHandler::updateUser); - + QString username; fromStringValue(usernamestr, username); @@ -184,13 +184,13 @@ void OAIUserApiRequest::updateUserRequest(const QString& usernamestr){ ::OpenAPI::fromJsonValue(oai_user, obj); - emit updateUser( username, oai_user); + emit updateUser(username, oai_user); } - + void OAIUserApiRequest::createUserResponse(){ - writeResponseHeaders(); + writeResponseHeaders(); socket->setStatusCode(QHttpEngine::Socket::OK); if(socket->isOpen()){ socket->close(); @@ -198,7 +198,7 @@ void OAIUserApiRequest::createUserResponse(){ } void OAIUserApiRequest::createUsersWithArrayInputResponse(){ - writeResponseHeaders(); + writeResponseHeaders(); socket->setStatusCode(QHttpEngine::Socket::OK); if(socket->isOpen()){ socket->close(); @@ -206,7 +206,7 @@ void OAIUserApiRequest::createUsersWithArrayInputResponse(){ } void OAIUserApiRequest::createUsersWithListInputResponse(){ - writeResponseHeaders(); + writeResponseHeaders(); socket->setStatusCode(QHttpEngine::Socket::OK); if(socket->isOpen()){ socket->close(); @@ -214,7 +214,7 @@ void OAIUserApiRequest::createUsersWithListInputResponse(){ } void OAIUserApiRequest::deleteUserResponse(){ - writeResponseHeaders(); + writeResponseHeaders(); socket->setStatusCode(QHttpEngine::Socket::OK); if(socket->isOpen()){ socket->close(); @@ -232,15 +232,14 @@ void OAIUserApiRequest::getUserByNameResponse(const OAIUser& res){ void OAIUserApiRequest::loginUserResponse(const QString& res){ writeResponseHeaders(); - QJsonDocument resDoc(::OpenAPI::toJsonValue(res).toObject()); - socket->writeJson(resDoc); + socket->write(::OpenAPI::toStringValue(res).toUtf8()); if(socket->isOpen()){ socket->close(); } } void OAIUserApiRequest::logoutUserResponse(){ - writeResponseHeaders(); + writeResponseHeaders(); socket->setStatusCode(QHttpEngine::Socket::OK); if(socket->isOpen()){ socket->close(); @@ -248,7 +247,7 @@ void OAIUserApiRequest::logoutUserResponse(){ } void OAIUserApiRequest::updateUserResponse(){ - writeResponseHeaders(); + writeResponseHeaders(); socket->setStatusCode(QHttpEngine::Socket::OK); if(socket->isOpen()){ socket->close(); @@ -258,7 +257,7 @@ void OAIUserApiRequest::updateUserResponse(){ void OAIUserApiRequest::createUserError(QNetworkReply::NetworkError error_type, QString& error_str){ Q_UNUSED(error_type); // TODO: Remap error_type to QHttpEngine::Socket errors - writeResponseHeaders(); + writeResponseHeaders(); socket->setStatusCode(QHttpEngine::Socket::NotFound); socket->write(error_str.toUtf8()); if(socket->isOpen()){ @@ -268,7 +267,7 @@ void OAIUserApiRequest::createUserError(QNetworkReply::NetworkError error_type, void OAIUserApiRequest::createUsersWithArrayInputError(QNetworkReply::NetworkError error_type, QString& error_str){ Q_UNUSED(error_type); // TODO: Remap error_type to QHttpEngine::Socket errors - writeResponseHeaders(); + writeResponseHeaders(); socket->setStatusCode(QHttpEngine::Socket::NotFound); socket->write(error_str.toUtf8()); if(socket->isOpen()){ @@ -278,7 +277,7 @@ void OAIUserApiRequest::createUsersWithArrayInputError(QNetworkReply::NetworkErr void OAIUserApiRequest::createUsersWithListInputError(QNetworkReply::NetworkError error_type, QString& error_str){ Q_UNUSED(error_type); // TODO: Remap error_type to QHttpEngine::Socket errors - writeResponseHeaders(); + writeResponseHeaders(); socket->setStatusCode(QHttpEngine::Socket::NotFound); socket->write(error_str.toUtf8()); if(socket->isOpen()){ @@ -288,7 +287,7 @@ void OAIUserApiRequest::createUsersWithListInputError(QNetworkReply::NetworkErro void OAIUserApiRequest::deleteUserError(QNetworkReply::NetworkError error_type, QString& error_str){ Q_UNUSED(error_type); // TODO: Remap error_type to QHttpEngine::Socket errors - writeResponseHeaders(); + writeResponseHeaders(); socket->setStatusCode(QHttpEngine::Socket::NotFound); socket->write(error_str.toUtf8()); if(socket->isOpen()){ @@ -311,8 +310,7 @@ void OAIUserApiRequest::loginUserError(const QString& res, QNetworkReply::Networ Q_UNUSED(error_type); // TODO: Remap error_type to QHttpEngine::Socket errors writeResponseHeaders(); Q_UNUSED(error_str); // response will be used instead of error string - QJsonDocument resDoc(::OpenAPI::toJsonValue(res).toObject()); - socket->writeJson(resDoc); + socket->write(::OpenAPI::toStringValue(res).toUtf8()); if(socket->isOpen()){ socket->close(); } @@ -320,7 +318,7 @@ void OAIUserApiRequest::loginUserError(const QString& res, QNetworkReply::Networ void OAIUserApiRequest::logoutUserError(QNetworkReply::NetworkError error_type, QString& error_str){ Q_UNUSED(error_type); // TODO: Remap error_type to QHttpEngine::Socket errors - writeResponseHeaders(); + writeResponseHeaders(); socket->setStatusCode(QHttpEngine::Socket::NotFound); socket->write(error_str.toUtf8()); if(socket->isOpen()){ @@ -330,7 +328,7 @@ void OAIUserApiRequest::logoutUserError(QNetworkReply::NetworkError error_type, void OAIUserApiRequest::updateUserError(QNetworkReply::NetworkError error_type, QString& error_str){ Q_UNUSED(error_type); // TODO: Remap error_type to QHttpEngine::Socket errors - writeResponseHeaders(); + writeResponseHeaders(); socket->setStatusCode(QHttpEngine::Socket::NotFound); socket->write(error_str.toUtf8()); if(socket->isOpen()){ @@ -343,7 +341,7 @@ void OAIUserApiRequest::sendCustomResponse(QByteArray & res, QNetworkReply::Netw Q_UNUSED(res); // TODO Q_UNUSED(error_type); // TODO } - + void OAIUserApiRequest::sendCustomResponse(QIODevice *res, QNetworkReply::NetworkError error_type){ Q_UNUSED(res); // TODO Q_UNUSED(error_type); // TODO diff --git a/samples/server/petstore/cpp-qt5-qhttpengine-server/server/src/requests/OAIUserApiRequest.h b/samples/server/petstore/cpp-qt5-qhttpengine-server/server/src/requests/OAIUserApiRequest.h index d1b30ef196..f773347330 100644 --- a/samples/server/petstore/cpp-qt5-qhttpengine-server/server/src/requests/OAIUserApiRequest.h +++ b/samples/server/petstore/cpp-qt5-qhttpengine-server/server/src/requests/OAIUserApiRequest.h @@ -30,7 +30,7 @@ namespace OpenAPI { class OAIUserApiRequest : public QObject { Q_OBJECT - + public: OAIUserApiRequest(QHttpEngine::Socket *s, OAIUserApiHandler* handler); virtual ~OAIUserApiRequest(); @@ -98,7 +98,7 @@ private: resHeaders.insert(itr.key().toUtf8(), itr.value().toUtf8()); } socket->setHeaders(resHeaders); - socket->writeHeaders(); + socket->writeHeaders(); } }; diff --git a/samples/server/petstore/jaxrs-jersey/.openapi-generator/VERSION b/samples/server/petstore/jaxrs-jersey/.openapi-generator/VERSION index 14900cee60..c791c986fb 100644 --- a/samples/server/petstore/jaxrs-jersey/.openapi-generator/VERSION +++ b/samples/server/petstore/jaxrs-jersey/.openapi-generator/VERSION @@ -1 +1 @@ -3.2.1-SNAPSHOT \ No newline at end of file +3.2.3-SNAPSHOT \ No newline at end of file diff --git a/samples/server/petstore/jaxrs-jersey/README.md b/samples/server/petstore/jaxrs-jersey/README.md index ed00420449..64a6c60dc3 100644 --- a/samples/server/petstore/jaxrs-jersey/README.md +++ b/samples/server/petstore/jaxrs-jersey/README.md @@ -1,11 +1,12 @@ -# Swagger Jersey generated server +# JAX-RS/Jersey server with OpenAPI ## Overview -This server was generated by the [OpenAPI Generator](https://openapi-generator.tech) project. By using the -[OpenAPI-Spec](https://openapis.org) from a remote server, you can easily generate a server stub. This -is an example of building a OpenAPI-enabled JAX-RS server. +This server was generated by the [OpenAPI Generator](https://openapi-generator.tech) project. By using an +[OpenAPI-Spec](https://openapis.org), you can easily generate a server stub. +This is an example of building a OpenAPI-enabled JAX-RS server. This example uses the [JAX-RS](https://jax-rs-spec.java.net/) framework. +Jersey is used as JAX-RS implementation, `io.swagger:swagger-jersey2-jaxrs` is used to derive the OpenAPI Specification from the annotated code. To run the server, please execute the following: @@ -13,10 +14,10 @@ To run the server, please execute the following: mvn clean package jetty:run ``` -You can then view the swagger listing here: +You can then view the OpenAPI v2 specification here: ``` -http://localhost:8080/v2/openapi.json +http://localhost:8080/v2/swagger.json ``` Note that if you have configured the `host` to be something other than localhost, the calls through diff --git a/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/api/ApiException.java b/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/api/ApiException.java index 2d2990bc7f..5cc52cf8f1 100644 --- a/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/api/ApiException.java +++ b/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/api/ApiException.java @@ -1,6 +1,6 @@ package org.openapitools.api; -@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaJerseyServerCodegen", date = "2018-08-10T15:02:11.723+09:00[Asia/Tokyo]") +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaJerseyServerCodegen", date = "2018-08-29T07:47:48.785+02:00[Europe/Zurich]") public class ApiException extends Exception{ private int code; public ApiException (int code, String msg) { diff --git a/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/api/ApiOriginFilter.java b/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/api/ApiOriginFilter.java index 96f2e34830..d6aca4e4be 100644 --- a/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/api/ApiOriginFilter.java +++ b/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/api/ApiOriginFilter.java @@ -5,7 +5,7 @@ import java.io.IOException; import javax.servlet.*; import javax.servlet.http.HttpServletResponse; -@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaJerseyServerCodegen", date = "2018-08-10T15:02:11.723+09:00[Asia/Tokyo]") +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaJerseyServerCodegen", date = "2018-08-29T07:47:48.785+02:00[Europe/Zurich]") public class ApiOriginFilter implements javax.servlet.Filter { public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { diff --git a/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/api/ApiResponseMessage.java b/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/api/ApiResponseMessage.java index d25a2f4d83..15bc0653ec 100644 --- a/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/api/ApiResponseMessage.java +++ b/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/api/ApiResponseMessage.java @@ -3,7 +3,7 @@ package org.openapitools.api; import javax.xml.bind.annotation.XmlTransient; @javax.xml.bind.annotation.XmlRootElement -@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaJerseyServerCodegen", date = "2018-08-10T15:02:11.723+09:00[Asia/Tokyo]") +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaJerseyServerCodegen", date = "2018-08-29T07:47:48.785+02:00[Europe/Zurich]") public class ApiResponseMessage { public static final int ERROR = 1; public static final int WARNING = 2; diff --git a/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/api/NotFoundException.java b/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/api/NotFoundException.java index edfc4e392a..4bc02b8fc2 100644 --- a/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/api/NotFoundException.java +++ b/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/api/NotFoundException.java @@ -1,6 +1,6 @@ package org.openapitools.api; -@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaJerseyServerCodegen", date = "2018-08-10T15:02:11.723+09:00[Asia/Tokyo]") +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaJerseyServerCodegen", date = "2018-08-29T07:47:48.785+02:00[Europe/Zurich]") public class NotFoundException extends ApiException { private int code; public NotFoundException (int code, String msg) { diff --git a/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/api/PetApi.java b/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/api/PetApi.java index c65b8d422e..deaa2ea7aa 100644 --- a/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/api/PetApi.java +++ b/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/api/PetApi.java @@ -31,7 +31,7 @@ import javax.validation.constraints.*; @io.swagger.annotations.Api(description = "the pet API") -@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaJerseyServerCodegen", date = "2018-08-10T15:02:11.723+09:00[Asia/Tokyo]") +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaJerseyServerCodegen", date = "2018-08-29T07:47:48.785+02:00[Europe/Zurich]") public class PetApi { private final PetApiService delegate; diff --git a/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/api/PetApiService.java b/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/api/PetApiService.java index 95bf11d9b0..3b79de69e7 100644 --- a/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/api/PetApiService.java +++ b/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/api/PetApiService.java @@ -17,7 +17,7 @@ import java.io.InputStream; import javax.ws.rs.core.Response; import javax.ws.rs.core.SecurityContext; import javax.validation.constraints.*; -@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaJerseyServerCodegen", date = "2018-08-10T15:02:11.723+09:00[Asia/Tokyo]") +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaJerseyServerCodegen", date = "2018-08-29T07:47:48.785+02:00[Europe/Zurich]") public abstract class PetApiService { public abstract Response addPet(Pet pet,SecurityContext securityContext) throws NotFoundException; public abstract Response deletePet(Long petId,String apiKey,SecurityContext securityContext) throws NotFoundException; diff --git a/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/api/StoreApi.java b/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/api/StoreApi.java index d0f12395db..d93e01928f 100644 --- a/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/api/StoreApi.java +++ b/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/api/StoreApi.java @@ -30,7 +30,7 @@ import javax.validation.constraints.*; @io.swagger.annotations.Api(description = "the store API") -@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaJerseyServerCodegen", date = "2018-08-10T15:02:11.723+09:00[Asia/Tokyo]") +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaJerseyServerCodegen", date = "2018-08-29T07:47:48.785+02:00[Europe/Zurich]") public class StoreApi { private final StoreApiService delegate; diff --git a/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/api/StoreApiService.java b/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/api/StoreApiService.java index 13698d783a..952e554c47 100644 --- a/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/api/StoreApiService.java +++ b/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/api/StoreApiService.java @@ -16,7 +16,7 @@ import java.io.InputStream; import javax.ws.rs.core.Response; import javax.ws.rs.core.SecurityContext; import javax.validation.constraints.*; -@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaJerseyServerCodegen", date = "2018-08-10T15:02:11.723+09:00[Asia/Tokyo]") +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaJerseyServerCodegen", date = "2018-08-29T07:47:48.785+02:00[Europe/Zurich]") public abstract class StoreApiService { public abstract Response deleteOrder(String orderId,SecurityContext securityContext) throws NotFoundException; public abstract Response getInventory(SecurityContext securityContext) throws NotFoundException; diff --git a/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/api/StringUtil.java b/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/api/StringUtil.java index 8810d4383b..28589f66e9 100644 --- a/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/api/StringUtil.java +++ b/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/api/StringUtil.java @@ -1,6 +1,6 @@ package org.openapitools.api; -@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaJerseyServerCodegen", date = "2018-08-10T15:02:11.723+09:00[Asia/Tokyo]") +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaJerseyServerCodegen", date = "2018-08-29T07:47:48.785+02:00[Europe/Zurich]") public class StringUtil { /** * Check if the given array contains the given value (with case-insensitive comparison). diff --git a/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/api/UserApi.java b/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/api/UserApi.java index 2c5625c2fe..5531c4f9e6 100644 --- a/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/api/UserApi.java +++ b/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/api/UserApi.java @@ -30,7 +30,7 @@ import javax.validation.constraints.*; @io.swagger.annotations.Api(description = "the user API") -@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaJerseyServerCodegen", date = "2018-08-10T15:02:11.723+09:00[Asia/Tokyo]") +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaJerseyServerCodegen", date = "2018-08-29T07:47:48.785+02:00[Europe/Zurich]") public class UserApi { private final UserApiService delegate; diff --git a/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/api/UserApiService.java b/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/api/UserApiService.java index e5919ae31c..572a568f05 100644 --- a/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/api/UserApiService.java +++ b/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/api/UserApiService.java @@ -16,7 +16,7 @@ import java.io.InputStream; import javax.ws.rs.core.Response; import javax.ws.rs.core.SecurityContext; import javax.validation.constraints.*; -@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaJerseyServerCodegen", date = "2018-08-10T15:02:11.723+09:00[Asia/Tokyo]") +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaJerseyServerCodegen", date = "2018-08-29T07:47:48.785+02:00[Europe/Zurich]") public abstract class UserApiService { public abstract Response createUser(User user,SecurityContext securityContext) throws NotFoundException; public abstract Response createUsersWithArrayInput(List user,SecurityContext securityContext) throws NotFoundException; diff --git a/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/model/Body.java b/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/model/Body.java new file mode 100644 index 0000000000..34c1291b79 --- /dev/null +++ b/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/model/Body.java @@ -0,0 +1,114 @@ +/* + * OpenAPI Petstore + * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. + * + * OpenAPI spec version: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import javax.validation.constraints.*; + +/** + * Body + */ +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaJerseyServerCodegen", date = "2018-08-29T07:47:48.785+02:00[Europe/Zurich]") +public class Body { + @JsonProperty("name") + private String name = null; + + @JsonProperty("status") + private String status = null; + + public Body name(String name) { + this.name = name; + return this; + } + + /** + * Updated name of the pet + * @return name + **/ + @JsonProperty("name") + @ApiModelProperty(value = "Updated name of the pet") + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public Body status(String status) { + this.status = status; + return this; + } + + /** + * Updated status of the pet + * @return status + **/ + @JsonProperty("status") + @ApiModelProperty(value = "Updated status of the pet") + public String getStatus() { + return status; + } + + public void setStatus(String status) { + this.status = status; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + Body body = (Body) o; + return Objects.equals(this.name, body.name) && + Objects.equals(this.status, body.status); + } + + @Override + public int hashCode() { + return Objects.hash(name, status); + } + + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Body {\n"); + + sb.append(" name: ").append(toIndentedString(name)).append("\n"); + sb.append(" status: ").append(toIndentedString(status)).append("\n"); + 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 "); + } +} + diff --git a/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/model/Body1.java b/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/model/Body1.java new file mode 100644 index 0000000000..e57d78b0b7 --- /dev/null +++ b/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/model/Body1.java @@ -0,0 +1,115 @@ +/* + * OpenAPI Petstore + * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. + * + * OpenAPI spec version: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import java.io.File; +import javax.validation.constraints.*; + +/** + * Body1 + */ +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaJerseyServerCodegen", date = "2018-08-29T07:47:48.785+02:00[Europe/Zurich]") +public class Body1 { + @JsonProperty("additionalMetadata") + private String additionalMetadata = null; + + @JsonProperty("file") + private File file = null; + + public Body1 additionalMetadata(String additionalMetadata) { + this.additionalMetadata = additionalMetadata; + return this; + } + + /** + * Additional data to pass to server + * @return additionalMetadata + **/ + @JsonProperty("additionalMetadata") + @ApiModelProperty(value = "Additional data to pass to server") + public String getAdditionalMetadata() { + return additionalMetadata; + } + + public void setAdditionalMetadata(String additionalMetadata) { + this.additionalMetadata = additionalMetadata; + } + + public Body1 file(File file) { + this.file = file; + return this; + } + + /** + * file to upload + * @return file + **/ + @JsonProperty("file") + @ApiModelProperty(value = "file to upload") + public File getFile() { + return file; + } + + public void setFile(File file) { + this.file = file; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + Body1 body1 = (Body1) o; + return Objects.equals(this.additionalMetadata, body1.additionalMetadata) && + Objects.equals(this.file, body1.file); + } + + @Override + public int hashCode() { + return Objects.hash(additionalMetadata, file); + } + + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Body1 {\n"); + + sb.append(" additionalMetadata: ").append(toIndentedString(additionalMetadata)).append("\n"); + sb.append(" file: ").append(toIndentedString(file)).append("\n"); + 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 "); + } +} + diff --git a/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/model/Category.java b/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/model/Category.java index 76cf0f8795..47a04f30d1 100644 --- a/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/model/Category.java +++ b/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/model/Category.java @@ -24,7 +24,7 @@ import javax.validation.constraints.*; * A category for a pet */ @ApiModel(description = "A category for a pet") -@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaJerseyServerCodegen", date = "2018-08-10T15:02:11.723+09:00[Asia/Tokyo]") +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaJerseyServerCodegen", date = "2018-08-29T07:47:48.785+02:00[Europe/Zurich]") public class Category { @JsonProperty("id") private Long id = null; diff --git a/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/model/ModelApiResponse.java b/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/model/ModelApiResponse.java index 4506944790..dae86b07e4 100644 --- a/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/model/ModelApiResponse.java +++ b/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/model/ModelApiResponse.java @@ -24,7 +24,7 @@ import javax.validation.constraints.*; * Describes the result of uploading an image resource */ @ApiModel(description = "Describes the result of uploading an image resource") -@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaJerseyServerCodegen", date = "2018-08-10T15:02:11.723+09:00[Asia/Tokyo]") +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaJerseyServerCodegen", date = "2018-08-29T07:47:48.785+02:00[Europe/Zurich]") public class ModelApiResponse { @JsonProperty("code") private Integer code = null; diff --git a/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/model/Order.java b/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/model/Order.java index 1f1c23188d..b3e07ef301 100644 --- a/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/model/Order.java +++ b/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/model/Order.java @@ -26,7 +26,7 @@ import javax.validation.constraints.*; * An order for a pets from the pet store */ @ApiModel(description = "An order for a pets from the pet store") -@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaJerseyServerCodegen", date = "2018-08-10T15:02:11.723+09:00[Asia/Tokyo]") +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaJerseyServerCodegen", date = "2018-08-29T07:47:48.785+02:00[Europe/Zurich]") public class Order { @JsonProperty("id") private Long id = null; diff --git a/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/model/Pet.java b/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/model/Pet.java index 9627129291..92a06e101e 100644 --- a/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/model/Pet.java +++ b/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/model/Pet.java @@ -29,7 +29,7 @@ import javax.validation.constraints.*; * A pet for sale in the pet store */ @ApiModel(description = "A pet for sale in the pet store") -@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaJerseyServerCodegen", date = "2018-08-10T15:02:11.723+09:00[Asia/Tokyo]") +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaJerseyServerCodegen", date = "2018-08-29T07:47:48.785+02:00[Europe/Zurich]") public class Pet { @JsonProperty("id") private Long id = null; diff --git a/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/model/Tag.java b/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/model/Tag.java index 5d78706d8f..b2576bd98a 100644 --- a/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/model/Tag.java +++ b/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/model/Tag.java @@ -24,7 +24,7 @@ import javax.validation.constraints.*; * A tag for a pet */ @ApiModel(description = "A tag for a pet") -@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaJerseyServerCodegen", date = "2018-08-10T15:02:11.723+09:00[Asia/Tokyo]") +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaJerseyServerCodegen", date = "2018-08-29T07:47:48.785+02:00[Europe/Zurich]") public class Tag { @JsonProperty("id") private Long id = null; diff --git a/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/model/User.java b/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/model/User.java index 3709c05050..e417fbd7ca 100644 --- a/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/model/User.java +++ b/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/model/User.java @@ -24,7 +24,7 @@ import javax.validation.constraints.*; * A User who is purchasing from the pet store */ @ApiModel(description = "A User who is purchasing from the pet store") -@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaJerseyServerCodegen", date = "2018-08-10T15:02:11.723+09:00[Asia/Tokyo]") +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaJerseyServerCodegen", date = "2018-08-29T07:47:48.785+02:00[Europe/Zurich]") public class User { @JsonProperty("id") private Long id = null; diff --git a/samples/server/petstore/jaxrs-jersey/src/main/java/org/openapitools/api/factories/PetApiServiceFactory.java b/samples/server/petstore/jaxrs-jersey/src/main/java/org/openapitools/api/factories/PetApiServiceFactory.java index 5bd95e5f1c..79a5da655d 100644 --- a/samples/server/petstore/jaxrs-jersey/src/main/java/org/openapitools/api/factories/PetApiServiceFactory.java +++ b/samples/server/petstore/jaxrs-jersey/src/main/java/org/openapitools/api/factories/PetApiServiceFactory.java @@ -3,7 +3,7 @@ package org.openapitools.api.factories; import org.openapitools.api.PetApiService; import org.openapitools.api.impl.PetApiServiceImpl; -@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaJerseyServerCodegen", date = "2018-08-10T15:02:11.723+09:00[Asia/Tokyo]") +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaJerseyServerCodegen", date = "2018-08-29T07:47:48.785+02:00[Europe/Zurich]") public class PetApiServiceFactory { private final static PetApiService service = new PetApiServiceImpl(); diff --git a/samples/server/petstore/jaxrs-jersey/src/main/java/org/openapitools/api/factories/StoreApiServiceFactory.java b/samples/server/petstore/jaxrs-jersey/src/main/java/org/openapitools/api/factories/StoreApiServiceFactory.java index 3a9ab3531a..51f64e041a 100644 --- a/samples/server/petstore/jaxrs-jersey/src/main/java/org/openapitools/api/factories/StoreApiServiceFactory.java +++ b/samples/server/petstore/jaxrs-jersey/src/main/java/org/openapitools/api/factories/StoreApiServiceFactory.java @@ -3,7 +3,7 @@ package org.openapitools.api.factories; import org.openapitools.api.StoreApiService; import org.openapitools.api.impl.StoreApiServiceImpl; -@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaJerseyServerCodegen", date = "2018-08-10T15:02:11.723+09:00[Asia/Tokyo]") +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaJerseyServerCodegen", date = "2018-08-29T07:47:48.785+02:00[Europe/Zurich]") public class StoreApiServiceFactory { private final static StoreApiService service = new StoreApiServiceImpl(); diff --git a/samples/server/petstore/jaxrs-jersey/src/main/java/org/openapitools/api/factories/UserApiServiceFactory.java b/samples/server/petstore/jaxrs-jersey/src/main/java/org/openapitools/api/factories/UserApiServiceFactory.java index 12540d9364..8496033949 100644 --- a/samples/server/petstore/jaxrs-jersey/src/main/java/org/openapitools/api/factories/UserApiServiceFactory.java +++ b/samples/server/petstore/jaxrs-jersey/src/main/java/org/openapitools/api/factories/UserApiServiceFactory.java @@ -3,7 +3,7 @@ package org.openapitools.api.factories; import org.openapitools.api.UserApiService; import org.openapitools.api.impl.UserApiServiceImpl; -@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaJerseyServerCodegen", date = "2018-08-10T15:02:11.723+09:00[Asia/Tokyo]") +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaJerseyServerCodegen", date = "2018-08-29T07:47:48.785+02:00[Europe/Zurich]") public class UserApiServiceFactory { private final static UserApiService service = new UserApiServiceImpl(); diff --git a/samples/server/petstore/jaxrs-jersey/src/main/java/org/openapitools/api/impl/PetApiServiceImpl.java b/samples/server/petstore/jaxrs-jersey/src/main/java/org/openapitools/api/impl/PetApiServiceImpl.java index 3ef3488fe8..f4a3e11232 100644 --- a/samples/server/petstore/jaxrs-jersey/src/main/java/org/openapitools/api/impl/PetApiServiceImpl.java +++ b/samples/server/petstore/jaxrs-jersey/src/main/java/org/openapitools/api/impl/PetApiServiceImpl.java @@ -17,7 +17,7 @@ import org.glassfish.jersey.media.multipart.FormDataContentDisposition; import javax.ws.rs.core.Response; import javax.ws.rs.core.SecurityContext; import javax.validation.constraints.*; -@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaJerseyServerCodegen", date = "2018-08-10T15:02:11.723+09:00[Asia/Tokyo]") +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaJerseyServerCodegen", date = "2018-08-29T07:47:48.785+02:00[Europe/Zurich]") public class PetApiServiceImpl extends PetApiService { @Override public Response addPet(Pet pet, SecurityContext securityContext) throws NotFoundException { diff --git a/samples/server/petstore/jaxrs-jersey/src/main/java/org/openapitools/api/impl/StoreApiServiceImpl.java b/samples/server/petstore/jaxrs-jersey/src/main/java/org/openapitools/api/impl/StoreApiServiceImpl.java index b4be886cf0..8adf955011 100644 --- a/samples/server/petstore/jaxrs-jersey/src/main/java/org/openapitools/api/impl/StoreApiServiceImpl.java +++ b/samples/server/petstore/jaxrs-jersey/src/main/java/org/openapitools/api/impl/StoreApiServiceImpl.java @@ -16,7 +16,7 @@ import org.glassfish.jersey.media.multipart.FormDataContentDisposition; import javax.ws.rs.core.Response; import javax.ws.rs.core.SecurityContext; import javax.validation.constraints.*; -@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaJerseyServerCodegen", date = "2018-08-10T15:02:11.723+09:00[Asia/Tokyo]") +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaJerseyServerCodegen", date = "2018-08-29T07:47:48.785+02:00[Europe/Zurich]") public class StoreApiServiceImpl extends StoreApiService { @Override public Response deleteOrder(String orderId, SecurityContext securityContext) throws NotFoundException { diff --git a/samples/server/petstore/jaxrs-jersey/src/main/java/org/openapitools/api/impl/UserApiServiceImpl.java b/samples/server/petstore/jaxrs-jersey/src/main/java/org/openapitools/api/impl/UserApiServiceImpl.java index fb2e323efc..63312af208 100644 --- a/samples/server/petstore/jaxrs-jersey/src/main/java/org/openapitools/api/impl/UserApiServiceImpl.java +++ b/samples/server/petstore/jaxrs-jersey/src/main/java/org/openapitools/api/impl/UserApiServiceImpl.java @@ -16,7 +16,7 @@ import org.glassfish.jersey.media.multipart.FormDataContentDisposition; import javax.ws.rs.core.Response; import javax.ws.rs.core.SecurityContext; import javax.validation.constraints.*; -@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaJerseyServerCodegen", date = "2018-08-10T15:02:11.723+09:00[Asia/Tokyo]") +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaJerseyServerCodegen", date = "2018-08-29T07:47:48.785+02:00[Europe/Zurich]") public class UserApiServiceImpl extends UserApiService { @Override public Response createUser(User user, SecurityContext securityContext) throws NotFoundException { diff --git a/samples/server/petstore/jaxrs-resteasy/default/README.md b/samples/server/petstore/jaxrs-resteasy/default/README.md index 78b550b6cf..050351dfcd 100644 --- a/samples/server/petstore/jaxrs-resteasy/default/README.md +++ b/samples/server/petstore/jaxrs-resteasy/default/README.md @@ -1,22 +1,23 @@ -# Swagger generated server +# JAX-RS/RESTEasy server with OpenAPI ## Overview -This server was generated by the [swagger-codegen](https://github.com/swagger-api/swagger-codegen) project. By using the -[OpenAPI-Spec](https://github.com/swagger-api/swagger-core/wiki) from a remote server, you can easily generate a server stub. This -is an example of building a swagger-enabled JAX-RS server. +This server was generated by the [OpenAPI Generator](https://openapi-generator.tech) project. By using an +[OpenAPI-Spec](https://openapis.org), you can easily generate a server stub. +This is an example of building a OpenAPI-enabled JAX-RS server. This example uses the [JAX-RS](https://jax-rs-spec.java.net/) framework. +RESTEasy is used as JAX-RS implementation library and is defined as dependency. To run the server, please execute the following: ``` -mvn clean package jetty:run +mvn -Djetty.http.port=8080 package org.eclipse.jetty:jetty-maven-plugin:run ``` -You can then view the swagger listing here: +You can then view the OpenAPI v2 specification here: ``` -http://localhost:8080/v2/openapi.json +http://localhost:8080/v2/swagger.json ``` Note that if you have configured the `host` to be something other than localhost, the calls through diff --git a/samples/server/petstore/jaxrs-resteasy/eap-java8/README.md b/samples/server/petstore/jaxrs-resteasy/eap-java8/README.md index 7bb1cfae22..74db54ed53 100644 --- a/samples/server/petstore/jaxrs-resteasy/eap-java8/README.md +++ b/samples/server/petstore/jaxrs-resteasy/eap-java8/README.md @@ -1,18 +1,18 @@ -# Swagger generated server +# JAX-RS/Resteasy server with OpenAPI for Jboss EAP ## Overview -This server was generated by the [swagger-codegen](https://github.com/swagger-api/swagger-codegen) project. By using the -[OpenAPI-Spec](https://github.com/swagger-api/swagger-core/wiki) from a remote server, you can easily generate a server stub. This -is an example of building a swagger-enabled JAX-RS server. +This server was generated by the [OpenAPI Generator](https://openapi-generator.tech) project. By using an +[OpenAPI-Spec](https://openapis.org), you can easily generate a server stub. +This is an example of building a OpenAPI-enabled JAX-RS server. This example uses the [JAX-RS](https://jax-rs-spec.java.net/) framework for Jboss Resteasy. You can deploy the WAR file to Jboss EAP or any other JEE server supporting Jboss Resteasy. -You can then view the swagger listing here: +You can then view the OpenAPI v2 specification here: ``` -http://localhost:8080/v2/openapi.json +http://localhost:8080/v2/swagger.json ``` Note that if you have configured the `host` to be something other than localhost, the calls through diff --git a/samples/server/petstore/jaxrs-resteasy/eap-joda/README.md b/samples/server/petstore/jaxrs-resteasy/eap-joda/README.md index 7bb1cfae22..74db54ed53 100644 --- a/samples/server/petstore/jaxrs-resteasy/eap-joda/README.md +++ b/samples/server/petstore/jaxrs-resteasy/eap-joda/README.md @@ -1,18 +1,18 @@ -# Swagger generated server +# JAX-RS/Resteasy server with OpenAPI for Jboss EAP ## Overview -This server was generated by the [swagger-codegen](https://github.com/swagger-api/swagger-codegen) project. By using the -[OpenAPI-Spec](https://github.com/swagger-api/swagger-core/wiki) from a remote server, you can easily generate a server stub. This -is an example of building a swagger-enabled JAX-RS server. +This server was generated by the [OpenAPI Generator](https://openapi-generator.tech) project. By using an +[OpenAPI-Spec](https://openapis.org), you can easily generate a server stub. +This is an example of building a OpenAPI-enabled JAX-RS server. This example uses the [JAX-RS](https://jax-rs-spec.java.net/) framework for Jboss Resteasy. You can deploy the WAR file to Jboss EAP or any other JEE server supporting Jboss Resteasy. -You can then view the swagger listing here: +You can then view the OpenAPI v2 specification here: ``` -http://localhost:8080/v2/openapi.json +http://localhost:8080/v2/swagger.json ``` Note that if you have configured the `host` to be something other than localhost, the calls through diff --git a/samples/server/petstore/jaxrs-resteasy/eap/README.md b/samples/server/petstore/jaxrs-resteasy/eap/README.md index 7bb1cfae22..74db54ed53 100644 --- a/samples/server/petstore/jaxrs-resteasy/eap/README.md +++ b/samples/server/petstore/jaxrs-resteasy/eap/README.md @@ -1,18 +1,18 @@ -# Swagger generated server +# JAX-RS/Resteasy server with OpenAPI for Jboss EAP ## Overview -This server was generated by the [swagger-codegen](https://github.com/swagger-api/swagger-codegen) project. By using the -[OpenAPI-Spec](https://github.com/swagger-api/swagger-core/wiki) from a remote server, you can easily generate a server stub. This -is an example of building a swagger-enabled JAX-RS server. +This server was generated by the [OpenAPI Generator](https://openapi-generator.tech) project. By using an +[OpenAPI-Spec](https://openapis.org), you can easily generate a server stub. +This is an example of building a OpenAPI-enabled JAX-RS server. This example uses the [JAX-RS](https://jax-rs-spec.java.net/) framework for Jboss Resteasy. You can deploy the WAR file to Jboss EAP or any other JEE server supporting Jboss Resteasy. -You can then view the swagger listing here: +You can then view the OpenAPI v2 specification here: ``` -http://localhost:8080/v2/openapi.json +http://localhost:8080/v2/swagger.json ``` Note that if you have configured the `host` to be something other than localhost, the calls through diff --git a/samples/server/petstore/jaxrs-resteasy/joda/README.md b/samples/server/petstore/jaxrs-resteasy/joda/README.md index 78b550b6cf..050351dfcd 100644 --- a/samples/server/petstore/jaxrs-resteasy/joda/README.md +++ b/samples/server/petstore/jaxrs-resteasy/joda/README.md @@ -1,22 +1,23 @@ -# Swagger generated server +# JAX-RS/RESTEasy server with OpenAPI ## Overview -This server was generated by the [swagger-codegen](https://github.com/swagger-api/swagger-codegen) project. By using the -[OpenAPI-Spec](https://github.com/swagger-api/swagger-core/wiki) from a remote server, you can easily generate a server stub. This -is an example of building a swagger-enabled JAX-RS server. +This server was generated by the [OpenAPI Generator](https://openapi-generator.tech) project. By using an +[OpenAPI-Spec](https://openapis.org), you can easily generate a server stub. +This is an example of building a OpenAPI-enabled JAX-RS server. This example uses the [JAX-RS](https://jax-rs-spec.java.net/) framework. +RESTEasy is used as JAX-RS implementation library and is defined as dependency. To run the server, please execute the following: ``` -mvn clean package jetty:run +mvn -Djetty.http.port=8080 package org.eclipse.jetty:jetty-maven-plugin:run ``` -You can then view the swagger listing here: +You can then view the OpenAPI v2 specification here: ``` -http://localhost:8080/v2/openapi.json +http://localhost:8080/v2/swagger.json ``` Note that if you have configured the `host` to be something other than localhost, the calls through diff --git a/samples/server/petstore/jaxrs-spec-interface/README.md b/samples/server/petstore/jaxrs-spec-interface/README.md new file mode 100644 index 0000000000..553be1f4b1 --- /dev/null +++ b/samples/server/petstore/jaxrs-spec-interface/README.md @@ -0,0 +1,12 @@ +# JAX-RS server with OpenAPI + +## Overview +This server was generated by the [OpenAPI Generator](https://openapi-generator.tech) project. By using an +[OpenAPI-Spec](https://openapis.org), you can easily generate a server stub. + +This is an example of building a OpenAPI-enabled JAX-RS server. +This example uses the [JAX-RS](https://jax-rs-spec.java.net/) framework. + +This project produces a jar that defines some interfaces. +The jar can be used in combination with an other project providing the implementation. + diff --git a/samples/server/petstore/jaxrs-spec/README.md b/samples/server/petstore/jaxrs-spec/README.md new file mode 100644 index 0000000000..603301eaf3 --- /dev/null +++ b/samples/server/petstore/jaxrs-spec/README.md @@ -0,0 +1,27 @@ +# JAX-RS server with OpenAPI + +## Overview +This server was generated by the [OpenAPI Generator](https://openapi-generator.tech) project. By using an +[OpenAPI-Spec](https://openapis.org), you can easily generate a server stub. + +This is an example of building a OpenAPI-enabled JAX-RS server. +This example uses the [JAX-RS](https://jax-rs-spec.java.net/) framework. + + +The JAX-RS implementation needs to be provided by the application server you are deploying on. + +To run the server from the command line, you can use maven to provision an start a TomEE Server. +Please execute the following: + +``` +mvn -Dtomee-embedded-plugin.http=80 package org.apache.tomee.maven:tomee-embedded-maven-plugin:7.0.5:run +``` + +You can then call your server endpoints under: + +``` +http://localhost:80/v2/ +``` + +Note that if you have configured the `host` to be something other than localhost, the calls through +swagger-ui will be directed to that host and not localhost! diff --git a/samples/server/petstore/jaxrs/jersey1-useTags/README.md b/samples/server/petstore/jaxrs/jersey1-useTags/README.md index 87263cc050..28668de74f 100644 --- a/samples/server/petstore/jaxrs/jersey1-useTags/README.md +++ b/samples/server/petstore/jaxrs/jersey1-useTags/README.md @@ -1,11 +1,12 @@ -# Swagger Jersey generated server +# JAX-RS/Jersey server with OpenAPI ## Overview -This server was generated by the [swagger-codegen](https://github.com/swagger-api/swagger-codegen) project. By using the -[OpenAPI-Spec](https://github.com/swagger-api/swagger-core/wiki) from a remote server, you can easily generate a server stub. This -is an example of building a swagger-enabled JAX-RS server. +This server was generated by the [OpenAPI Generator](https://openapi-generator.tech) project. By using an +[OpenAPI-Spec](https://openapis.org), you can easily generate a server stub. +This is an example of building a OpenAPI-enabled JAX-RS server. This example uses the [JAX-RS](https://jax-rs-spec.java.net/) framework. +Jersey is used as JAX-RS implementation, `io.swagger:swagger-jersey2-jaxrs` is used to derive the OpenAPI Specification from the annotated code. To run the server, please execute the following: @@ -13,10 +14,10 @@ To run the server, please execute the following: mvn clean package jetty:run ``` -You can then view the swagger listing here: +You can then view the OpenAPI v2 specification here: ``` -http://localhost:8082/v2/openapi.json +http://localhost:8082/v2/swagger.json ``` Note that if you have configured the `host` to be something other than localhost, the calls through diff --git a/samples/server/petstore/jaxrs/jersey1/README.md b/samples/server/petstore/jaxrs/jersey1/README.md index 87263cc050..28668de74f 100644 --- a/samples/server/petstore/jaxrs/jersey1/README.md +++ b/samples/server/petstore/jaxrs/jersey1/README.md @@ -1,11 +1,12 @@ -# Swagger Jersey generated server +# JAX-RS/Jersey server with OpenAPI ## Overview -This server was generated by the [swagger-codegen](https://github.com/swagger-api/swagger-codegen) project. By using the -[OpenAPI-Spec](https://github.com/swagger-api/swagger-core/wiki) from a remote server, you can easily generate a server stub. This -is an example of building a swagger-enabled JAX-RS server. +This server was generated by the [OpenAPI Generator](https://openapi-generator.tech) project. By using an +[OpenAPI-Spec](https://openapis.org), you can easily generate a server stub. +This is an example of building a OpenAPI-enabled JAX-RS server. This example uses the [JAX-RS](https://jax-rs-spec.java.net/) framework. +Jersey is used as JAX-RS implementation, `io.swagger:swagger-jersey2-jaxrs` is used to derive the OpenAPI Specification from the annotated code. To run the server, please execute the following: @@ -13,10 +14,10 @@ To run the server, please execute the following: mvn clean package jetty:run ``` -You can then view the swagger listing here: +You can then view the OpenAPI v2 specification here: ``` -http://localhost:8082/v2/openapi.json +http://localhost:8082/v2/swagger.json ``` Note that if you have configured the `host` to be something other than localhost, the calls through diff --git a/samples/server/petstore/jaxrs/jersey2-useTags/README.md b/samples/server/petstore/jaxrs/jersey2-useTags/README.md index 87263cc050..28668de74f 100644 --- a/samples/server/petstore/jaxrs/jersey2-useTags/README.md +++ b/samples/server/petstore/jaxrs/jersey2-useTags/README.md @@ -1,11 +1,12 @@ -# Swagger Jersey generated server +# JAX-RS/Jersey server with OpenAPI ## Overview -This server was generated by the [swagger-codegen](https://github.com/swagger-api/swagger-codegen) project. By using the -[OpenAPI-Spec](https://github.com/swagger-api/swagger-core/wiki) from a remote server, you can easily generate a server stub. This -is an example of building a swagger-enabled JAX-RS server. +This server was generated by the [OpenAPI Generator](https://openapi-generator.tech) project. By using an +[OpenAPI-Spec](https://openapis.org), you can easily generate a server stub. +This is an example of building a OpenAPI-enabled JAX-RS server. This example uses the [JAX-RS](https://jax-rs-spec.java.net/) framework. +Jersey is used as JAX-RS implementation, `io.swagger:swagger-jersey2-jaxrs` is used to derive the OpenAPI Specification from the annotated code. To run the server, please execute the following: @@ -13,10 +14,10 @@ To run the server, please execute the following: mvn clean package jetty:run ``` -You can then view the swagger listing here: +You can then view the OpenAPI v2 specification here: ``` -http://localhost:8082/v2/openapi.json +http://localhost:8082/v2/swagger.json ``` Note that if you have configured the `host` to be something other than localhost, the calls through diff --git a/samples/server/petstore/jaxrs/jersey2/README.md b/samples/server/petstore/jaxrs/jersey2/README.md index 87263cc050..28668de74f 100644 --- a/samples/server/petstore/jaxrs/jersey2/README.md +++ b/samples/server/petstore/jaxrs/jersey2/README.md @@ -1,11 +1,12 @@ -# Swagger Jersey generated server +# JAX-RS/Jersey server with OpenAPI ## Overview -This server was generated by the [swagger-codegen](https://github.com/swagger-api/swagger-codegen) project. By using the -[OpenAPI-Spec](https://github.com/swagger-api/swagger-core/wiki) from a remote server, you can easily generate a server stub. This -is an example of building a swagger-enabled JAX-RS server. +This server was generated by the [OpenAPI Generator](https://openapi-generator.tech) project. By using an +[OpenAPI-Spec](https://openapis.org), you can easily generate a server stub. +This is an example of building a OpenAPI-enabled JAX-RS server. This example uses the [JAX-RS](https://jax-rs-spec.java.net/) framework. +Jersey is used as JAX-RS implementation, `io.swagger:swagger-jersey2-jaxrs` is used to derive the OpenAPI Specification from the annotated code. To run the server, please execute the following: @@ -13,10 +14,10 @@ To run the server, please execute the following: mvn clean package jetty:run ``` -You can then view the swagger listing here: +You can then view the OpenAPI v2 specification here: ``` -http://localhost:8082/v2/openapi.json +http://localhost:8082/v2/swagger.json ``` Note that if you have configured the `host` to be something other than localhost, the calls through diff --git a/samples/server/petstore/kotlin-springboot/.openapi-generator-ignore b/samples/server/petstore/kotlin-springboot/.openapi-generator-ignore new file mode 100644 index 0000000000..7484ee590a --- /dev/null +++ b/samples/server/petstore/kotlin-springboot/.openapi-generator-ignore @@ -0,0 +1,23 @@ +# OpenAPI Generator Ignore +# Generated by openapi-generator https://github.com/openapitools/openapi-generator + +# Use this file to prevent files from being overwritten by the generator. +# The patterns follow closely to .gitignore or .dockerignore. + +# As an example, the C# client generator defines ApiClient.cs. +# You can make changes and tell OpenAPI Generator to ignore just this file by uncommenting the following line: +#ApiClient.cs + +# You can match any string of characters against a directory, file or extension with a single asterisk (*): +#foo/*/qux +# The above matches foo/bar/qux and foo/baz/qux, but not foo/bar/baz/qux + +# You can recursively match patterns against a directory, file or extension with a double asterisk (**): +#foo/**/qux +# This matches foo/bar/qux, foo/baz/qux, and foo/bar/baz/qux + +# You can also negate patterns with an exclamation (!). +# For example, you can ignore all files in a docs folder with the file extension .md: +#docs/*.md +# Then explicitly reverse the ignore rule for a single file: +#!docs/README.md diff --git a/samples/server/petstore/kotlin-springboot/.openapi-generator/VERSION b/samples/server/petstore/kotlin-springboot/.openapi-generator/VERSION new file mode 100644 index 0000000000..c791c986fb --- /dev/null +++ b/samples/server/petstore/kotlin-springboot/.openapi-generator/VERSION @@ -0,0 +1 @@ +3.2.3-SNAPSHOT \ No newline at end of file diff --git a/samples/server/petstore/kotlin-springboot/README.md b/samples/server/petstore/kotlin-springboot/README.md new file mode 100644 index 0000000000..b6865a0811 --- /dev/null +++ b/samples/server/petstore/kotlin-springboot/README.md @@ -0,0 +1,21 @@ +# openAPIPetstore + +This Kotlin based [Spring Boot](https://spring.io/projects/spring-boot) application has been generated using the [OpenAPI Generator](https://github.com/OpenAPITools/openapi-generator). + +## Getting Started + +This document assumes you have either maven or gradle available, either via the wrapper or otherwise. This does not come with a gradle / maven wrapper checked in. + +By default a [`pom.xml`](pom.xml) file will be generated. If you specified `gradleBuildFile=true` when generating this project, a `build.gradle.kts` will also be generated. Note this uses [Gradle Kotlin DSL](https://github.com/gradle/kotlin-dsl). + +To build the project using maven, run: +```bash +mvn package && java -jar target/openapi-spring-1.0.0.jar +``` + +To build the project using gradle, run: +```bash +gradle build && java -jar build/libs/openapi-spring-1.0.0.jar +``` + +If all builds successfully, the server should run on [http://localhost:8080/](http://localhost:8080/) diff --git a/samples/server/petstore/kotlin-springboot/build.gradle.kts b/samples/server/petstore/kotlin-springboot/build.gradle.kts new file mode 100644 index 0000000000..b5a8fef745 --- /dev/null +++ b/samples/server/petstore/kotlin-springboot/build.gradle.kts @@ -0,0 +1,45 @@ +import org.jetbrains.kotlin.gradle.tasks.KotlinCompile + +buildscript { + repositories { + jcenter() + mavenCentral() + } + dependencies { + classpath("org.springframework.boot:spring-boot-gradle-plugin:2.0.3.RELEASE") + } +} + +group = "org.openapitools" +version = "1.0.0" + +repositories { + jcenter() + mavenCentral() +} + +tasks.withType { + kotlinOptions.jvmTarget = "1.8" +} + +plugins { + val kotlinVersion = "1.2.60" + id("org.jetbrains.kotlin.jvm") version kotlinVersion + id("org.jetbrains.kotlin.plugin.jpa") version kotlinVersion + id("org.jetbrains.kotlin.plugin.spring") version kotlinVersion + id("org.springframework.boot") version "2.0.3.RELEASE" + id("io.spring.dependency-management") version "1.0.5.RELEASE" +} + +dependencies { + compile("org.jetbrains.kotlin:kotlin-stdlib-jdk8") + compile("org.jetbrains.kotlin:kotlin-reflect") + compile("org.springframework.boot:spring-boot-starter-web") + compile("io.swagger:swagger-annotations:1.5.21") + compile("com.fasterxml.jackson.dataformat:jackson-dataformat-yaml") + compile("com.fasterxml.jackson.dataformat:jackson-dataformat-xml") + + testCompile("org.springframework.boot:spring-boot-starter-test") { + exclude(module = "junit") + } +} diff --git a/samples/server/petstore/kotlin-springboot/pom.xml b/samples/server/petstore/kotlin-springboot/pom.xml new file mode 100644 index 0000000000..fb79c82cca --- /dev/null +++ b/samples/server/petstore/kotlin-springboot/pom.xml @@ -0,0 +1,105 @@ + + 4.0.0 + org.openapitools + openapi-spring + jar + openapi-spring + 1.0.0 + + 1.2.60 + + + org.springframework.boot + spring-boot-starter-parent + 2.0.3.RELEASE + + + ${project.basedir}/src/main/kotlin + ${project.basedir}/src/test/kotlin + + + org.springframework.boot + spring-boot-maven-plugin + + + + repackage + + + + + + kotlin-maven-plugin + org.jetbrains.kotlin + ${kotlin.version} + + + spring + + 1.8 + + + + compile + compile + + compile + + + + test-compile + test-compile + + test-compile + + + + + + org.jetbrains.kotlin + kotlin-maven-allopen + ${kotlin.version} + + + + + + + + org.jetbrains.kotlin + kotlin-stdlib-jdk8 + ${kotlin.version} + + + org.jetbrains.kotlin + kotlin-reflect + ${kotlin.version} + + + org.springframework.boot + spring-boot-starter-web + + + io.swagger + swagger-annotations + 1.5.21 + + + com.fasterxml.jackson.dataformat + jackson-dataformat-yaml + + + com.fasterxml.jackson.dataformat + jackson-dataformat-xml + + + com.fasterxml.jackson.datatype + jackson-datatype-jsr310 + + + + javax.validation + validation-api + + + diff --git a/samples/server/petstore/kotlin-springboot/settings.gradle b/samples/server/petstore/kotlin-springboot/settings.gradle new file mode 100644 index 0000000000..f0dd035311 --- /dev/null +++ b/samples/server/petstore/kotlin-springboot/settings.gradle @@ -0,0 +1 @@ +rootProject.name = "openapi-spring" \ No newline at end of file diff --git a/samples/server/petstore/kotlin-springboot/src/main/kotlin/org/openapitools/Application.kt b/samples/server/petstore/kotlin-springboot/src/main/kotlin/org/openapitools/Application.kt new file mode 100644 index 0000000000..f2ee49d476 --- /dev/null +++ b/samples/server/petstore/kotlin-springboot/src/main/kotlin/org/openapitools/Application.kt @@ -0,0 +1,14 @@ +package org.openapitools + +import org.springframework.boot.runApplication +import org.springframework.context.annotation.ComponentScan +import org.springframework.boot.autoconfigure.SpringBootApplication + + +@SpringBootApplication +@ComponentScan(basePackages = ["org.openapitools", "org.openapitools.api", "org.openapitools.model"]) +class Application + +fun main(args: Array) { + runApplication(*args) +} diff --git a/samples/server/petstore/kotlin-springboot/src/main/kotlin/org/openapitools/api/Exceptions.kt b/samples/server/petstore/kotlin-springboot/src/main/kotlin/org/openapitools/api/Exceptions.kt new file mode 100644 index 0000000000..4d8400902a --- /dev/null +++ b/samples/server/petstore/kotlin-springboot/src/main/kotlin/org/openapitools/api/Exceptions.kt @@ -0,0 +1,29 @@ +package org.openapitools.api + +import org.springframework.http.HttpStatus +import org.springframework.web.bind.annotation.ControllerAdvice +import org.springframework.web.bind.annotation.ExceptionHandler +import javax.servlet.http.HttpServletResponse +import javax.validation.ConstraintViolationException + +// TODO Extend ApiException for custom exception handling, e.g. the below NotFound exception +sealed class ApiException(msg: String, val code: Int) : Exception(msg) + +class NotFoundException(msg: String, code: Int = HttpStatus.NOT_FOUND.value()) : ApiException(msg, code) + + +@ControllerAdvice +class DefaultExceptionHandler { + + @ExceptionHandler(value = [ApiException::class]) + fun onApiException(ex: ApiException, response: HttpServletResponse): Unit = + response.sendError(ex.code, ex.message) + + @ExceptionHandler(value = [NotImplementedError::class]) + fun onNotImplemented(ex: NotImplementedError, response: HttpServletResponse): Unit = + response.sendError(HttpStatus.NOT_IMPLEMENTED.value()) + + @ExceptionHandler(value = [ConstraintViolationException::class]) + fun onConstraintViolation(ex: ConstraintViolationException, response: HttpServletResponse): Unit = + response.sendError(HttpStatus.BAD_REQUEST.value(), ex.constraintViolations.joinToString(", ") { it.message }) +} diff --git a/samples/server/petstore/kotlin-springboot/src/main/kotlin/org/openapitools/api/PetApi.kt b/samples/server/petstore/kotlin-springboot/src/main/kotlin/org/openapitools/api/PetApi.kt new file mode 100644 index 0000000000..05aee6becb --- /dev/null +++ b/samples/server/petstore/kotlin-springboot/src/main/kotlin/org/openapitools/api/PetApi.kt @@ -0,0 +1,159 @@ +package org.openapitools.api + +import org.openapitools.model.ModelApiResponse +import org.openapitools.model.Pet +import io.swagger.annotations.* +import org.springframework.http.HttpStatus +import org.springframework.http.MediaType +import org.springframework.http.ResponseEntity +import org.springframework.stereotype.Controller +import org.springframework.web.bind.annotation.RequestBody +import org.springframework.web.bind.annotation.RequestPart +import org.springframework.web.bind.annotation.RequestParam +import org.springframework.web.bind.annotation.PathVariable +import org.springframework.web.bind.annotation.RequestHeader +import org.springframework.web.bind.annotation.RequestMethod +import org.springframework.web.bind.annotation.RequestMapping +import org.springframework.validation.annotation.Validated +import org.springframework.web.context.request.NativeWebRequest +import org.springframework.web.multipart.MultipartFile +import org.springframework.beans.factory.annotation.Autowired + +import javax.validation.Valid +import javax.validation.constraints.* + +import kotlin.collections.List +import kotlin.collections.Map + +@Controller +@Validated +@Api(value = "Pet", description = "The Pet API") +@RequestMapping("\${openapi.openAPIPetstore.base-path:/v2}") +class PetApiController(@Autowired(required = true) val service: PetApiService) { + + @ApiOperation( + value = "Add a new pet to the store", + nickname = "addPet", + notes = "", + authorizations = [Authorization(value = "petstore_auth", scopes = [AuthorizationScope(scope = "write:pets", description = "modify pets in your account"), AuthorizationScope(scope = "read:pets", description = "read your pets")])]) + @ApiResponses( + value = [ApiResponse(code = 405, message = "Invalid input")]) + @RequestMapping( + value = ["/pet"], + consumes = ["application/json", "application/xml"], + method = [RequestMethod.POST]) + fun addPet(@ApiParam(value = "Pet object that needs to be added to the store" ,required=true ) @Valid @RequestBody pet: Pet): ResponseEntity { + return ResponseEntity(service.addPet(pet), HttpStatus.OK) + } + + @ApiOperation( + value = "Deletes a pet", + nickname = "deletePet", + notes = "", + authorizations = [Authorization(value = "petstore_auth", scopes = [AuthorizationScope(scope = "write:pets", description = "modify pets in your account"), AuthorizationScope(scope = "read:pets", description = "read your pets")])]) + @ApiResponses( + value = [ApiResponse(code = 400, message = "Invalid pet value")]) + @RequestMapping( + value = ["/pet/{petId}"], + method = [RequestMethod.DELETE]) + fun deletePet(@ApiParam(value = "Pet id to delete", required=true) @PathVariable("petId") petId: kotlin.Long,@ApiParam(value = "" ) @RequestHeader(value="api_key", required=false) apiKey: kotlin.String): ResponseEntity { + return ResponseEntity(service.deletePet(petId, apiKey), HttpStatus.OK) + } + + @ApiOperation( + value = "Finds Pets by status", + nickname = "findPetsByStatus", + notes = "Multiple status values can be provided with comma separated strings", + response = Pet::class, + responseContainer = "List", + authorizations = [Authorization(value = "petstore_auth", scopes = [AuthorizationScope(scope = "write:pets", description = "modify pets in your account"), AuthorizationScope(scope = "read:pets", description = "read your pets")])]) + @ApiResponses( + value = [ApiResponse(code = 200, message = "successful operation", response = Pet::class, responseContainer = "List"),ApiResponse(code = 400, message = "Invalid status value")]) + @RequestMapping( + value = ["/pet/findByStatus"], + produces = ["application/xml", "application/json"], + method = [RequestMethod.GET]) + fun findPetsByStatus(@NotNull @ApiParam(value = "Status values that need to be considered for filter", required = true, allowableValues = "available, pending, sold") @Valid @RequestParam(value = "status", required = true) status: kotlin.Array): ResponseEntity> { + return ResponseEntity(service.findPetsByStatus(status), HttpStatus.OK) + } + + @ApiOperation( + value = "Finds Pets by tags", + nickname = "findPetsByTags", + notes = "Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing.", + response = Pet::class, + responseContainer = "List", + authorizations = [Authorization(value = "petstore_auth", scopes = [AuthorizationScope(scope = "write:pets", description = "modify pets in your account"), AuthorizationScope(scope = "read:pets", description = "read your pets")])]) + @ApiResponses( + value = [ApiResponse(code = 200, message = "successful operation", response = Pet::class, responseContainer = "List"),ApiResponse(code = 400, message = "Invalid tag value")]) + @RequestMapping( + value = ["/pet/findByTags"], + produces = ["application/xml", "application/json"], + method = [RequestMethod.GET]) + fun findPetsByTags(@NotNull @ApiParam(value = "Tags to filter by", required = true) @Valid @RequestParam(value = "tags", required = true) tags: kotlin.Array): ResponseEntity> { + return ResponseEntity(service.findPetsByTags(tags), HttpStatus.OK) + } + + @ApiOperation( + value = "Find pet by ID", + nickname = "getPetById", + notes = "Returns a single pet", + response = Pet::class, + authorizations = [Authorization(value = "api_key")]) + @ApiResponses( + value = [ApiResponse(code = 200, message = "successful operation", response = Pet::class),ApiResponse(code = 400, message = "Invalid ID supplied"),ApiResponse(code = 404, message = "Pet not found")]) + @RequestMapping( + value = ["/pet/{petId}"], + produces = ["application/xml", "application/json"], + method = [RequestMethod.GET]) + fun getPetById(@ApiParam(value = "ID of pet to return", required=true) @PathVariable("petId") petId: kotlin.Long): ResponseEntity { + return ResponseEntity(service.getPetById(petId), HttpStatus.OK) + } + + @ApiOperation( + value = "Update an existing pet", + nickname = "updatePet", + notes = "", + authorizations = [Authorization(value = "petstore_auth", scopes = [AuthorizationScope(scope = "write:pets", description = "modify pets in your account"), AuthorizationScope(scope = "read:pets", description = "read your pets")])]) + @ApiResponses( + value = [ApiResponse(code = 400, message = "Invalid ID supplied"),ApiResponse(code = 404, message = "Pet not found"),ApiResponse(code = 405, message = "Validation exception")]) + @RequestMapping( + value = ["/pet"], + consumes = ["application/json", "application/xml"], + method = [RequestMethod.PUT]) + fun updatePet(@ApiParam(value = "Pet object that needs to be added to the store" ,required=true ) @Valid @RequestBody pet: Pet): ResponseEntity { + return ResponseEntity(service.updatePet(pet), HttpStatus.OK) + } + + @ApiOperation( + value = "Updates a pet in the store with form data", + nickname = "updatePetWithForm", + notes = "", + authorizations = [Authorization(value = "petstore_auth", scopes = [AuthorizationScope(scope = "write:pets", description = "modify pets in your account"), AuthorizationScope(scope = "read:pets", description = "read your pets")])]) + @ApiResponses( + value = [ApiResponse(code = 405, message = "Invalid input")]) + @RequestMapping( + value = ["/pet/{petId}"], + consumes = ["application/x-www-form-urlencoded"], + method = [RequestMethod.POST]) + fun updatePetWithForm(@ApiParam(value = "ID of pet that needs to be updated", required=true) @PathVariable("petId") petId: kotlin.Long,@ApiParam(value = "Updated name of the pet", defaultValue="null") @RequestParam(value="name", required=false) name: kotlin.String ,@ApiParam(value = "Updated status of the pet", defaultValue="null") @RequestParam(value="status", required=false) status: kotlin.String ): ResponseEntity { + return ResponseEntity(service.updatePetWithForm(petId, name, status), HttpStatus.OK) + } + + @ApiOperation( + value = "uploads an image", + nickname = "uploadFile", + notes = "", + response = ModelApiResponse::class, + authorizations = [Authorization(value = "petstore_auth", scopes = [AuthorizationScope(scope = "write:pets", description = "modify pets in your account"), AuthorizationScope(scope = "read:pets", description = "read your pets")])]) + @ApiResponses( + value = [ApiResponse(code = 200, message = "successful operation", response = ModelApiResponse::class)]) + @RequestMapping( + value = ["/pet/{petId}/uploadImage"], + produces = ["application/json"], + consumes = ["multipart/form-data"], + method = [RequestMethod.POST]) + fun uploadFile(@ApiParam(value = "ID of pet to update", required=true) @PathVariable("petId") petId: kotlin.Long,@ApiParam(value = "Additional data to pass to server", defaultValue="null") @RequestParam(value="additionalMetadata", required=false) additionalMetadata: kotlin.String ,@ApiParam(value = "file detail") @Valid @RequestPart("file") file: MultipartFile): ResponseEntity { + return ResponseEntity(service.uploadFile(petId, additionalMetadata, file), HttpStatus.OK) + } +} diff --git a/samples/server/petstore/kotlin-springboot/src/main/kotlin/org/openapitools/api/PetApiService.kt b/samples/server/petstore/kotlin-springboot/src/main/kotlin/org/openapitools/api/PetApiService.kt new file mode 100644 index 0000000000..e7bd7fae34 --- /dev/null +++ b/samples/server/petstore/kotlin-springboot/src/main/kotlin/org/openapitools/api/PetApiService.kt @@ -0,0 +1,23 @@ +package org.openapitools.api + +import org.openapitools.model.ModelApiResponse +import org.openapitools.model.Pet + +interface PetApiService { + + fun addPet(pet: Pet): Unit + + fun deletePet(petId: kotlin.Long,apiKey: kotlin.String): Unit + + fun findPetsByStatus(status: kotlin.Array): List + + fun findPetsByTags(tags: kotlin.Array): List + + fun getPetById(petId: kotlin.Long): Pet + + fun updatePet(pet: Pet): Unit + + fun updatePetWithForm(petId: kotlin.Long,name: kotlin.String,status: kotlin.String): Unit + + fun uploadFile(petId: kotlin.Long,additionalMetadata: kotlin.String,file: org.springframework.web.multipart.MultipartFile): ModelApiResponse +} diff --git a/samples/server/petstore/kotlin-springboot/src/main/kotlin/org/openapitools/api/PetApiServiceImpl.kt b/samples/server/petstore/kotlin-springboot/src/main/kotlin/org/openapitools/api/PetApiServiceImpl.kt new file mode 100644 index 0000000000..e898ab9892 --- /dev/null +++ b/samples/server/petstore/kotlin-springboot/src/main/kotlin/org/openapitools/api/PetApiServiceImpl.kt @@ -0,0 +1,41 @@ +package org.openapitools.api + +import org.openapitools.model.ModelApiResponse +import org.openapitools.model.Pet +import org.springframework.stereotype.Service + +@Service +class PetApiServiceImpl : PetApiService { + + override fun addPet(pet: Pet): Unit { + TODO("Implement me") + } + + override fun deletePet(petId: kotlin.Long,apiKey: kotlin.String): Unit { + TODO("Implement me") + } + + override fun findPetsByStatus(status: kotlin.Array): List { + TODO("Implement me") + } + + override fun findPetsByTags(tags: kotlin.Array): List { + TODO("Implement me") + } + + override fun getPetById(petId: kotlin.Long): Pet { + TODO("Implement me") + } + + override fun updatePet(pet: Pet): Unit { + TODO("Implement me") + } + + override fun updatePetWithForm(petId: kotlin.Long,name: kotlin.String,status: kotlin.String): Unit { + TODO("Implement me") + } + + override fun uploadFile(petId: kotlin.Long,additionalMetadata: kotlin.String,file: org.springframework.web.multipart.MultipartFile): ModelApiResponse { + TODO("Implement me") + } +} diff --git a/samples/server/petstore/kotlin-springboot/src/main/kotlin/org/openapitools/api/StoreApi.kt b/samples/server/petstore/kotlin-springboot/src/main/kotlin/org/openapitools/api/StoreApi.kt new file mode 100644 index 0000000000..fd682adb7c --- /dev/null +++ b/samples/server/petstore/kotlin-springboot/src/main/kotlin/org/openapitools/api/StoreApi.kt @@ -0,0 +1,92 @@ +package org.openapitools.api + +import org.openapitools.model.Order +import io.swagger.annotations.* +import org.springframework.http.HttpStatus +import org.springframework.http.MediaType +import org.springframework.http.ResponseEntity +import org.springframework.stereotype.Controller +import org.springframework.web.bind.annotation.RequestBody +import org.springframework.web.bind.annotation.RequestPart +import org.springframework.web.bind.annotation.RequestParam +import org.springframework.web.bind.annotation.PathVariable +import org.springframework.web.bind.annotation.RequestHeader +import org.springframework.web.bind.annotation.RequestMethod +import org.springframework.web.bind.annotation.RequestMapping +import org.springframework.validation.annotation.Validated +import org.springframework.web.context.request.NativeWebRequest +import org.springframework.web.multipart.MultipartFile +import org.springframework.beans.factory.annotation.Autowired + +import javax.validation.Valid +import javax.validation.constraints.* + +import kotlin.collections.List +import kotlin.collections.Map + +@Controller +@Validated +@Api(value = "Store", description = "The Store API") +@RequestMapping("\${openapi.openAPIPetstore.base-path:/v2}") +class StoreApiController(@Autowired(required = true) val service: StoreApiService) { + + @ApiOperation( + value = "Delete purchase order by ID", + nickname = "deleteOrder", + notes = "For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors") + @ApiResponses( + value = [ApiResponse(code = 400, message = "Invalid ID supplied"),ApiResponse(code = 404, message = "Order not found")]) + @RequestMapping( + value = ["/store/order/{orderId}"], + method = [RequestMethod.DELETE]) + fun deleteOrder(@ApiParam(value = "ID of the order that needs to be deleted", required=true) @PathVariable("orderId") orderId: kotlin.String): ResponseEntity { + return ResponseEntity(service.deleteOrder(orderId), HttpStatus.OK) + } + + @ApiOperation( + value = "Returns pet inventories by status", + nickname = "getInventory", + notes = "Returns a map of status codes to quantities", + response = kotlin.Int::class, + responseContainer = "Map", + authorizations = [Authorization(value = "api_key")]) + @ApiResponses( + value = [ApiResponse(code = 200, message = "successful operation", response = kotlin.collections.Map::class, responseContainer = "Map")]) + @RequestMapping( + value = ["/store/inventory"], + produces = ["application/json"], + method = [RequestMethod.GET]) + fun getInventory(): ResponseEntity> { + return ResponseEntity(service.getInventory(), HttpStatus.OK) + } + + @ApiOperation( + value = "Find purchase order by ID", + nickname = "getOrderById", + notes = "For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions", + response = Order::class) + @ApiResponses( + value = [ApiResponse(code = 200, message = "successful operation", response = Order::class),ApiResponse(code = 400, message = "Invalid ID supplied"),ApiResponse(code = 404, message = "Order not found")]) + @RequestMapping( + value = ["/store/order/{orderId}"], + produces = ["application/xml", "application/json"], + method = [RequestMethod.GET]) + fun getOrderById(@Min(1L) @Max(5L) @ApiParam(value = "ID of pet that needs to be fetched", required=true) @PathVariable("orderId") orderId: kotlin.Long): ResponseEntity { + return ResponseEntity(service.getOrderById(orderId), HttpStatus.OK) + } + + @ApiOperation( + value = "Place an order for a pet", + nickname = "placeOrder", + notes = "", + response = Order::class) + @ApiResponses( + value = [ApiResponse(code = 200, message = "successful operation", response = Order::class),ApiResponse(code = 400, message = "Invalid Order")]) + @RequestMapping( + value = ["/store/order"], + produces = ["application/xml", "application/json"], + method = [RequestMethod.POST]) + fun placeOrder(@ApiParam(value = "order placed for purchasing the pet" ,required=true ) @Valid @RequestBody order: Order): ResponseEntity { + return ResponseEntity(service.placeOrder(order), HttpStatus.OK) + } +} diff --git a/samples/server/petstore/kotlin-springboot/src/main/kotlin/org/openapitools/api/StoreApiService.kt b/samples/server/petstore/kotlin-springboot/src/main/kotlin/org/openapitools/api/StoreApiService.kt new file mode 100644 index 0000000000..5eb379cb18 --- /dev/null +++ b/samples/server/petstore/kotlin-springboot/src/main/kotlin/org/openapitools/api/StoreApiService.kt @@ -0,0 +1,14 @@ +package org.openapitools.api + +import org.openapitools.model.Order + +interface StoreApiService { + + fun deleteOrder(orderId: kotlin.String): Unit + + fun getInventory(): Map + + fun getOrderById(orderId: kotlin.Long): Order + + fun placeOrder(order: Order): Order +} diff --git a/samples/server/petstore/kotlin-springboot/src/main/kotlin/org/openapitools/api/StoreApiServiceImpl.kt b/samples/server/petstore/kotlin-springboot/src/main/kotlin/org/openapitools/api/StoreApiServiceImpl.kt new file mode 100644 index 0000000000..87d2551740 --- /dev/null +++ b/samples/server/petstore/kotlin-springboot/src/main/kotlin/org/openapitools/api/StoreApiServiceImpl.kt @@ -0,0 +1,24 @@ +package org.openapitools.api + +import org.openapitools.model.Order +import org.springframework.stereotype.Service + +@Service +class StoreApiServiceImpl : StoreApiService { + + override fun deleteOrder(orderId: kotlin.String): Unit { + TODO("Implement me") + } + + override fun getInventory(): Map { + TODO("Implement me") + } + + override fun getOrderById(orderId: kotlin.Long): Order { + TODO("Implement me") + } + + override fun placeOrder(order: Order): Order { + TODO("Implement me") + } +} diff --git a/samples/server/petstore/kotlin-springboot/src/main/kotlin/org/openapitools/api/UserApi.kt b/samples/server/petstore/kotlin-springboot/src/main/kotlin/org/openapitools/api/UserApi.kt new file mode 100644 index 0000000000..cc275f82f4 --- /dev/null +++ b/samples/server/petstore/kotlin-springboot/src/main/kotlin/org/openapitools/api/UserApi.kt @@ -0,0 +1,140 @@ +package org.openapitools.api + +import org.openapitools.model.User +import io.swagger.annotations.* +import org.springframework.http.HttpStatus +import org.springframework.http.MediaType +import org.springframework.http.ResponseEntity +import org.springframework.stereotype.Controller +import org.springframework.web.bind.annotation.RequestBody +import org.springframework.web.bind.annotation.RequestPart +import org.springframework.web.bind.annotation.RequestParam +import org.springframework.web.bind.annotation.PathVariable +import org.springframework.web.bind.annotation.RequestHeader +import org.springframework.web.bind.annotation.RequestMethod +import org.springframework.web.bind.annotation.RequestMapping +import org.springframework.validation.annotation.Validated +import org.springframework.web.context.request.NativeWebRequest +import org.springframework.web.multipart.MultipartFile +import org.springframework.beans.factory.annotation.Autowired + +import javax.validation.Valid +import javax.validation.constraints.* + +import kotlin.collections.List +import kotlin.collections.Map + +@Controller +@Validated +@Api(value = "User", description = "The User API") +@RequestMapping("\${openapi.openAPIPetstore.base-path:/v2}") +class UserApiController(@Autowired(required = true) val service: UserApiService) { + + @ApiOperation( + value = "Create user", + nickname = "createUser", + notes = "This can only be done by the logged in user.") + @ApiResponses( + value = [ApiResponse(code = 200, message = "successful operation")]) + @RequestMapping( + value = ["/user"], + method = [RequestMethod.POST]) + fun createUser(@ApiParam(value = "Created user object" ,required=true ) @Valid @RequestBody user: User): ResponseEntity { + return ResponseEntity(service.createUser(user), HttpStatus.OK) + } + + @ApiOperation( + value = "Creates list of users with given input array", + nickname = "createUsersWithArrayInput", + notes = "") + @ApiResponses( + value = [ApiResponse(code = 200, message = "successful operation")]) + @RequestMapping( + value = ["/user/createWithArray"], + method = [RequestMethod.POST]) + fun createUsersWithArrayInput(@ApiParam(value = "List of user object" ,required=true ) @Valid @RequestBody user: kotlin.Array): ResponseEntity { + return ResponseEntity(service.createUsersWithArrayInput(user), HttpStatus.OK) + } + + @ApiOperation( + value = "Creates list of users with given input array", + nickname = "createUsersWithListInput", + notes = "") + @ApiResponses( + value = [ApiResponse(code = 200, message = "successful operation")]) + @RequestMapping( + value = ["/user/createWithList"], + method = [RequestMethod.POST]) + fun createUsersWithListInput(@ApiParam(value = "List of user object" ,required=true ) @Valid @RequestBody user: kotlin.Array): ResponseEntity { + return ResponseEntity(service.createUsersWithListInput(user), HttpStatus.OK) + } + + @ApiOperation( + value = "Delete user", + nickname = "deleteUser", + notes = "This can only be done by the logged in user.") + @ApiResponses( + value = [ApiResponse(code = 400, message = "Invalid username supplied"),ApiResponse(code = 404, message = "User not found")]) + @RequestMapping( + value = ["/user/{username}"], + method = [RequestMethod.DELETE]) + fun deleteUser(@ApiParam(value = "The name that needs to be deleted", required=true) @PathVariable("username") username: kotlin.String): ResponseEntity { + return ResponseEntity(service.deleteUser(username), HttpStatus.OK) + } + + @ApiOperation( + value = "Get user by user name", + nickname = "getUserByName", + notes = "", + response = User::class) + @ApiResponses( + value = [ApiResponse(code = 200, message = "successful operation", response = User::class),ApiResponse(code = 400, message = "Invalid username supplied"),ApiResponse(code = 404, message = "User not found")]) + @RequestMapping( + value = ["/user/{username}"], + produces = ["application/xml", "application/json"], + method = [RequestMethod.GET]) + fun getUserByName(@ApiParam(value = "The name that needs to be fetched. Use user1 for testing.", required=true) @PathVariable("username") username: kotlin.String): ResponseEntity { + return ResponseEntity(service.getUserByName(username), HttpStatus.OK) + } + + @ApiOperation( + value = "Logs user into the system", + nickname = "loginUser", + notes = "", + response = kotlin.String::class) + @ApiResponses( + value = [ApiResponse(code = 200, message = "successful operation", response = kotlin.String::class),ApiResponse(code = 400, message = "Invalid username/password supplied")]) + @RequestMapping( + value = ["/user/login"], + produces = ["application/xml", "application/json"], + method = [RequestMethod.GET]) + fun loginUser(@NotNull @ApiParam(value = "The user name for login", required = true) @Valid @RequestParam(value = "username", required = true) username: kotlin.String,@NotNull @ApiParam(value = "The password for login in clear text", required = true) @Valid @RequestParam(value = "password", required = true) password: kotlin.String): ResponseEntity { + return ResponseEntity(service.loginUser(username, password), HttpStatus.OK) + } + + @ApiOperation( + value = "Logs out current logged in user session", + nickname = "logoutUser", + notes = "") + @ApiResponses( + value = [ApiResponse(code = 200, message = "successful operation")]) + @RequestMapping( + value = ["/user/logout"], + method = [RequestMethod.GET]) + fun logoutUser(): ResponseEntity { + return ResponseEntity(service.logoutUser(), HttpStatus.OK) + } + + @ApiOperation( + value = "Updated user", + nickname = "updateUser", + notes = "This can only be done by the logged in user.") + @ApiResponses( + value = [ApiResponse(code = 400, message = "Invalid user supplied"),ApiResponse(code = 404, message = "User not found")]) + @RequestMapping( + value = ["/user/{username}"], + method = [RequestMethod.PUT]) + fun updateUser(@ApiParam(value = "name that need to be deleted", required=true) @PathVariable("username") username: kotlin.String,@ApiParam(value = "Updated user object" ,required=true ) @Valid @RequestBody user: User): ResponseEntity { + return ResponseEntity(service.updateUser(username, user), HttpStatus.OK) + } +} diff --git a/samples/server/petstore/kotlin-springboot/src/main/kotlin/org/openapitools/api/UserApiService.kt b/samples/server/petstore/kotlin-springboot/src/main/kotlin/org/openapitools/api/UserApiService.kt new file mode 100644 index 0000000000..4b913ace3d --- /dev/null +++ b/samples/server/petstore/kotlin-springboot/src/main/kotlin/org/openapitools/api/UserApiService.kt @@ -0,0 +1,22 @@ +package org.openapitools.api + +import org.openapitools.model.User + +interface UserApiService { + + fun createUser(user: User): Unit + + fun createUsersWithArrayInput(user: kotlin.Array): Unit + + fun createUsersWithListInput(user: kotlin.Array): Unit + + fun deleteUser(username: kotlin.String): Unit + + fun getUserByName(username: kotlin.String): User + + fun loginUser(username: kotlin.String,password: kotlin.String): kotlin.String + + fun logoutUser(): Unit + + fun updateUser(username: kotlin.String,user: User): Unit +} diff --git a/samples/server/petstore/kotlin-springboot/src/main/kotlin/org/openapitools/api/UserApiServiceImpl.kt b/samples/server/petstore/kotlin-springboot/src/main/kotlin/org/openapitools/api/UserApiServiceImpl.kt new file mode 100644 index 0000000000..9600f60768 --- /dev/null +++ b/samples/server/petstore/kotlin-springboot/src/main/kotlin/org/openapitools/api/UserApiServiceImpl.kt @@ -0,0 +1,40 @@ +package org.openapitools.api + +import org.openapitools.model.User +import org.springframework.stereotype.Service + +@Service +class UserApiServiceImpl : UserApiService { + + override fun createUser(user: User): Unit { + TODO("Implement me") + } + + override fun createUsersWithArrayInput(user: kotlin.Array): Unit { + TODO("Implement me") + } + + override fun createUsersWithListInput(user: kotlin.Array): Unit { + TODO("Implement me") + } + + override fun deleteUser(username: kotlin.String): Unit { + TODO("Implement me") + } + + override fun getUserByName(username: kotlin.String): User { + TODO("Implement me") + } + + override fun loginUser(username: kotlin.String,password: kotlin.String): kotlin.String { + TODO("Implement me") + } + + override fun logoutUser(): Unit { + TODO("Implement me") + } + + override fun updateUser(username: kotlin.String,user: User): Unit { + TODO("Implement me") + } +} diff --git a/samples/server/petstore/kotlin-springboot/src/main/kotlin/org/openapitools/model/Category.kt b/samples/server/petstore/kotlin-springboot/src/main/kotlin/org/openapitools/model/Category.kt new file mode 100644 index 0000000000..36d48aa093 --- /dev/null +++ b/samples/server/petstore/kotlin-springboot/src/main/kotlin/org/openapitools/model/Category.kt @@ -0,0 +1,24 @@ +package org.openapitools.model + +import java.util.Objects +import com.fasterxml.jackson.annotation.JsonProperty +import javax.validation.Valid +import javax.validation.constraints.* +import io.swagger.annotations.ApiModelProperty + +/** + * A category for a pet + * @param id + * @param name + */ +data class Category ( + + @ApiModelProperty(value = "") + @JsonProperty("id") val id: kotlin.Long? = null, + + @ApiModelProperty(value = "") + @JsonProperty("name") val name: kotlin.String? = null +) { + +} + diff --git a/samples/server/petstore/kotlin-springboot/src/main/kotlin/org/openapitools/model/ModelApiResponse.kt b/samples/server/petstore/kotlin-springboot/src/main/kotlin/org/openapitools/model/ModelApiResponse.kt new file mode 100644 index 0000000000..9a259e9baa --- /dev/null +++ b/samples/server/petstore/kotlin-springboot/src/main/kotlin/org/openapitools/model/ModelApiResponse.kt @@ -0,0 +1,28 @@ +package org.openapitools.model + +import java.util.Objects +import com.fasterxml.jackson.annotation.JsonProperty +import javax.validation.Valid +import javax.validation.constraints.* +import io.swagger.annotations.ApiModelProperty + +/** + * Describes the result of uploading an image resource + * @param code + * @param type + * @param message + */ +data class ModelApiResponse ( + + @ApiModelProperty(value = "") + @JsonProperty("code") val code: kotlin.Int? = null, + + @ApiModelProperty(value = "") + @JsonProperty("type") val type: kotlin.String? = null, + + @ApiModelProperty(value = "") + @JsonProperty("message") val message: kotlin.String? = null +) { + +} + diff --git a/samples/server/petstore/kotlin-springboot/src/main/kotlin/org/openapitools/model/Order.kt b/samples/server/petstore/kotlin-springboot/src/main/kotlin/org/openapitools/model/Order.kt new file mode 100644 index 0000000000..2a7a639a9c --- /dev/null +++ b/samples/server/petstore/kotlin-springboot/src/main/kotlin/org/openapitools/model/Order.kt @@ -0,0 +1,55 @@ +package org.openapitools.model + +import java.util.Objects +import com.fasterxml.jackson.annotation.JsonProperty +import com.fasterxml.jackson.annotation.JsonValue +import javax.validation.Valid +import javax.validation.constraints.* +import io.swagger.annotations.ApiModelProperty + +/** + * An order for a pets from the pet store + * @param id + * @param petId + * @param quantity + * @param shipDate + * @param status Order Status + * @param complete + */ +data class Order ( + + @ApiModelProperty(value = "") + @JsonProperty("id") val id: kotlin.Long? = null, + + @ApiModelProperty(value = "") + @JsonProperty("petId") val petId: kotlin.Long? = null, + + @ApiModelProperty(value = "") + @JsonProperty("quantity") val quantity: kotlin.Int? = null, + + @ApiModelProperty(value = "") + @JsonProperty("shipDate") val shipDate: java.time.OffsetDateTime? = null, + + @ApiModelProperty(value = "Order Status") + @JsonProperty("status") val status: Order.Status? = null, + + @ApiModelProperty(value = "") + @JsonProperty("complete") val complete: kotlin.Boolean? = null +) { + + /** + * Order Status + * Values: placed,approved,delivered + */ + enum class Status(val value: kotlin.String) { + + @JsonProperty("placed") placed("placed"), + + @JsonProperty("approved") approved("approved"), + + @JsonProperty("delivered") delivered("delivered"); + + } + +} + diff --git a/samples/server/petstore/kotlin-springboot/src/main/kotlin/org/openapitools/model/Pet.kt b/samples/server/petstore/kotlin-springboot/src/main/kotlin/org/openapitools/model/Pet.kt new file mode 100644 index 0000000000..29665f1779 --- /dev/null +++ b/samples/server/petstore/kotlin-springboot/src/main/kotlin/org/openapitools/model/Pet.kt @@ -0,0 +1,59 @@ +package org.openapitools.model + +import java.util.Objects +import com.fasterxml.jackson.annotation.JsonProperty +import com.fasterxml.jackson.annotation.JsonValue +import org.openapitools.model.Category +import org.openapitools.model.Tag +import javax.validation.Valid +import javax.validation.constraints.* +import io.swagger.annotations.ApiModelProperty + +/** + * A pet for sale in the pet store + * @param id + * @param category + * @param name + * @param photoUrls + * @param tags + * @param status pet status in the store + */ +data class Pet ( + + @get:NotNull + @ApiModelProperty(example = "doggie", required = true, value = "") + @JsonProperty("name") val name: kotlin.String, + + @get:NotNull + @ApiModelProperty(required = true, value = "") + @JsonProperty("photoUrls") val photoUrls: kotlin.Array, + + @ApiModelProperty(value = "") + @JsonProperty("id") val id: kotlin.Long? = null, + + @ApiModelProperty(value = "") + @JsonProperty("category") val category: Category? = null, + + @ApiModelProperty(value = "") + @JsonProperty("tags") val tags: kotlin.Array? = null, + + @ApiModelProperty(value = "pet status in the store") + @JsonProperty("status") val status: Pet.Status? = null +) { + + /** + * pet status in the store + * Values: available,pending,sold + */ + enum class Status(val value: kotlin.String) { + + @JsonProperty("available") available("available"), + + @JsonProperty("pending") pending("pending"), + + @JsonProperty("sold") sold("sold"); + + } + +} + diff --git a/samples/server/petstore/kotlin-springboot/src/main/kotlin/org/openapitools/model/Tag.kt b/samples/server/petstore/kotlin-springboot/src/main/kotlin/org/openapitools/model/Tag.kt new file mode 100644 index 0000000000..76b362380b --- /dev/null +++ b/samples/server/petstore/kotlin-springboot/src/main/kotlin/org/openapitools/model/Tag.kt @@ -0,0 +1,24 @@ +package org.openapitools.model + +import java.util.Objects +import com.fasterxml.jackson.annotation.JsonProperty +import javax.validation.Valid +import javax.validation.constraints.* +import io.swagger.annotations.ApiModelProperty + +/** + * A tag for a pet + * @param id + * @param name + */ +data class Tag ( + + @ApiModelProperty(value = "") + @JsonProperty("id") val id: kotlin.Long? = null, + + @ApiModelProperty(value = "") + @JsonProperty("name") val name: kotlin.String? = null +) { + +} + diff --git a/samples/server/petstore/kotlin-springboot/src/main/kotlin/org/openapitools/model/User.kt b/samples/server/petstore/kotlin-springboot/src/main/kotlin/org/openapitools/model/User.kt new file mode 100644 index 0000000000..6ebdab0208 --- /dev/null +++ b/samples/server/petstore/kotlin-springboot/src/main/kotlin/org/openapitools/model/User.kt @@ -0,0 +1,48 @@ +package org.openapitools.model + +import java.util.Objects +import com.fasterxml.jackson.annotation.JsonProperty +import javax.validation.Valid +import javax.validation.constraints.* +import io.swagger.annotations.ApiModelProperty + +/** + * A User who is purchasing from the pet store + * @param id + * @param username + * @param firstName + * @param lastName + * @param email + * @param password + * @param phone + * @param userStatus User Status + */ +data class User ( + + @ApiModelProperty(value = "") + @JsonProperty("id") val id: kotlin.Long? = null, + + @ApiModelProperty(value = "") + @JsonProperty("username") val username: kotlin.String? = null, + + @ApiModelProperty(value = "") + @JsonProperty("firstName") val firstName: kotlin.String? = null, + + @ApiModelProperty(value = "") + @JsonProperty("lastName") val lastName: kotlin.String? = null, + + @ApiModelProperty(value = "") + @JsonProperty("email") val email: kotlin.String? = null, + + @ApiModelProperty(value = "") + @JsonProperty("password") val password: kotlin.String? = null, + + @ApiModelProperty(value = "") + @JsonProperty("phone") val phone: kotlin.String? = null, + + @ApiModelProperty(value = "User Status") + @JsonProperty("userStatus") val userStatus: kotlin.Int? = null +) { + +} + diff --git a/samples/server/petstore/kotlin-springboot/src/main/resources/application.yaml b/samples/server/petstore/kotlin-springboot/src/main/resources/application.yaml new file mode 100644 index 0000000000..366e320d52 --- /dev/null +++ b/samples/server/petstore/kotlin-springboot/src/main/resources/application.yaml @@ -0,0 +1,3 @@ +spring.application.name=openAPIPetstore +server.port=8080 +spring.jackson.serialization.WRITE_DATES_AS_TIMESTAMPS=false \ No newline at end of file diff --git a/samples/server/petstore/php-slim/README.md b/samples/server/petstore/php-slim/README.md index 85f8dfa980..bc52802744 100644 --- a/samples/server/petstore/php-slim/README.md +++ b/samples/server/petstore/php-slim/README.md @@ -30,15 +30,17 @@ $ php -S localhost:8888 -t php-slim-server ## Run tests -This package uses PHPUnit 4.8 for unit testing. +This package uses PHPUnit 4.8 for unit testing and PHP Codesniffer to check source code against user defined coding standard(`phpcsStandard` generator config option). [Test folder](test) contains templates which you can fill with real test assertions. How to write tests read at [PHPUnit Manual - Chapter 2. Writing Tests for PHPUnit](https://phpunit.de/manual/4.8/en/writing-tests-for-phpunit.html). +How to configure PHP CodeSniffer read at [PHP CodeSniffer Documentation](https://github.com/squizlabs/PHP_CodeSniffer/wiki). Command | Tool | Target ---- | ---- | ---- `$ composer test` | PHPUnit | All tests `$ composer run test-apis` | PHPUnit | Apis tests `$ composer run test-models` | PHPUnit | Models tests +`$ composer run phpcs` | PHP CodeSniffer | All files ## API Endpoints diff --git a/samples/server/petstore/php-slim/composer.json b/samples/server/petstore/php-slim/composer.json index ca19917902..166250643b 100644 --- a/samples/server/petstore/php-slim/composer.json +++ b/samples/server/petstore/php-slim/composer.json @@ -6,7 +6,8 @@ "tuupola/slim-basic-auth": "^3.0.0" }, "require-dev": { - "phpunit/phpunit": "^4.8" + "phpunit/phpunit": "^4.8", + "squizlabs/php_codesniffer": "^3.0" }, "autoload": { "psr-4": { "OpenAPIServer\\": "lib/" } @@ -20,6 +21,7 @@ "@test-models" ], "test-apis": "phpunit --testsuite Apis", - "test-models": "phpunit --testsuite Models" + "test-models": "phpunit --testsuite Models", + "phpcs": "phpcs ./ --ignore=vendor --warning-severity=0 --standard=PSR12" } } \ No newline at end of file diff --git a/samples/server/petstore/php-slim/lib/AbstractApiController.php b/samples/server/petstore/php-slim/lib/AbstractApiController.php index 7f1ee41419..9f20afc877 100644 --- a/samples/server/petstore/php-slim/lib/AbstractApiController.php +++ b/samples/server/petstore/php-slim/lib/AbstractApiController.php @@ -35,7 +35,8 @@ namespace OpenAPIServer; * @author OpenAPI Generator team * @link https://github.com/openapitools/openapi-generator */ -abstract class AbstractApiController { +abstract class AbstractApiController +{ /** * @var \Interop\Container\ContainerInterface Slim app container instance @@ -47,8 +48,8 @@ abstract class AbstractApiController { * * @param \Interop\Container\ContainerInterface $container Slim app container instance */ - public function __construct($container) { + public function __construct($container) + { $this->container = $container; } - } diff --git a/samples/server/petstore/php-slim/lib/Api/AnotherFakeApi.php b/samples/server/petstore/php-slim/lib/Api/AnotherFakeApi.php index ff108200b5..80b1a67e42 100644 --- a/samples/server/petstore/php-slim/lib/Api/AnotherFakeApi.php +++ b/samples/server/petstore/php-slim/lib/Api/AnotherFakeApi.php @@ -37,8 +37,9 @@ use OpenAPIServer\AbstractApiController; * @author OpenAPI Generator team * @link https://github.com/openapitools/openapi-generator */ -class AnotherFakeApi extends AbstractApiController { - +class AnotherFakeApi extends AbstractApiController +{ + /** * PATCH call123TestSpecialTags * Summary: To test special tags @@ -49,10 +50,10 @@ class AnotherFakeApi extends AbstractApiController { * @param \Psr\Http\Message\ResponseInterface $response Response * @param array|null $args Path arguments */ - public function call123TestSpecialTags($request, $response, $args) { + public function call123TestSpecialTags($request, $response, $args) + { $body = $request->getParsedBody(); $response->write('How about implementing call123TestSpecialTags as a PATCH method ?'); return $response; } - } diff --git a/samples/server/petstore/php-slim/lib/Api/FakeApi.php b/samples/server/petstore/php-slim/lib/Api/FakeApi.php index 2f8fee1349..3d69b510d0 100644 --- a/samples/server/petstore/php-slim/lib/Api/FakeApi.php +++ b/samples/server/petstore/php-slim/lib/Api/FakeApi.php @@ -37,11 +37,11 @@ use OpenAPIServer\AbstractApiController; * @author OpenAPI Generator team * @link https://github.com/openapitools/openapi-generator */ -class FakeApi extends AbstractApiController { - +class FakeApi extends AbstractApiController +{ + /** * POST fakeOuterBooleanSerialize - * Summary: * Notes: Test serialization of outer boolean types * Output-Formats: [*_/_*] * @@ -49,7 +49,8 @@ class FakeApi extends AbstractApiController { * @param \Psr\Http\Message\ResponseInterface $response Response * @param array|null $args Path arguments */ - public function fakeOuterBooleanSerialize($request, $response, $args) { + public function fakeOuterBooleanSerialize($request, $response, $args) + { $body = $request->getParsedBody(); $response->write('How about implementing fakeOuterBooleanSerialize as a POST method ?'); return $response; @@ -57,7 +58,6 @@ class FakeApi extends AbstractApiController { /** * POST fakeOuterCompositeSerialize - * Summary: * Notes: Test serialization of object with outer number type * Output-Formats: [*_/_*] * @@ -65,7 +65,8 @@ class FakeApi extends AbstractApiController { * @param \Psr\Http\Message\ResponseInterface $response Response * @param array|null $args Path arguments */ - public function fakeOuterCompositeSerialize($request, $response, $args) { + public function fakeOuterCompositeSerialize($request, $response, $args) + { $body = $request->getParsedBody(); $response->write('How about implementing fakeOuterCompositeSerialize as a POST method ?'); return $response; @@ -73,7 +74,6 @@ class FakeApi extends AbstractApiController { /** * POST fakeOuterNumberSerialize - * Summary: * Notes: Test serialization of outer number types * Output-Formats: [*_/_*] * @@ -81,7 +81,8 @@ class FakeApi extends AbstractApiController { * @param \Psr\Http\Message\ResponseInterface $response Response * @param array|null $args Path arguments */ - public function fakeOuterNumberSerialize($request, $response, $args) { + public function fakeOuterNumberSerialize($request, $response, $args) + { $body = $request->getParsedBody(); $response->write('How about implementing fakeOuterNumberSerialize as a POST method ?'); return $response; @@ -89,7 +90,6 @@ class FakeApi extends AbstractApiController { /** * POST fakeOuterStringSerialize - * Summary: * Notes: Test serialization of outer string types * Output-Formats: [*_/_*] * @@ -97,7 +97,8 @@ class FakeApi extends AbstractApiController { * @param \Psr\Http\Message\ResponseInterface $response Response * @param array|null $args Path arguments */ - public function fakeOuterStringSerialize($request, $response, $args) { + public function fakeOuterStringSerialize($request, $response, $args) + { $body = $request->getParsedBody(); $response->write('How about implementing fakeOuterStringSerialize as a POST method ?'); return $response; @@ -105,14 +106,14 @@ class FakeApi extends AbstractApiController { /** * PUT testBodyWithFileSchema - * Summary: * Notes: For this test, the body for this request much reference a schema named `File`. * * @param \Psr\Http\Message\ServerRequestInterface $request Request * @param \Psr\Http\Message\ResponseInterface $response Response * @param array|null $args Path arguments */ - public function testBodyWithFileSchema($request, $response, $args) { + public function testBodyWithFileSchema($request, $response, $args) + { $body = $request->getParsedBody(); $response->write('How about implementing testBodyWithFileSchema as a PUT method ?'); return $response; @@ -120,14 +121,13 @@ class FakeApi extends AbstractApiController { /** * PUT testBodyWithQueryParams - * Summary: - * Notes: * * @param \Psr\Http\Message\ServerRequestInterface $request Request * @param \Psr\Http\Message\ResponseInterface $response Response * @param array|null $args Path arguments */ - public function testBodyWithQueryParams($request, $response, $args) { + public function testBodyWithQueryParams($request, $response, $args) + { $queryParams = $request->getQueryParams(); $query = $request->getQueryParam('query'); $body = $request->getParsedBody(); @@ -145,7 +145,8 @@ class FakeApi extends AbstractApiController { * @param \Psr\Http\Message\ResponseInterface $response Response * @param array|null $args Path arguments */ - public function testClientModel($request, $response, $args) { + public function testClientModel($request, $response, $args) + { $body = $request->getParsedBody(); $response->write('How about implementing testClientModel as a PATCH method ?'); return $response; @@ -160,7 +161,8 @@ class FakeApi extends AbstractApiController { * @param \Psr\Http\Message\ResponseInterface $response Response * @param array|null $args Path arguments */ - public function testEndpointParameters($request, $response, $args) { + public function testEndpointParameters($request, $response, $args) + { $integer = $request->getParsedBodyParam('integer'); $int32 = $request->getParsedBodyParam('int32'); $int64 = $request->getParsedBodyParam('int64'); @@ -188,7 +190,8 @@ class FakeApi extends AbstractApiController { * @param \Psr\Http\Message\ResponseInterface $response Response * @param array|null $args Path arguments */ - public function testEnumParameters($request, $response, $args) { + public function testEnumParameters($request, $response, $args) + { $headers = $request->getHeaders(); $enumHeaderStringArray = $request->hasHeader('enum_header_string_array') ? $headers['enum_header_string_array'] : null; $enumHeaderString = $request->hasHeader('enum_header_string') ? $headers['enum_header_string'] : null; @@ -206,13 +209,13 @@ class FakeApi extends AbstractApiController { /** * POST testInlineAdditionalProperties * Summary: test inline additionalProperties - * Notes: * * @param \Psr\Http\Message\ServerRequestInterface $request Request * @param \Psr\Http\Message\ResponseInterface $response Response * @param array|null $args Path arguments */ - public function testInlineAdditionalProperties($request, $response, $args) { + public function testInlineAdditionalProperties($request, $response, $args) + { $body = $request->getParsedBody(); $response->write('How about implementing testInlineAdditionalProperties as a POST method ?'); return $response; @@ -221,17 +224,16 @@ class FakeApi extends AbstractApiController { /** * GET testJsonFormData * Summary: test json serialization of form data - * Notes: * * @param \Psr\Http\Message\ServerRequestInterface $request Request * @param \Psr\Http\Message\ResponseInterface $response Response * @param array|null $args Path arguments */ - public function testJsonFormData($request, $response, $args) { + public function testJsonFormData($request, $response, $args) + { $param = $request->getParsedBodyParam('param'); $param2 = $request->getParsedBodyParam('param2'); $response->write('How about implementing testJsonFormData as a GET method ?'); return $response; } - } diff --git a/samples/server/petstore/php-slim/lib/Api/FakeClassnameTags123Api.php b/samples/server/petstore/php-slim/lib/Api/FakeClassnameTags123Api.php index e824913c4e..a245034eaa 100644 --- a/samples/server/petstore/php-slim/lib/Api/FakeClassnameTags123Api.php +++ b/samples/server/petstore/php-slim/lib/Api/FakeClassnameTags123Api.php @@ -37,8 +37,9 @@ use OpenAPIServer\AbstractApiController; * @author OpenAPI Generator team * @link https://github.com/openapitools/openapi-generator */ -class FakeClassnameTags123Api extends AbstractApiController { - +class FakeClassnameTags123Api extends AbstractApiController +{ + /** * PATCH testClassname * Summary: To test class name in snake case @@ -49,10 +50,10 @@ class FakeClassnameTags123Api extends AbstractApiController { * @param \Psr\Http\Message\ResponseInterface $response Response * @param array|null $args Path arguments */ - public function testClassname($request, $response, $args) { + public function testClassname($request, $response, $args) + { $body = $request->getParsedBody(); $response->write('How about implementing testClassname as a PATCH method ?'); return $response; } - } diff --git a/samples/server/petstore/php-slim/lib/Api/PetApi.php b/samples/server/petstore/php-slim/lib/Api/PetApi.php index 7534dd9e48..b8ddd815a8 100644 --- a/samples/server/petstore/php-slim/lib/Api/PetApi.php +++ b/samples/server/petstore/php-slim/lib/Api/PetApi.php @@ -37,18 +37,19 @@ use OpenAPIServer\AbstractApiController; * @author OpenAPI Generator team * @link https://github.com/openapitools/openapi-generator */ -class PetApi extends AbstractApiController { - +class PetApi extends AbstractApiController +{ + /** * POST addPet * Summary: Add a new pet to the store - * Notes: * * @param \Psr\Http\Message\ServerRequestInterface $request Request * @param \Psr\Http\Message\ResponseInterface $response Response * @param array|null $args Path arguments */ - public function addPet($request, $response, $args) { + public function addPet($request, $response, $args) + { $body = $request->getParsedBody(); $response->write('How about implementing addPet as a POST method ?'); return $response; @@ -57,13 +58,13 @@ class PetApi extends AbstractApiController { /** * DELETE deletePet * Summary: Deletes a pet - * Notes: * * @param \Psr\Http\Message\ServerRequestInterface $request Request * @param \Psr\Http\Message\ResponseInterface $response Response * @param array|null $args Path arguments */ - public function deletePet($request, $response, $args) { + public function deletePet($request, $response, $args) + { $headers = $request->getHeaders(); $apiKey = $request->hasHeader('api_key') ? $headers['api_key'] : null; $petId = $args['petId']; @@ -81,7 +82,8 @@ class PetApi extends AbstractApiController { * @param \Psr\Http\Message\ResponseInterface $response Response * @param array|null $args Path arguments */ - public function findPetsByStatus($request, $response, $args) { + public function findPetsByStatus($request, $response, $args) + { $queryParams = $request->getQueryParams(); $status = $request->getQueryParam('status'); $response->write('How about implementing findPetsByStatus as a GET method ?'); @@ -98,7 +100,8 @@ class PetApi extends AbstractApiController { * @param \Psr\Http\Message\ResponseInterface $response Response * @param array|null $args Path arguments */ - public function findPetsByTags($request, $response, $args) { + public function findPetsByTags($request, $response, $args) + { $queryParams = $request->getQueryParams(); $tags = $request->getQueryParam('tags'); $response->write('How about implementing findPetsByTags as a GET method ?'); @@ -115,7 +118,8 @@ class PetApi extends AbstractApiController { * @param \Psr\Http\Message\ResponseInterface $response Response * @param array|null $args Path arguments */ - public function getPetById($request, $response, $args) { + public function getPetById($request, $response, $args) + { $petId = $args['petId']; $response->write('How about implementing getPetById as a GET method ?'); return $response; @@ -124,13 +128,13 @@ class PetApi extends AbstractApiController { /** * PUT updatePet * Summary: Update an existing pet - * Notes: * * @param \Psr\Http\Message\ServerRequestInterface $request Request * @param \Psr\Http\Message\ResponseInterface $response Response * @param array|null $args Path arguments */ - public function updatePet($request, $response, $args) { + public function updatePet($request, $response, $args) + { $body = $request->getParsedBody(); $response->write('How about implementing updatePet as a PUT method ?'); return $response; @@ -139,13 +143,13 @@ class PetApi extends AbstractApiController { /** * POST updatePetWithForm * Summary: Updates a pet in the store with form data - * Notes: * * @param \Psr\Http\Message\ServerRequestInterface $request Request * @param \Psr\Http\Message\ResponseInterface $response Response * @param array|null $args Path arguments */ - public function updatePetWithForm($request, $response, $args) { + public function updatePetWithForm($request, $response, $args) + { $petId = $args['petId']; $name = $request->getParsedBodyParam('name'); $status = $request->getParsedBodyParam('status'); @@ -156,14 +160,14 @@ class PetApi extends AbstractApiController { /** * POST uploadFile * Summary: uploads an image - * Notes: * Output-Formats: [application/json] * * @param \Psr\Http\Message\ServerRequestInterface $request Request * @param \Psr\Http\Message\ResponseInterface $response Response * @param array|null $args Path arguments */ - public function uploadFile($request, $response, $args) { + public function uploadFile($request, $response, $args) + { $petId = $args['petId']; $additionalMetadata = $request->getParsedBodyParam('additionalMetadata'); $file = (key_exists('file', $request->getUploadedFiles())) ? $request->getUploadedFiles()['file'] : null; @@ -174,19 +178,18 @@ class PetApi extends AbstractApiController { /** * POST uploadFileWithRequiredFile * Summary: uploads an image (required) - * Notes: * Output-Formats: [application/json] * * @param \Psr\Http\Message\ServerRequestInterface $request Request * @param \Psr\Http\Message\ResponseInterface $response Response * @param array|null $args Path arguments */ - public function uploadFileWithRequiredFile($request, $response, $args) { + public function uploadFileWithRequiredFile($request, $response, $args) + { $petId = $args['petId']; $additionalMetadata = $request->getParsedBodyParam('additionalMetadata'); $requiredFile = (key_exists('requiredFile', $request->getUploadedFiles())) ? $request->getUploadedFiles()['requiredFile'] : null; $response->write('How about implementing uploadFileWithRequiredFile as a POST method ?'); return $response; } - } diff --git a/samples/server/petstore/php-slim/lib/Api/StoreApi.php b/samples/server/petstore/php-slim/lib/Api/StoreApi.php index 181c66337e..8fcb48a411 100644 --- a/samples/server/petstore/php-slim/lib/Api/StoreApi.php +++ b/samples/server/petstore/php-slim/lib/Api/StoreApi.php @@ -37,8 +37,9 @@ use OpenAPIServer\AbstractApiController; * @author OpenAPI Generator team * @link https://github.com/openapitools/openapi-generator */ -class StoreApi extends AbstractApiController { - +class StoreApi extends AbstractApiController +{ + /** * DELETE deleteOrder * Summary: Delete purchase order by ID @@ -48,7 +49,8 @@ class StoreApi extends AbstractApiController { * @param \Psr\Http\Message\ResponseInterface $response Response * @param array|null $args Path arguments */ - public function deleteOrder($request, $response, $args) { + public function deleteOrder($request, $response, $args) + { $orderId = $args['order_id']; $response->write('How about implementing deleteOrder as a DELETE method ?'); return $response; @@ -64,7 +66,8 @@ class StoreApi extends AbstractApiController { * @param \Psr\Http\Message\ResponseInterface $response Response * @param array|null $args Path arguments */ - public function getInventory($request, $response, $args) { + public function getInventory($request, $response, $args) + { $response->write('How about implementing getInventory as a GET method ?'); return $response; } @@ -79,7 +82,8 @@ class StoreApi extends AbstractApiController { * @param \Psr\Http\Message\ResponseInterface $response Response * @param array|null $args Path arguments */ - public function getOrderById($request, $response, $args) { + public function getOrderById($request, $response, $args) + { $orderId = $args['order_id']; $response->write('How about implementing getOrderById as a GET method ?'); return $response; @@ -88,17 +92,16 @@ class StoreApi extends AbstractApiController { /** * POST placeOrder * Summary: Place an order for a pet - * Notes: * Output-Formats: [application/xml, application/json] * * @param \Psr\Http\Message\ServerRequestInterface $request Request * @param \Psr\Http\Message\ResponseInterface $response Response * @param array|null $args Path arguments */ - public function placeOrder($request, $response, $args) { + public function placeOrder($request, $response, $args) + { $body = $request->getParsedBody(); $response->write('How about implementing placeOrder as a POST method ?'); return $response; } - } diff --git a/samples/server/petstore/php-slim/lib/Api/UserApi.php b/samples/server/petstore/php-slim/lib/Api/UserApi.php index 4ba8c652b7..39d48b919f 100644 --- a/samples/server/petstore/php-slim/lib/Api/UserApi.php +++ b/samples/server/petstore/php-slim/lib/Api/UserApi.php @@ -37,8 +37,9 @@ use OpenAPIServer\AbstractApiController; * @author OpenAPI Generator team * @link https://github.com/openapitools/openapi-generator */ -class UserApi extends AbstractApiController { - +class UserApi extends AbstractApiController +{ + /** * POST createUser * Summary: Create user @@ -48,7 +49,8 @@ class UserApi extends AbstractApiController { * @param \Psr\Http\Message\ResponseInterface $response Response * @param array|null $args Path arguments */ - public function createUser($request, $response, $args) { + public function createUser($request, $response, $args) + { $body = $request->getParsedBody(); $response->write('How about implementing createUser as a POST method ?'); return $response; @@ -57,13 +59,13 @@ class UserApi extends AbstractApiController { /** * POST createUsersWithArrayInput * Summary: Creates list of users with given input array - * Notes: * * @param \Psr\Http\Message\ServerRequestInterface $request Request * @param \Psr\Http\Message\ResponseInterface $response Response * @param array|null $args Path arguments */ - public function createUsersWithArrayInput($request, $response, $args) { + public function createUsersWithArrayInput($request, $response, $args) + { $body = $request->getParsedBody(); $response->write('How about implementing createUsersWithArrayInput as a POST method ?'); return $response; @@ -72,13 +74,13 @@ class UserApi extends AbstractApiController { /** * POST createUsersWithListInput * Summary: Creates list of users with given input array - * Notes: * * @param \Psr\Http\Message\ServerRequestInterface $request Request * @param \Psr\Http\Message\ResponseInterface $response Response * @param array|null $args Path arguments */ - public function createUsersWithListInput($request, $response, $args) { + public function createUsersWithListInput($request, $response, $args) + { $body = $request->getParsedBody(); $response->write('How about implementing createUsersWithListInput as a POST method ?'); return $response; @@ -93,7 +95,8 @@ class UserApi extends AbstractApiController { * @param \Psr\Http\Message\ResponseInterface $response Response * @param array|null $args Path arguments */ - public function deleteUser($request, $response, $args) { + public function deleteUser($request, $response, $args) + { $username = $args['username']; $response->write('How about implementing deleteUser as a DELETE method ?'); return $response; @@ -102,14 +105,14 @@ class UserApi extends AbstractApiController { /** * GET getUserByName * Summary: Get user by user name - * Notes: * Output-Formats: [application/xml, application/json] * * @param \Psr\Http\Message\ServerRequestInterface $request Request * @param \Psr\Http\Message\ResponseInterface $response Response * @param array|null $args Path arguments */ - public function getUserByName($request, $response, $args) { + public function getUserByName($request, $response, $args) + { $username = $args['username']; $response->write('How about implementing getUserByName as a GET method ?'); return $response; @@ -118,14 +121,14 @@ class UserApi extends AbstractApiController { /** * GET loginUser * Summary: Logs user into the system - * Notes: * Output-Formats: [application/xml, application/json] * * @param \Psr\Http\Message\ServerRequestInterface $request Request * @param \Psr\Http\Message\ResponseInterface $response Response * @param array|null $args Path arguments */ - public function loginUser($request, $response, $args) { + public function loginUser($request, $response, $args) + { $queryParams = $request->getQueryParams(); $username = $request->getQueryParam('username'); $password = $request->getQueryParam('password'); @@ -136,13 +139,13 @@ class UserApi extends AbstractApiController { /** * GET logoutUser * Summary: Logs out current logged in user session - * Notes: * * @param \Psr\Http\Message\ServerRequestInterface $request Request * @param \Psr\Http\Message\ResponseInterface $response Response * @param array|null $args Path arguments */ - public function logoutUser($request, $response, $args) { + public function logoutUser($request, $response, $args) + { $response->write('How about implementing logoutUser as a GET method ?'); return $response; } @@ -156,11 +159,11 @@ class UserApi extends AbstractApiController { * @param \Psr\Http\Message\ResponseInterface $response Response * @param array|null $args Path arguments */ - public function updateUser($request, $response, $args) { + public function updateUser($request, $response, $args) + { $username = $args['username']; $body = $request->getParsedBody(); $response->write('How about implementing updateUser as a PUT method ?'); return $response; } - } diff --git a/samples/server/petstore/php-slim/lib/Model/AdditionalPropertiesClass.php b/samples/server/petstore/php-slim/lib/Model/AdditionalPropertiesClass.php index 460fd8573b..ee96953acb 100644 --- a/samples/server/petstore/php-slim/lib/Model/AdditionalPropertiesClass.php +++ b/samples/server/petstore/php-slim/lib/Model/AdditionalPropertiesClass.php @@ -7,12 +7,12 @@ namespace OpenAPIServer\Model; /** * AdditionalPropertiesClass */ -class AdditionalPropertiesClass { - +class AdditionalPropertiesClass +{ + /** @var map[string,string] $mapProperty */ private $mapProperty; - + /** @var map[string,map[string,string]] $mapOfMapProperty */ private $mapOfMapProperty; - } diff --git a/samples/server/petstore/php-slim/lib/Model/Animal.php b/samples/server/petstore/php-slim/lib/Model/Animal.php index d4c127fc75..b9bc8ea44b 100644 --- a/samples/server/petstore/php-slim/lib/Model/Animal.php +++ b/samples/server/petstore/php-slim/lib/Model/Animal.php @@ -7,12 +7,12 @@ namespace OpenAPIServer\Model; /** * Animal */ -class Animal { - +class Animal +{ + /** @var string $className */ private $className; - + /** @var string $color */ private $color; - } diff --git a/samples/server/petstore/php-slim/lib/Model/AnimalFarm.php b/samples/server/petstore/php-slim/lib/Model/AnimalFarm.php index 3d3e6bc018..36466e0181 100644 --- a/samples/server/petstore/php-slim/lib/Model/AnimalFarm.php +++ b/samples/server/petstore/php-slim/lib/Model/AnimalFarm.php @@ -7,6 +7,6 @@ namespace OpenAPIServer\Model; /** * AnimalFarm */ -class AnimalFarm { - +class AnimalFarm +{ } diff --git a/samples/server/petstore/php-slim/lib/Model/ApiResponse.php b/samples/server/petstore/php-slim/lib/Model/ApiResponse.php index fe48dcd69c..b6a7390c8b 100644 --- a/samples/server/petstore/php-slim/lib/Model/ApiResponse.php +++ b/samples/server/petstore/php-slim/lib/Model/ApiResponse.php @@ -7,15 +7,15 @@ namespace OpenAPIServer\Model; /** * ApiResponse */ -class ApiResponse { - +class ApiResponse +{ + /** @var int $code */ private $code; - + /** @var string $type */ private $type; - + /** @var string $message */ private $message; - } diff --git a/samples/server/petstore/php-slim/lib/Model/ArrayOfArrayOfNumberOnly.php b/samples/server/petstore/php-slim/lib/Model/ArrayOfArrayOfNumberOnly.php index 6040111252..1a9159e7ce 100644 --- a/samples/server/petstore/php-slim/lib/Model/ArrayOfArrayOfNumberOnly.php +++ b/samples/server/petstore/php-slim/lib/Model/ArrayOfArrayOfNumberOnly.php @@ -7,9 +7,9 @@ namespace OpenAPIServer\Model; /** * ArrayOfArrayOfNumberOnly */ -class ArrayOfArrayOfNumberOnly { - +class ArrayOfArrayOfNumberOnly +{ + /** @var float[][] $arrayArrayNumber */ private $arrayArrayNumber; - } diff --git a/samples/server/petstore/php-slim/lib/Model/ArrayOfNumberOnly.php b/samples/server/petstore/php-slim/lib/Model/ArrayOfNumberOnly.php index a3b2e76c22..33a08beb98 100644 --- a/samples/server/petstore/php-slim/lib/Model/ArrayOfNumberOnly.php +++ b/samples/server/petstore/php-slim/lib/Model/ArrayOfNumberOnly.php @@ -7,9 +7,9 @@ namespace OpenAPIServer\Model; /** * ArrayOfNumberOnly */ -class ArrayOfNumberOnly { - +class ArrayOfNumberOnly +{ + /** @var float[] $arrayNumber */ private $arrayNumber; - } diff --git a/samples/server/petstore/php-slim/lib/Model/ArrayTest.php b/samples/server/petstore/php-slim/lib/Model/ArrayTest.php index 08e8a8ea03..dfc5ac6c52 100644 --- a/samples/server/petstore/php-slim/lib/Model/ArrayTest.php +++ b/samples/server/petstore/php-slim/lib/Model/ArrayTest.php @@ -7,15 +7,15 @@ namespace OpenAPIServer\Model; /** * ArrayTest */ -class ArrayTest { - +class ArrayTest +{ + /** @var string[] $arrayOfString */ private $arrayOfString; - + /** @var int[][] $arrayArrayOfInteger */ private $arrayArrayOfInteger; - + /** @var \OpenAPIServer\Model\ReadOnlyFirst[][] $arrayArrayOfModel */ private $arrayArrayOfModel; - } diff --git a/samples/server/petstore/php-slim/lib/Model/Capitalization.php b/samples/server/petstore/php-slim/lib/Model/Capitalization.php index 8ea348bece..b31affec6a 100644 --- a/samples/server/petstore/php-slim/lib/Model/Capitalization.php +++ b/samples/server/petstore/php-slim/lib/Model/Capitalization.php @@ -7,24 +7,24 @@ namespace OpenAPIServer\Model; /** * Capitalization */ -class Capitalization { - +class Capitalization +{ + /** @var string $smallCamel */ private $smallCamel; - + /** @var string $capitalCamel */ private $capitalCamel; - + /** @var string $smallSnake */ private $smallSnake; - + /** @var string $capitalSnake */ private $capitalSnake; - + /** @var string $sCAETHFlowPoints */ private $sCAETHFlowPoints; - + /** @var string $aTTNAME Name of the pet*/ private $aTTNAME; - } diff --git a/samples/server/petstore/php-slim/lib/Model/Cat.php b/samples/server/petstore/php-slim/lib/Model/Cat.php index 072c86d1cb..9a800c0297 100644 --- a/samples/server/petstore/php-slim/lib/Model/Cat.php +++ b/samples/server/petstore/php-slim/lib/Model/Cat.php @@ -7,15 +7,15 @@ namespace OpenAPIServer\Model; /** * Cat */ -class Cat { - +class Cat +{ + /** @var string $className */ private $className; - + /** @var string $color */ private $color; - + /** @var bool $declawed */ private $declawed; - } diff --git a/samples/server/petstore/php-slim/lib/Model/Category.php b/samples/server/petstore/php-slim/lib/Model/Category.php index 92d49af1ba..9bed27a1f2 100644 --- a/samples/server/petstore/php-slim/lib/Model/Category.php +++ b/samples/server/petstore/php-slim/lib/Model/Category.php @@ -7,12 +7,12 @@ namespace OpenAPIServer\Model; /** * Category */ -class Category { - +class Category +{ + /** @var int $id */ private $id; - + /** @var string $name */ private $name; - } diff --git a/samples/server/petstore/php-slim/lib/Model/ClassModel.php b/samples/server/petstore/php-slim/lib/Model/ClassModel.php index 831e8afad4..43b08c7016 100644 --- a/samples/server/petstore/php-slim/lib/Model/ClassModel.php +++ b/samples/server/petstore/php-slim/lib/Model/ClassModel.php @@ -7,9 +7,9 @@ namespace OpenAPIServer\Model; /** * ClassModel */ -class ClassModel { - +class ClassModel +{ + /** @var string $class */ private $class; - } diff --git a/samples/server/petstore/php-slim/lib/Model/Client.php b/samples/server/petstore/php-slim/lib/Model/Client.php index 573a7f71b0..95ded593b9 100644 --- a/samples/server/petstore/php-slim/lib/Model/Client.php +++ b/samples/server/petstore/php-slim/lib/Model/Client.php @@ -7,9 +7,9 @@ namespace OpenAPIServer\Model; /** * Client */ -class Client { - +class Client +{ + /** @var string $client */ private $client; - } diff --git a/samples/server/petstore/php-slim/lib/Model/Dog.php b/samples/server/petstore/php-slim/lib/Model/Dog.php index cbb138e270..2af41c927e 100644 --- a/samples/server/petstore/php-slim/lib/Model/Dog.php +++ b/samples/server/petstore/php-slim/lib/Model/Dog.php @@ -7,15 +7,15 @@ namespace OpenAPIServer\Model; /** * Dog */ -class Dog { - +class Dog +{ + /** @var string $className */ private $className; - + /** @var string $color */ private $color; - + /** @var string $breed */ private $breed; - } diff --git a/samples/server/petstore/php-slim/lib/Model/EnumArrays.php b/samples/server/petstore/php-slim/lib/Model/EnumArrays.php index 420c603ff9..0683034c18 100644 --- a/samples/server/petstore/php-slim/lib/Model/EnumArrays.php +++ b/samples/server/petstore/php-slim/lib/Model/EnumArrays.php @@ -7,12 +7,12 @@ namespace OpenAPIServer\Model; /** * EnumArrays */ -class EnumArrays { - +class EnumArrays +{ + /** @var string $justSymbol */ private $justSymbol; - + /** @var string[] $arrayEnum */ private $arrayEnum; - } diff --git a/samples/server/petstore/php-slim/lib/Model/EnumClass.php b/samples/server/petstore/php-slim/lib/Model/EnumClass.php index b6ec1ac942..61cf77c95a 100644 --- a/samples/server/petstore/php-slim/lib/Model/EnumClass.php +++ b/samples/server/petstore/php-slim/lib/Model/EnumClass.php @@ -7,6 +7,6 @@ namespace OpenAPIServer\Model; /** * EnumClass */ -class EnumClass { - +class EnumClass +{ } diff --git a/samples/server/petstore/php-slim/lib/Model/EnumTest.php b/samples/server/petstore/php-slim/lib/Model/EnumTest.php index eef0cfb6aa..b4754610cf 100644 --- a/samples/server/petstore/php-slim/lib/Model/EnumTest.php +++ b/samples/server/petstore/php-slim/lib/Model/EnumTest.php @@ -7,21 +7,21 @@ namespace OpenAPIServer\Model; /** * EnumTest */ -class EnumTest { - +class EnumTest +{ + /** @var string $enumString */ private $enumString; - + /** @var string $enumStringRequired */ private $enumStringRequired; - + /** @var int $enumInteger */ private $enumInteger; - + /** @var double $enumNumber */ private $enumNumber; - + /** @var \OpenAPIServer\Model\OuterEnum $outerEnum */ private $outerEnum; - } diff --git a/samples/server/petstore/php-slim/lib/Model/File.php b/samples/server/petstore/php-slim/lib/Model/File.php index 8ad71447f8..18f242d8c2 100644 --- a/samples/server/petstore/php-slim/lib/Model/File.php +++ b/samples/server/petstore/php-slim/lib/Model/File.php @@ -7,9 +7,9 @@ namespace OpenAPIServer\Model; /** * File */ -class File { - +class File +{ + /** @var string $sourceURI Test capitalization*/ private $sourceURI; - } diff --git a/samples/server/petstore/php-slim/lib/Model/FileSchemaTestClass.php b/samples/server/petstore/php-slim/lib/Model/FileSchemaTestClass.php index fccee8b953..972d7a3efc 100644 --- a/samples/server/petstore/php-slim/lib/Model/FileSchemaTestClass.php +++ b/samples/server/petstore/php-slim/lib/Model/FileSchemaTestClass.php @@ -7,12 +7,12 @@ namespace OpenAPIServer\Model; /** * FileSchemaTestClass */ -class FileSchemaTestClass { - +class FileSchemaTestClass +{ + /** @var \OpenAPIServer\Model\File $file */ private $file; - + /** @var \OpenAPIServer\Model\File[] $files */ private $files; - } diff --git a/samples/server/petstore/php-slim/lib/Model/FormatTest.php b/samples/server/petstore/php-slim/lib/Model/FormatTest.php index c04cc766ab..878781c9d4 100644 --- a/samples/server/petstore/php-slim/lib/Model/FormatTest.php +++ b/samples/server/petstore/php-slim/lib/Model/FormatTest.php @@ -7,45 +7,45 @@ namespace OpenAPIServer\Model; /** * FormatTest */ -class FormatTest { - +class FormatTest +{ + /** @var int $integer */ private $integer; - + /** @var int $int32 */ private $int32; - + /** @var int $int64 */ private $int64; - + /** @var float $number */ private $number; - + /** @var float $float */ private $float; - + /** @var double $double */ private $double; - + /** @var string $string */ private $string; - + /** @var string $byte */ private $byte; - + /** @var \SplFileObject $binary */ private $binary; - + /** @var \DateTime $date */ private $date; - + /** @var \DateTime $dateTime */ private $dateTime; - + /** @var string $uuid */ private $uuid; - + /** @var string $password */ private $password; - } diff --git a/samples/server/petstore/php-slim/lib/Model/HasOnlyReadOnly.php b/samples/server/petstore/php-slim/lib/Model/HasOnlyReadOnly.php index de4638ac29..8403b53408 100644 --- a/samples/server/petstore/php-slim/lib/Model/HasOnlyReadOnly.php +++ b/samples/server/petstore/php-slim/lib/Model/HasOnlyReadOnly.php @@ -7,12 +7,12 @@ namespace OpenAPIServer\Model; /** * HasOnlyReadOnly */ -class HasOnlyReadOnly { - +class HasOnlyReadOnly +{ + /** @var string $bar */ private $bar; - + /** @var string $foo */ private $foo; - } diff --git a/samples/server/petstore/php-slim/lib/Model/MapTest.php b/samples/server/petstore/php-slim/lib/Model/MapTest.php index 58415e379e..4adc9d60f8 100644 --- a/samples/server/petstore/php-slim/lib/Model/MapTest.php +++ b/samples/server/petstore/php-slim/lib/Model/MapTest.php @@ -7,18 +7,18 @@ namespace OpenAPIServer\Model; /** * MapTest */ -class MapTest { - +class MapTest +{ + /** @var map[string,map[string,string]] $mapMapOfString */ private $mapMapOfString; - + /** @var map[string,string] $mapOfEnumString */ private $mapOfEnumString; - + /** @var map[string,bool] $directMap */ private $directMap; - + /** @var \OpenAPIServer\Model\StringBooleanMap $indirectMap */ private $indirectMap; - } diff --git a/samples/server/petstore/php-slim/lib/Model/MixedPropertiesAndAdditionalPropertiesClass.php b/samples/server/petstore/php-slim/lib/Model/MixedPropertiesAndAdditionalPropertiesClass.php index 077a355cc1..43fb017140 100644 --- a/samples/server/petstore/php-slim/lib/Model/MixedPropertiesAndAdditionalPropertiesClass.php +++ b/samples/server/petstore/php-slim/lib/Model/MixedPropertiesAndAdditionalPropertiesClass.php @@ -7,15 +7,15 @@ namespace OpenAPIServer\Model; /** * MixedPropertiesAndAdditionalPropertiesClass */ -class MixedPropertiesAndAdditionalPropertiesClass { - +class MixedPropertiesAndAdditionalPropertiesClass +{ + /** @var string $uuid */ private $uuid; - + /** @var \DateTime $dateTime */ private $dateTime; - + /** @var map[string,\OpenAPIServer\Model\Animal] $map */ private $map; - } diff --git a/samples/server/petstore/php-slim/lib/Model/Model200Response.php b/samples/server/petstore/php-slim/lib/Model/Model200Response.php index 404ceaad1b..8782c6a0f7 100644 --- a/samples/server/petstore/php-slim/lib/Model/Model200Response.php +++ b/samples/server/petstore/php-slim/lib/Model/Model200Response.php @@ -7,12 +7,12 @@ namespace OpenAPIServer\Model; /** * Model200Response */ -class Model200Response { - +class Model200Response +{ + /** @var int $name */ private $name; - + /** @var string $class */ private $class; - } diff --git a/samples/server/petstore/php-slim/lib/Model/ModelList.php b/samples/server/petstore/php-slim/lib/Model/ModelList.php index 8e668357a1..943c0d69a1 100644 --- a/samples/server/petstore/php-slim/lib/Model/ModelList.php +++ b/samples/server/petstore/php-slim/lib/Model/ModelList.php @@ -7,9 +7,9 @@ namespace OpenAPIServer\Model; /** * ModelList */ -class ModelList { - +class ModelList +{ + /** @var string $_123list */ private $_123list; - } diff --git a/samples/server/petstore/php-slim/lib/Model/ModelReturn.php b/samples/server/petstore/php-slim/lib/Model/ModelReturn.php index 5373aa2e7b..fdc6cbcf7a 100644 --- a/samples/server/petstore/php-slim/lib/Model/ModelReturn.php +++ b/samples/server/petstore/php-slim/lib/Model/ModelReturn.php @@ -7,9 +7,9 @@ namespace OpenAPIServer\Model; /** * ModelReturn */ -class ModelReturn { - +class ModelReturn +{ + /** @var int $return */ private $return; - } diff --git a/samples/server/petstore/php-slim/lib/Model/Name.php b/samples/server/petstore/php-slim/lib/Model/Name.php index 162aa21ebe..bcf2a71da7 100644 --- a/samples/server/petstore/php-slim/lib/Model/Name.php +++ b/samples/server/petstore/php-slim/lib/Model/Name.php @@ -7,18 +7,18 @@ namespace OpenAPIServer\Model; /** * Name */ -class Name { - +class Name +{ + /** @var int $name */ private $name; - + /** @var int $snakeCase */ private $snakeCase; - + /** @var string $property */ private $property; - + /** @var int $_123number */ private $_123number; - } diff --git a/samples/server/petstore/php-slim/lib/Model/NumberOnly.php b/samples/server/petstore/php-slim/lib/Model/NumberOnly.php index c725eb39fd..64d9350fc8 100644 --- a/samples/server/petstore/php-slim/lib/Model/NumberOnly.php +++ b/samples/server/petstore/php-slim/lib/Model/NumberOnly.php @@ -7,9 +7,9 @@ namespace OpenAPIServer\Model; /** * NumberOnly */ -class NumberOnly { - +class NumberOnly +{ + /** @var float $justNumber */ private $justNumber; - } diff --git a/samples/server/petstore/php-slim/lib/Model/Order.php b/samples/server/petstore/php-slim/lib/Model/Order.php index 7295a384c8..16da927060 100644 --- a/samples/server/petstore/php-slim/lib/Model/Order.php +++ b/samples/server/petstore/php-slim/lib/Model/Order.php @@ -7,24 +7,24 @@ namespace OpenAPIServer\Model; /** * Order */ -class Order { - +class Order +{ + /** @var int $id */ private $id; - + /** @var int $petId */ private $petId; - + /** @var int $quantity */ private $quantity; - + /** @var \DateTime $shipDate */ private $shipDate; - + /** @var string $status Order Status*/ private $status; - + /** @var bool $complete */ private $complete; - } diff --git a/samples/server/petstore/php-slim/lib/Model/OuterComposite.php b/samples/server/petstore/php-slim/lib/Model/OuterComposite.php index 522683f125..5521b8aec1 100644 --- a/samples/server/petstore/php-slim/lib/Model/OuterComposite.php +++ b/samples/server/petstore/php-slim/lib/Model/OuterComposite.php @@ -7,15 +7,15 @@ namespace OpenAPIServer\Model; /** * OuterComposite */ -class OuterComposite { - +class OuterComposite +{ + /** @var float $myNumber */ private $myNumber; - + /** @var string $myString */ private $myString; - + /** @var bool $myBoolean */ private $myBoolean; - } diff --git a/samples/server/petstore/php-slim/lib/Model/OuterEnum.php b/samples/server/petstore/php-slim/lib/Model/OuterEnum.php index bd529aca5e..793e29314a 100644 --- a/samples/server/petstore/php-slim/lib/Model/OuterEnum.php +++ b/samples/server/petstore/php-slim/lib/Model/OuterEnum.php @@ -7,6 +7,6 @@ namespace OpenAPIServer\Model; /** * OuterEnum */ -class OuterEnum { - +class OuterEnum +{ } diff --git a/samples/server/petstore/php-slim/lib/Model/Pet.php b/samples/server/petstore/php-slim/lib/Model/Pet.php index 6699506e33..a082a16bb0 100644 --- a/samples/server/petstore/php-slim/lib/Model/Pet.php +++ b/samples/server/petstore/php-slim/lib/Model/Pet.php @@ -7,24 +7,24 @@ namespace OpenAPIServer\Model; /** * Pet */ -class Pet { - +class Pet +{ + /** @var int $id */ private $id; - + /** @var \OpenAPIServer\Model\Category $category */ private $category; - + /** @var string $name */ private $name; - + /** @var string[] $photoUrls */ private $photoUrls; - + /** @var \OpenAPIServer\Model\Tag[] $tags */ private $tags; - + /** @var string $status pet status in the store*/ private $status; - } diff --git a/samples/server/petstore/php-slim/lib/Model/ReadOnlyFirst.php b/samples/server/petstore/php-slim/lib/Model/ReadOnlyFirst.php index 17ae0f6c98..c20d8105c2 100644 --- a/samples/server/petstore/php-slim/lib/Model/ReadOnlyFirst.php +++ b/samples/server/petstore/php-slim/lib/Model/ReadOnlyFirst.php @@ -7,12 +7,12 @@ namespace OpenAPIServer\Model; /** * ReadOnlyFirst */ -class ReadOnlyFirst { - +class ReadOnlyFirst +{ + /** @var string $bar */ private $bar; - + /** @var string $baz */ private $baz; - } diff --git a/samples/server/petstore/php-slim/lib/Model/SpecialModelName.php b/samples/server/petstore/php-slim/lib/Model/SpecialModelName.php index dd1d71ff4b..1ad7651e54 100644 --- a/samples/server/petstore/php-slim/lib/Model/SpecialModelName.php +++ b/samples/server/petstore/php-slim/lib/Model/SpecialModelName.php @@ -7,9 +7,9 @@ namespace OpenAPIServer\Model; /** * SpecialModelName */ -class SpecialModelName { - +class SpecialModelName +{ + /** @var int $specialPropertyName */ private $specialPropertyName; - } diff --git a/samples/server/petstore/php-slim/lib/Model/StringBooleanMap.php b/samples/server/petstore/php-slim/lib/Model/StringBooleanMap.php index 1164e1d707..5d50196896 100644 --- a/samples/server/petstore/php-slim/lib/Model/StringBooleanMap.php +++ b/samples/server/petstore/php-slim/lib/Model/StringBooleanMap.php @@ -7,6 +7,6 @@ namespace OpenAPIServer\Model; /** * StringBooleanMap */ -class StringBooleanMap { - +class StringBooleanMap +{ } diff --git a/samples/server/petstore/php-slim/lib/Model/Tag.php b/samples/server/petstore/php-slim/lib/Model/Tag.php index d4ff6fad5d..861b2f8503 100644 --- a/samples/server/petstore/php-slim/lib/Model/Tag.php +++ b/samples/server/petstore/php-slim/lib/Model/Tag.php @@ -7,12 +7,12 @@ namespace OpenAPIServer\Model; /** * Tag */ -class Tag { - +class Tag +{ + /** @var int $id */ private $id; - + /** @var string $name */ private $name; - } diff --git a/samples/server/petstore/php-slim/lib/Model/User.php b/samples/server/petstore/php-slim/lib/Model/User.php index c68813e5a5..1696c85a0b 100644 --- a/samples/server/petstore/php-slim/lib/Model/User.php +++ b/samples/server/petstore/php-slim/lib/Model/User.php @@ -7,30 +7,30 @@ namespace OpenAPIServer\Model; /** * User */ -class User { - +class User +{ + /** @var int $id */ private $id; - + /** @var string $username */ private $username; - + /** @var string $firstName */ private $firstName; - + /** @var string $lastName */ private $lastName; - + /** @var string $email */ private $email; - + /** @var string $password */ private $password; - + /** @var string $phone */ private $phone; - + /** @var int $userStatus User Status*/ private $userStatus; - } diff --git a/samples/server/petstore/php-slim/lib/SlimRouter.php b/samples/server/petstore/php-slim/lib/SlimRouter.php index 296e2964d8..ba105c7059 100644 --- a/samples/server/petstore/php-slim/lib/SlimRouter.php +++ b/samples/server/petstore/php-slim/lib/SlimRouter.php @@ -10,7 +10,7 @@ * @link https://github.com/openapitools/openapi-generator */ -/** +/** * 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: \" \\ @@ -46,7 +46,8 @@ use Tuupola\Middleware\HttpBasicAuthentication; * @author OpenAPI Generator team * @link https://github.com/openapitools/openapi-generator */ -class SlimRouter { +class SlimRouter +{ /** * @var $slimApp Slim\App instance @@ -59,7 +60,8 @@ class SlimRouter { * @param ContainerInterface|array $container Either a ContainerInterface or an associative array of app settings * @throws InvalidArgumentException when no container is provided that implements ContainerInterface */ - public function __construct($container = []) { + public function __construct($container = []) + { $app = new App($container); $basicAuth = new HttpBasicAuthentication([ @@ -72,108 +74,142 @@ class SlimRouter { ]); $app->PATCH( - '/v2/another-fake/dummy', AnotherFakeApi::class . ':call123TestSpecialTags' + '/v2/another-fake/dummy', + AnotherFakeApi::class . ':call123TestSpecialTags' ); $app->POST( - '/v2/fake/outer/boolean', FakeApi::class . ':fakeOuterBooleanSerialize' + '/v2/fake/outer/boolean', + FakeApi::class . ':fakeOuterBooleanSerialize' ); $app->POST( - '/v2/fake/outer/composite', FakeApi::class . ':fakeOuterCompositeSerialize' + '/v2/fake/outer/composite', + FakeApi::class . ':fakeOuterCompositeSerialize' ); $app->POST( - '/v2/fake/outer/number', FakeApi::class . ':fakeOuterNumberSerialize' + '/v2/fake/outer/number', + FakeApi::class . ':fakeOuterNumberSerialize' ); $app->POST( - '/v2/fake/outer/string', FakeApi::class . ':fakeOuterStringSerialize' + '/v2/fake/outer/string', + FakeApi::class . ':fakeOuterStringSerialize' ); $app->PUT( - '/v2/fake/body-with-file-schema', FakeApi::class . ':testBodyWithFileSchema' + '/v2/fake/body-with-file-schema', + FakeApi::class . ':testBodyWithFileSchema' ); $app->PUT( - '/v2/fake/body-with-query-params', FakeApi::class . ':testBodyWithQueryParams' + '/v2/fake/body-with-query-params', + FakeApi::class . ':testBodyWithQueryParams' ); $app->PATCH( - '/v2/fake', FakeApi::class . ':testClientModel' + '/v2/fake', + FakeApi::class . ':testClientModel' ); $app->POST( - '/v2/fake', FakeApi::class . ':testEndpointParameters' + '/v2/fake', + FakeApi::class . ':testEndpointParameters' )->add( $basicAuth ); $app->GET( - '/v2/fake', FakeApi::class . ':testEnumParameters' + '/v2/fake', + FakeApi::class . ':testEnumParameters' ); $app->POST( - '/v2/fake/inline-additionalProperties', FakeApi::class . ':testInlineAdditionalProperties' + '/v2/fake/inline-additionalProperties', + FakeApi::class . ':testInlineAdditionalProperties' ); $app->GET( - '/v2/fake/jsonFormData', FakeApi::class . ':testJsonFormData' + '/v2/fake/jsonFormData', + FakeApi::class . ':testJsonFormData' ); $app->PATCH( - '/v2/fake_classname_test', FakeClassnameTags123Api::class . ':testClassname' + '/v2/fake_classname_test', + FakeClassnameTags123Api::class . ':testClassname' ); $app->POST( - '/v2/pet', PetApi::class . ':addPet' + '/v2/pet', + PetApi::class . ':addPet' ); $app->GET( - '/v2/pet/findByStatus', PetApi::class . ':findPetsByStatus' + '/v2/pet/findByStatus', + PetApi::class . ':findPetsByStatus' ); $app->GET( - '/v2/pet/findByTags', PetApi::class . ':findPetsByTags' + '/v2/pet/findByTags', + PetApi::class . ':findPetsByTags' ); $app->PUT( - '/v2/pet', PetApi::class . ':updatePet' + '/v2/pet', + PetApi::class . ':updatePet' ); $app->DELETE( - '/v2/pet/{petId}', PetApi::class . ':deletePet' + '/v2/pet/{petId}', + PetApi::class . ':deletePet' ); $app->GET( - '/v2/pet/{petId}', PetApi::class . ':getPetById' + '/v2/pet/{petId}', + PetApi::class . ':getPetById' ); $app->POST( - '/v2/pet/{petId}', PetApi::class . ':updatePetWithForm' + '/v2/pet/{petId}', + PetApi::class . ':updatePetWithForm' ); $app->POST( - '/v2/pet/{petId}/uploadImage', PetApi::class . ':uploadFile' + '/v2/pet/{petId}/uploadImage', + PetApi::class . ':uploadFile' ); $app->POST( - '/v2/fake/{petId}/uploadImageWithRequiredFile', PetApi::class . ':uploadFileWithRequiredFile' + '/v2/fake/{petId}/uploadImageWithRequiredFile', + PetApi::class . ':uploadFileWithRequiredFile' ); $app->GET( - '/v2/store/inventory', StoreApi::class . ':getInventory' + '/v2/store/inventory', + StoreApi::class . ':getInventory' ); $app->POST( - '/v2/store/order', StoreApi::class . ':placeOrder' + '/v2/store/order', + StoreApi::class . ':placeOrder' ); $app->DELETE( - '/v2/store/order/{order_id}', StoreApi::class . ':deleteOrder' + '/v2/store/order/{order_id}', + StoreApi::class . ':deleteOrder' ); $app->GET( - '/v2/store/order/{order_id}', StoreApi::class . ':getOrderById' + '/v2/store/order/{order_id}', + StoreApi::class . ':getOrderById' ); $app->POST( - '/v2/user', UserApi::class . ':createUser' + '/v2/user', + UserApi::class . ':createUser' ); $app->POST( - '/v2/user/createWithArray', UserApi::class . ':createUsersWithArrayInput' + '/v2/user/createWithArray', + UserApi::class . ':createUsersWithArrayInput' ); $app->POST( - '/v2/user/createWithList', UserApi::class . ':createUsersWithListInput' + '/v2/user/createWithList', + UserApi::class . ':createUsersWithListInput' ); $app->GET( - '/v2/user/login', UserApi::class . ':loginUser' + '/v2/user/login', + UserApi::class . ':loginUser' ); $app->GET( - '/v2/user/logout', UserApi::class . ':logoutUser' + '/v2/user/logout', + UserApi::class . ':logoutUser' ); $app->DELETE( - '/v2/user/{username}', UserApi::class . ':deleteUser' + '/v2/user/{username}', + UserApi::class . ':deleteUser' ); $app->GET( - '/v2/user/{username}', UserApi::class . ':getUserByName' + '/v2/user/{username}', + UserApi::class . ':getUserByName' ); $app->PUT( - '/v2/user/{username}', UserApi::class . ':updateUser' + '/v2/user/{username}', + UserApi::class . ':updateUser' ); $this->slimApp = $app; @@ -183,7 +219,8 @@ class SlimRouter { * Returns Slim Framework instance * @return App */ - public function getSlimApp() { + public function getSlimApp() + { return $this->slimApp; } } diff --git a/samples/server/petstore/php-slim/test/Api/AnotherFakeApiTest.php b/samples/server/petstore/php-slim/test/Api/AnotherFakeApiTest.php index 06cd6fe39c..fc78f599d5 100644 --- a/samples/server/petstore/php-slim/test/Api/AnotherFakeApiTest.php +++ b/samples/server/petstore/php-slim/test/Api/AnotherFakeApiTest.php @@ -36,43 +36,44 @@ use OpenAPIServer\Api\AnotherFakeApi; * @link https://github.com/openapitools/openapi-generator * @coversDefaultClass \OpenAPIServer\Model\AnotherFakeApi */ -class AnotherFakeApiTest extends \PHPUnit_Framework_TestCase { +class AnotherFakeApiTest extends \PHPUnit_Framework_TestCase +{ /** * Setup before running any test cases */ - public static function setUpBeforeClass() { - + public static function setUpBeforeClass() + { } /** * Setup before running each test case */ - public function setUp() { - + public function setUp() + { } /** * Clean up after running each test case */ - public function tearDown() { - + public function tearDown() + { } /** * Clean up after running all test cases */ - public static function tearDownAfterClass() { - + public static function tearDownAfterClass() + { } /** - * Test case for testSpecialTags + * Test case for call123TestSpecialTags * * To test special tags. - * @covers ::testSpecialTags + * @covers ::call123TestSpecialTags */ - public function testTestSpecialTags() { - + public function testCall123TestSpecialTags() + { } } diff --git a/samples/server/petstore/php-slim/test/Api/FakeApiTest.php b/samples/server/petstore/php-slim/test/Api/FakeApiTest.php index f020953e05..c5f07d79f4 100644 --- a/samples/server/petstore/php-slim/test/Api/FakeApiTest.php +++ b/samples/server/petstore/php-slim/test/Api/FakeApiTest.php @@ -36,34 +36,35 @@ use OpenAPIServer\Api\FakeApi; * @link https://github.com/openapitools/openapi-generator * @coversDefaultClass \OpenAPIServer\Model\FakeApi */ -class FakeApiTest extends \PHPUnit_Framework_TestCase { +class FakeApiTest extends \PHPUnit_Framework_TestCase +{ /** * Setup before running any test cases */ - public static function setUpBeforeClass() { - + public static function setUpBeforeClass() + { } /** * Setup before running each test case */ - public function setUp() { - + public function setUp() + { } /** * Clean up after running each test case */ - public function tearDown() { - + public function tearDown() + { } /** * Clean up after running all test cases */ - public static function tearDownAfterClass() { - + public static function tearDownAfterClass() + { } /** @@ -72,8 +73,8 @@ class FakeApiTest extends \PHPUnit_Framework_TestCase { * . * @covers ::fakeOuterBooleanSerialize */ - public function testFakeOuterBooleanSerialize() { - + public function testFakeOuterBooleanSerialize() + { } /** @@ -82,8 +83,8 @@ class FakeApiTest extends \PHPUnit_Framework_TestCase { * . * @covers ::fakeOuterCompositeSerialize */ - public function testFakeOuterCompositeSerialize() { - + public function testFakeOuterCompositeSerialize() + { } /** @@ -92,8 +93,8 @@ class FakeApiTest extends \PHPUnit_Framework_TestCase { * . * @covers ::fakeOuterNumberSerialize */ - public function testFakeOuterNumberSerialize() { - + public function testFakeOuterNumberSerialize() + { } /** @@ -102,8 +103,8 @@ class FakeApiTest extends \PHPUnit_Framework_TestCase { * . * @covers ::fakeOuterStringSerialize */ - public function testFakeOuterStringSerialize() { - + public function testFakeOuterStringSerialize() + { } /** @@ -112,8 +113,8 @@ class FakeApiTest extends \PHPUnit_Framework_TestCase { * . * @covers ::testBodyWithFileSchema */ - public function testTestBodyWithFileSchema() { - + public function testTestBodyWithFileSchema() + { } /** @@ -122,8 +123,8 @@ class FakeApiTest extends \PHPUnit_Framework_TestCase { * . * @covers ::testBodyWithQueryParams */ - public function testTestBodyWithQueryParams() { - + public function testTestBodyWithQueryParams() + { } /** @@ -132,8 +133,8 @@ class FakeApiTest extends \PHPUnit_Framework_TestCase { * To test \"client\" model. * @covers ::testClientModel */ - public function testTestClientModel() { - + public function testTestClientModel() + { } /** @@ -142,8 +143,8 @@ class FakeApiTest extends \PHPUnit_Framework_TestCase { * Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트. * @covers ::testEndpointParameters */ - public function testTestEndpointParameters() { - + public function testTestEndpointParameters() + { } /** @@ -152,8 +153,8 @@ class FakeApiTest extends \PHPUnit_Framework_TestCase { * To test enum parameters. * @covers ::testEnumParameters */ - public function testTestEnumParameters() { - + public function testTestEnumParameters() + { } /** @@ -162,8 +163,8 @@ class FakeApiTest extends \PHPUnit_Framework_TestCase { * test inline additionalProperties. * @covers ::testInlineAdditionalProperties */ - public function testTestInlineAdditionalProperties() { - + public function testTestInlineAdditionalProperties() + { } /** @@ -172,7 +173,7 @@ class FakeApiTest extends \PHPUnit_Framework_TestCase { * test json serialization of form data. * @covers ::testJsonFormData */ - public function testTestJsonFormData() { - + public function testTestJsonFormData() + { } } diff --git a/samples/server/petstore/php-slim/test/Api/FakeClassnameTags123ApiTest.php b/samples/server/petstore/php-slim/test/Api/FakeClassnameTags123ApiTest.php index de4105136e..e06689f428 100644 --- a/samples/server/petstore/php-slim/test/Api/FakeClassnameTags123ApiTest.php +++ b/samples/server/petstore/php-slim/test/Api/FakeClassnameTags123ApiTest.php @@ -36,34 +36,35 @@ use OpenAPIServer\Api\FakeClassnameTags123Api; * @link https://github.com/openapitools/openapi-generator * @coversDefaultClass \OpenAPIServer\Model\FakeClassnameTags123Api */ -class FakeClassnameTags123ApiTest extends \PHPUnit_Framework_TestCase { +class FakeClassnameTags123ApiTest extends \PHPUnit_Framework_TestCase +{ /** * Setup before running any test cases */ - public static function setUpBeforeClass() { - + public static function setUpBeforeClass() + { } /** * Setup before running each test case */ - public function setUp() { - + public function setUp() + { } /** * Clean up after running each test case */ - public function tearDown() { - + public function tearDown() + { } /** * Clean up after running all test cases */ - public static function tearDownAfterClass() { - + public static function tearDownAfterClass() + { } /** @@ -72,7 +73,7 @@ class FakeClassnameTags123ApiTest extends \PHPUnit_Framework_TestCase { * To test class name in snake case. * @covers ::testClassname */ - public function testTestClassname() { - + public function testTestClassname() + { } } diff --git a/samples/server/petstore/php-slim/test/Api/PetApiTest.php b/samples/server/petstore/php-slim/test/Api/PetApiTest.php index 3e5f9eec21..9959ad609d 100644 --- a/samples/server/petstore/php-slim/test/Api/PetApiTest.php +++ b/samples/server/petstore/php-slim/test/Api/PetApiTest.php @@ -36,34 +36,35 @@ use OpenAPIServer\Api\PetApi; * @link https://github.com/openapitools/openapi-generator * @coversDefaultClass \OpenAPIServer\Model\PetApi */ -class PetApiTest extends \PHPUnit_Framework_TestCase { +class PetApiTest extends \PHPUnit_Framework_TestCase +{ /** * Setup before running any test cases */ - public static function setUpBeforeClass() { - + public static function setUpBeforeClass() + { } /** * Setup before running each test case */ - public function setUp() { - + public function setUp() + { } /** * Clean up after running each test case */ - public function tearDown() { - + public function tearDown() + { } /** * Clean up after running all test cases */ - public static function tearDownAfterClass() { - + public static function tearDownAfterClass() + { } /** @@ -72,8 +73,8 @@ class PetApiTest extends \PHPUnit_Framework_TestCase { * Add a new pet to the store. * @covers ::addPet */ - public function testAddPet() { - + public function testAddPet() + { } /** @@ -82,8 +83,8 @@ class PetApiTest extends \PHPUnit_Framework_TestCase { * Deletes a pet. * @covers ::deletePet */ - public function testDeletePet() { - + public function testDeletePet() + { } /** @@ -92,8 +93,8 @@ class PetApiTest extends \PHPUnit_Framework_TestCase { * Finds Pets by status. * @covers ::findPetsByStatus */ - public function testFindPetsByStatus() { - + public function testFindPetsByStatus() + { } /** @@ -102,8 +103,8 @@ class PetApiTest extends \PHPUnit_Framework_TestCase { * Finds Pets by tags. * @covers ::findPetsByTags */ - public function testFindPetsByTags() { - + public function testFindPetsByTags() + { } /** @@ -112,8 +113,8 @@ class PetApiTest extends \PHPUnit_Framework_TestCase { * Find pet by ID. * @covers ::getPetById */ - public function testGetPetById() { - + public function testGetPetById() + { } /** @@ -122,8 +123,8 @@ class PetApiTest extends \PHPUnit_Framework_TestCase { * Update an existing pet. * @covers ::updatePet */ - public function testUpdatePet() { - + public function testUpdatePet() + { } /** @@ -132,8 +133,8 @@ class PetApiTest extends \PHPUnit_Framework_TestCase { * Updates a pet in the store with form data. * @covers ::updatePetWithForm */ - public function testUpdatePetWithForm() { - + public function testUpdatePetWithForm() + { } /** @@ -142,8 +143,8 @@ class PetApiTest extends \PHPUnit_Framework_TestCase { * uploads an image. * @covers ::uploadFile */ - public function testUploadFile() { - + public function testUploadFile() + { } /** @@ -152,7 +153,7 @@ class PetApiTest extends \PHPUnit_Framework_TestCase { * uploads an image (required). * @covers ::uploadFileWithRequiredFile */ - public function testUploadFileWithRequiredFile() { - + public function testUploadFileWithRequiredFile() + { } } diff --git a/samples/server/petstore/php-slim/test/Api/StoreApiTest.php b/samples/server/petstore/php-slim/test/Api/StoreApiTest.php index 220bb260c7..f7c02fa1ba 100644 --- a/samples/server/petstore/php-slim/test/Api/StoreApiTest.php +++ b/samples/server/petstore/php-slim/test/Api/StoreApiTest.php @@ -36,34 +36,35 @@ use OpenAPIServer\Api\StoreApi; * @link https://github.com/openapitools/openapi-generator * @coversDefaultClass \OpenAPIServer\Model\StoreApi */ -class StoreApiTest extends \PHPUnit_Framework_TestCase { +class StoreApiTest extends \PHPUnit_Framework_TestCase +{ /** * Setup before running any test cases */ - public static function setUpBeforeClass() { - + public static function setUpBeforeClass() + { } /** * Setup before running each test case */ - public function setUp() { - + public function setUp() + { } /** * Clean up after running each test case */ - public function tearDown() { - + public function tearDown() + { } /** * Clean up after running all test cases */ - public static function tearDownAfterClass() { - + public static function tearDownAfterClass() + { } /** @@ -72,8 +73,8 @@ class StoreApiTest extends \PHPUnit_Framework_TestCase { * Delete purchase order by ID. * @covers ::deleteOrder */ - public function testDeleteOrder() { - + public function testDeleteOrder() + { } /** @@ -82,8 +83,8 @@ class StoreApiTest extends \PHPUnit_Framework_TestCase { * Returns pet inventories by status. * @covers ::getInventory */ - public function testGetInventory() { - + public function testGetInventory() + { } /** @@ -92,8 +93,8 @@ class StoreApiTest extends \PHPUnit_Framework_TestCase { * Find purchase order by ID. * @covers ::getOrderById */ - public function testGetOrderById() { - + public function testGetOrderById() + { } /** @@ -102,7 +103,7 @@ class StoreApiTest extends \PHPUnit_Framework_TestCase { * Place an order for a pet. * @covers ::placeOrder */ - public function testPlaceOrder() { - + public function testPlaceOrder() + { } } diff --git a/samples/server/petstore/php-slim/test/Api/UserApiTest.php b/samples/server/petstore/php-slim/test/Api/UserApiTest.php index d4eb4382f2..519c10cd08 100644 --- a/samples/server/petstore/php-slim/test/Api/UserApiTest.php +++ b/samples/server/petstore/php-slim/test/Api/UserApiTest.php @@ -36,34 +36,35 @@ use OpenAPIServer\Api\UserApi; * @link https://github.com/openapitools/openapi-generator * @coversDefaultClass \OpenAPIServer\Model\UserApi */ -class UserApiTest extends \PHPUnit_Framework_TestCase { +class UserApiTest extends \PHPUnit_Framework_TestCase +{ /** * Setup before running any test cases */ - public static function setUpBeforeClass() { - + public static function setUpBeforeClass() + { } /** * Setup before running each test case */ - public function setUp() { - + public function setUp() + { } /** * Clean up after running each test case */ - public function tearDown() { - + public function tearDown() + { } /** * Clean up after running all test cases */ - public static function tearDownAfterClass() { - + public static function tearDownAfterClass() + { } /** @@ -72,8 +73,8 @@ class UserApiTest extends \PHPUnit_Framework_TestCase { * Create user. * @covers ::createUser */ - public function testCreateUser() { - + public function testCreateUser() + { } /** @@ -82,8 +83,8 @@ class UserApiTest extends \PHPUnit_Framework_TestCase { * Creates list of users with given input array. * @covers ::createUsersWithArrayInput */ - public function testCreateUsersWithArrayInput() { - + public function testCreateUsersWithArrayInput() + { } /** @@ -92,8 +93,8 @@ class UserApiTest extends \PHPUnit_Framework_TestCase { * Creates list of users with given input array. * @covers ::createUsersWithListInput */ - public function testCreateUsersWithListInput() { - + public function testCreateUsersWithListInput() + { } /** @@ -102,8 +103,8 @@ class UserApiTest extends \PHPUnit_Framework_TestCase { * Delete user. * @covers ::deleteUser */ - public function testDeleteUser() { - + public function testDeleteUser() + { } /** @@ -112,8 +113,8 @@ class UserApiTest extends \PHPUnit_Framework_TestCase { * Get user by user name. * @covers ::getUserByName */ - public function testGetUserByName() { - + public function testGetUserByName() + { } /** @@ -122,8 +123,8 @@ class UserApiTest extends \PHPUnit_Framework_TestCase { * Logs user into the system. * @covers ::loginUser */ - public function testLoginUser() { - + public function testLoginUser() + { } /** @@ -132,8 +133,8 @@ class UserApiTest extends \PHPUnit_Framework_TestCase { * Logs out current logged in user session. * @covers ::logoutUser */ - public function testLogoutUser() { - + public function testLogoutUser() + { } /** @@ -142,7 +143,7 @@ class UserApiTest extends \PHPUnit_Framework_TestCase { * Updated user. * @covers ::updateUser */ - public function testUpdateUser() { - + public function testUpdateUser() + { } } diff --git a/samples/server/petstore/php-slim/test/Model/AdditionalPropertiesClassTest.php b/samples/server/petstore/php-slim/test/Model/AdditionalPropertiesClassTest.php index 0dc870c25f..14d94718ea 100644 --- a/samples/server/petstore/php-slim/test/Model/AdditionalPropertiesClassTest.php +++ b/samples/server/petstore/php-slim/test/Model/AdditionalPropertiesClassTest.php @@ -36,55 +36,56 @@ use OpenAPIServer\Model\AdditionalPropertiesClass; * @link https://github.com/openapitools/openapi-generator * @coversDefaultClass \OpenAPIServer\Model\AdditionalPropertiesClass */ -class AdditionalPropertiesClassTest extends \PHPUnit_Framework_TestCase { +class AdditionalPropertiesClassTest extends \PHPUnit_Framework_TestCase +{ /** * Setup before running any test cases */ - public static function setUpBeforeClass() { - + public static function setUpBeforeClass() + { } /** * Setup before running each test case */ - public function setUp() { - + public function setUp() + { } /** * Clean up after running each test case */ - public function tearDown() { - + public function tearDown() + { } /** * Clean up after running all test cases */ - public static function tearDownAfterClass() { - + public static function tearDownAfterClass() + { } /** * Test "AdditionalPropertiesClass" */ - public function testAdditionalPropertiesClass() { + public function testAdditionalPropertiesClass() + { $testAdditionalPropertiesClass = new AdditionalPropertiesClass(); } /** * Test attribute "mapProperty" */ - public function testPropertyMapProperty() { - + public function testPropertyMapProperty() + { } /** * Test attribute "mapOfMapProperty" */ - public function testPropertyMapOfMapProperty() { - + public function testPropertyMapOfMapProperty() + { } } - diff --git a/samples/server/petstore/php-slim/test/Model/AnimalFarmTest.php b/samples/server/petstore/php-slim/test/Model/AnimalFarmTest.php index b10de6ebe5..93e748a8c6 100644 --- a/samples/server/petstore/php-slim/test/Model/AnimalFarmTest.php +++ b/samples/server/petstore/php-slim/test/Model/AnimalFarmTest.php @@ -36,41 +36,42 @@ use OpenAPIServer\Model\AnimalFarm; * @link https://github.com/openapitools/openapi-generator * @coversDefaultClass \OpenAPIServer\Model\AnimalFarm */ -class AnimalFarmTest extends \PHPUnit_Framework_TestCase { +class AnimalFarmTest extends \PHPUnit_Framework_TestCase +{ /** * Setup before running any test cases */ - public static function setUpBeforeClass() { - + public static function setUpBeforeClass() + { } /** * Setup before running each test case */ - public function setUp() { - + public function setUp() + { } /** * Clean up after running each test case */ - public function tearDown() { - + public function tearDown() + { } /** * Clean up after running all test cases */ - public static function tearDownAfterClass() { - + public static function tearDownAfterClass() + { } /** * Test "AnimalFarm" */ - public function testAnimalFarm() { + public function testAnimalFarm() + { $testAnimalFarm = new AnimalFarm(); } } - diff --git a/samples/server/petstore/php-slim/test/Model/AnimalTest.php b/samples/server/petstore/php-slim/test/Model/AnimalTest.php index e2e9955cb7..bd6e2f4b97 100644 --- a/samples/server/petstore/php-slim/test/Model/AnimalTest.php +++ b/samples/server/petstore/php-slim/test/Model/AnimalTest.php @@ -36,55 +36,56 @@ use OpenAPIServer\Model\Animal; * @link https://github.com/openapitools/openapi-generator * @coversDefaultClass \OpenAPIServer\Model\Animal */ -class AnimalTest extends \PHPUnit_Framework_TestCase { +class AnimalTest extends \PHPUnit_Framework_TestCase +{ /** * Setup before running any test cases */ - public static function setUpBeforeClass() { - + public static function setUpBeforeClass() + { } /** * Setup before running each test case */ - public function setUp() { - + public function setUp() + { } /** * Clean up after running each test case */ - public function tearDown() { - + public function tearDown() + { } /** * Clean up after running all test cases */ - public static function tearDownAfterClass() { - + public static function tearDownAfterClass() + { } /** * Test "Animal" */ - public function testAnimal() { + public function testAnimal() + { $testAnimal = new Animal(); } /** * Test attribute "className" */ - public function testPropertyClassName() { - + public function testPropertyClassName() + { } /** * Test attribute "color" */ - public function testPropertyColor() { - + public function testPropertyColor() + { } } - diff --git a/samples/server/petstore/php-slim/test/Model/ApiResponseTest.php b/samples/server/petstore/php-slim/test/Model/ApiResponseTest.php index de1e64136b..ac3378cc3b 100644 --- a/samples/server/petstore/php-slim/test/Model/ApiResponseTest.php +++ b/samples/server/petstore/php-slim/test/Model/ApiResponseTest.php @@ -36,62 +36,63 @@ use OpenAPIServer\Model\ApiResponse; * @link https://github.com/openapitools/openapi-generator * @coversDefaultClass \OpenAPIServer\Model\ApiResponse */ -class ApiResponseTest extends \PHPUnit_Framework_TestCase { +class ApiResponseTest extends \PHPUnit_Framework_TestCase +{ /** * Setup before running any test cases */ - public static function setUpBeforeClass() { - + public static function setUpBeforeClass() + { } /** * Setup before running each test case */ - public function setUp() { - + public function setUp() + { } /** * Clean up after running each test case */ - public function tearDown() { - + public function tearDown() + { } /** * Clean up after running all test cases */ - public static function tearDownAfterClass() { - + public static function tearDownAfterClass() + { } /** * Test "ApiResponse" */ - public function testApiResponse() { + public function testApiResponse() + { $testApiResponse = new ApiResponse(); } /** * Test attribute "code" */ - public function testPropertyCode() { - + public function testPropertyCode() + { } /** * Test attribute "type" */ - public function testPropertyType() { - + public function testPropertyType() + { } /** * Test attribute "message" */ - public function testPropertyMessage() { - + public function testPropertyMessage() + { } } - diff --git a/samples/server/petstore/php-slim/test/Model/ArrayOfArrayOfNumberOnlyTest.php b/samples/server/petstore/php-slim/test/Model/ArrayOfArrayOfNumberOnlyTest.php index e0e2bded85..bbc5077b1c 100644 --- a/samples/server/petstore/php-slim/test/Model/ArrayOfArrayOfNumberOnlyTest.php +++ b/samples/server/petstore/php-slim/test/Model/ArrayOfArrayOfNumberOnlyTest.php @@ -36,48 +36,49 @@ use OpenAPIServer\Model\ArrayOfArrayOfNumberOnly; * @link https://github.com/openapitools/openapi-generator * @coversDefaultClass \OpenAPIServer\Model\ArrayOfArrayOfNumberOnly */ -class ArrayOfArrayOfNumberOnlyTest extends \PHPUnit_Framework_TestCase { +class ArrayOfArrayOfNumberOnlyTest extends \PHPUnit_Framework_TestCase +{ /** * Setup before running any test cases */ - public static function setUpBeforeClass() { - + public static function setUpBeforeClass() + { } /** * Setup before running each test case */ - public function setUp() { - + public function setUp() + { } /** * Clean up after running each test case */ - public function tearDown() { - + public function tearDown() + { } /** * Clean up after running all test cases */ - public static function tearDownAfterClass() { - + public static function tearDownAfterClass() + { } /** * Test "ArrayOfArrayOfNumberOnly" */ - public function testArrayOfArrayOfNumberOnly() { + public function testArrayOfArrayOfNumberOnly() + { $testArrayOfArrayOfNumberOnly = new ArrayOfArrayOfNumberOnly(); } /** * Test attribute "arrayArrayNumber" */ - public function testPropertyArrayArrayNumber() { - + public function testPropertyArrayArrayNumber() + { } } - diff --git a/samples/server/petstore/php-slim/test/Model/ArrayOfNumberOnlyTest.php b/samples/server/petstore/php-slim/test/Model/ArrayOfNumberOnlyTest.php index 4e6b319009..ce575e4b92 100644 --- a/samples/server/petstore/php-slim/test/Model/ArrayOfNumberOnlyTest.php +++ b/samples/server/petstore/php-slim/test/Model/ArrayOfNumberOnlyTest.php @@ -36,48 +36,49 @@ use OpenAPIServer\Model\ArrayOfNumberOnly; * @link https://github.com/openapitools/openapi-generator * @coversDefaultClass \OpenAPIServer\Model\ArrayOfNumberOnly */ -class ArrayOfNumberOnlyTest extends \PHPUnit_Framework_TestCase { +class ArrayOfNumberOnlyTest extends \PHPUnit_Framework_TestCase +{ /** * Setup before running any test cases */ - public static function setUpBeforeClass() { - + public static function setUpBeforeClass() + { } /** * Setup before running each test case */ - public function setUp() { - + public function setUp() + { } /** * Clean up after running each test case */ - public function tearDown() { - + public function tearDown() + { } /** * Clean up after running all test cases */ - public static function tearDownAfterClass() { - + public static function tearDownAfterClass() + { } /** * Test "ArrayOfNumberOnly" */ - public function testArrayOfNumberOnly() { + public function testArrayOfNumberOnly() + { $testArrayOfNumberOnly = new ArrayOfNumberOnly(); } /** * Test attribute "arrayNumber" */ - public function testPropertyArrayNumber() { - + public function testPropertyArrayNumber() + { } } - diff --git a/samples/server/petstore/php-slim/test/Model/ArrayTestTest.php b/samples/server/petstore/php-slim/test/Model/ArrayTestTest.php index b3def0a71b..236b83b3a8 100644 --- a/samples/server/petstore/php-slim/test/Model/ArrayTestTest.php +++ b/samples/server/petstore/php-slim/test/Model/ArrayTestTest.php @@ -36,62 +36,63 @@ use OpenAPIServer\Model\ArrayTest; * @link https://github.com/openapitools/openapi-generator * @coversDefaultClass \OpenAPIServer\Model\ArrayTest */ -class ArrayTestTest extends \PHPUnit_Framework_TestCase { +class ArrayTestTest extends \PHPUnit_Framework_TestCase +{ /** * Setup before running any test cases */ - public static function setUpBeforeClass() { - + public static function setUpBeforeClass() + { } /** * Setup before running each test case */ - public function setUp() { - + public function setUp() + { } /** * Clean up after running each test case */ - public function tearDown() { - + public function tearDown() + { } /** * Clean up after running all test cases */ - public static function tearDownAfterClass() { - + public static function tearDownAfterClass() + { } /** * Test "ArrayTest" */ - public function testArrayTest() { + public function testArrayTest() + { $testArrayTest = new ArrayTest(); } /** * Test attribute "arrayOfString" */ - public function testPropertyArrayOfString() { - + public function testPropertyArrayOfString() + { } /** * Test attribute "arrayArrayOfInteger" */ - public function testPropertyArrayArrayOfInteger() { - + public function testPropertyArrayArrayOfInteger() + { } /** * Test attribute "arrayArrayOfModel" */ - public function testPropertyArrayArrayOfModel() { - + public function testPropertyArrayArrayOfModel() + { } } - diff --git a/samples/server/petstore/php-slim/test/Model/CapitalizationTest.php b/samples/server/petstore/php-slim/test/Model/CapitalizationTest.php index 5e13387834..bbd0bf6a82 100644 --- a/samples/server/petstore/php-slim/test/Model/CapitalizationTest.php +++ b/samples/server/petstore/php-slim/test/Model/CapitalizationTest.php @@ -36,83 +36,84 @@ use OpenAPIServer\Model\Capitalization; * @link https://github.com/openapitools/openapi-generator * @coversDefaultClass \OpenAPIServer\Model\Capitalization */ -class CapitalizationTest extends \PHPUnit_Framework_TestCase { +class CapitalizationTest extends \PHPUnit_Framework_TestCase +{ /** * Setup before running any test cases */ - public static function setUpBeforeClass() { - + public static function setUpBeforeClass() + { } /** * Setup before running each test case */ - public function setUp() { - + public function setUp() + { } /** * Clean up after running each test case */ - public function tearDown() { - + public function tearDown() + { } /** * Clean up after running all test cases */ - public static function tearDownAfterClass() { - + public static function tearDownAfterClass() + { } /** * Test "Capitalization" */ - public function testCapitalization() { + public function testCapitalization() + { $testCapitalization = new Capitalization(); } /** * Test attribute "smallCamel" */ - public function testPropertySmallCamel() { - + public function testPropertySmallCamel() + { } /** * Test attribute "capitalCamel" */ - public function testPropertyCapitalCamel() { - + public function testPropertyCapitalCamel() + { } /** * Test attribute "smallSnake" */ - public function testPropertySmallSnake() { - + public function testPropertySmallSnake() + { } /** * Test attribute "capitalSnake" */ - public function testPropertyCapitalSnake() { - + public function testPropertyCapitalSnake() + { } /** * Test attribute "sCAETHFlowPoints" */ - public function testPropertySCAETHFlowPoints() { - + public function testPropertySCAETHFlowPoints() + { } /** * Test attribute "aTTNAME" */ - public function testPropertyATTNAME() { - + public function testPropertyATTNAME() + { } } - diff --git a/samples/server/petstore/php-slim/test/Model/CatTest.php b/samples/server/petstore/php-slim/test/Model/CatTest.php index 13a542dd77..b534aecf02 100644 --- a/samples/server/petstore/php-slim/test/Model/CatTest.php +++ b/samples/server/petstore/php-slim/test/Model/CatTest.php @@ -36,62 +36,63 @@ use OpenAPIServer\Model\Cat; * @link https://github.com/openapitools/openapi-generator * @coversDefaultClass \OpenAPIServer\Model\Cat */ -class CatTest extends \PHPUnit_Framework_TestCase { +class CatTest extends \PHPUnit_Framework_TestCase +{ /** * Setup before running any test cases */ - public static function setUpBeforeClass() { - + public static function setUpBeforeClass() + { } /** * Setup before running each test case */ - public function setUp() { - + public function setUp() + { } /** * Clean up after running each test case */ - public function tearDown() { - + public function tearDown() + { } /** * Clean up after running all test cases */ - public static function tearDownAfterClass() { - + public static function tearDownAfterClass() + { } /** * Test "Cat" */ - public function testCat() { + public function testCat() + { $testCat = new Cat(); } /** * Test attribute "className" */ - public function testPropertyClassName() { - + public function testPropertyClassName() + { } /** * Test attribute "color" */ - public function testPropertyColor() { - + public function testPropertyColor() + { } /** * Test attribute "declawed" */ - public function testPropertyDeclawed() { - + public function testPropertyDeclawed() + { } } - diff --git a/samples/server/petstore/php-slim/test/Model/CategoryTest.php b/samples/server/petstore/php-slim/test/Model/CategoryTest.php index ade7b72a95..0fb0264738 100644 --- a/samples/server/petstore/php-slim/test/Model/CategoryTest.php +++ b/samples/server/petstore/php-slim/test/Model/CategoryTest.php @@ -36,55 +36,56 @@ use OpenAPIServer\Model\Category; * @link https://github.com/openapitools/openapi-generator * @coversDefaultClass \OpenAPIServer\Model\Category */ -class CategoryTest extends \PHPUnit_Framework_TestCase { +class CategoryTest extends \PHPUnit_Framework_TestCase +{ /** * Setup before running any test cases */ - public static function setUpBeforeClass() { - + public static function setUpBeforeClass() + { } /** * Setup before running each test case */ - public function setUp() { - + public function setUp() + { } /** * Clean up after running each test case */ - public function tearDown() { - + public function tearDown() + { } /** * Clean up after running all test cases */ - public static function tearDownAfterClass() { - + public static function tearDownAfterClass() + { } /** * Test "Category" */ - public function testCategory() { + public function testCategory() + { $testCategory = new Category(); } /** * Test attribute "id" */ - public function testPropertyId() { - + public function testPropertyId() + { } /** * Test attribute "name" */ - public function testPropertyName() { - + public function testPropertyName() + { } } - diff --git a/samples/server/petstore/php-slim/test/Model/ClassModelTest.php b/samples/server/petstore/php-slim/test/Model/ClassModelTest.php index efcbec71f6..74a06642eb 100644 --- a/samples/server/petstore/php-slim/test/Model/ClassModelTest.php +++ b/samples/server/petstore/php-slim/test/Model/ClassModelTest.php @@ -36,48 +36,49 @@ use OpenAPIServer\Model\ClassModel; * @link https://github.com/openapitools/openapi-generator * @coversDefaultClass \OpenAPIServer\Model\ClassModel */ -class ClassModelTest extends \PHPUnit_Framework_TestCase { +class ClassModelTest extends \PHPUnit_Framework_TestCase +{ /** * Setup before running any test cases */ - public static function setUpBeforeClass() { - + public static function setUpBeforeClass() + { } /** * Setup before running each test case */ - public function setUp() { - + public function setUp() + { } /** * Clean up after running each test case */ - public function tearDown() { - + public function tearDown() + { } /** * Clean up after running all test cases */ - public static function tearDownAfterClass() { - + public static function tearDownAfterClass() + { } /** * Test "ClassModel" */ - public function testClassModel() { + public function testClassModel() + { $testClassModel = new ClassModel(); } /** * Test attribute "class" */ - public function testPropertyClass() { - + public function testPropertyClass() + { } } - diff --git a/samples/server/petstore/php-slim/test/Model/ClientTest.php b/samples/server/petstore/php-slim/test/Model/ClientTest.php index c1eba0c362..56c29cc683 100644 --- a/samples/server/petstore/php-slim/test/Model/ClientTest.php +++ b/samples/server/petstore/php-slim/test/Model/ClientTest.php @@ -36,48 +36,49 @@ use OpenAPIServer\Model\Client; * @link https://github.com/openapitools/openapi-generator * @coversDefaultClass \OpenAPIServer\Model\Client */ -class ClientTest extends \PHPUnit_Framework_TestCase { +class ClientTest extends \PHPUnit_Framework_TestCase +{ /** * Setup before running any test cases */ - public static function setUpBeforeClass() { - + public static function setUpBeforeClass() + { } /** * Setup before running each test case */ - public function setUp() { - + public function setUp() + { } /** * Clean up after running each test case */ - public function tearDown() { - + public function tearDown() + { } /** * Clean up after running all test cases */ - public static function tearDownAfterClass() { - + public static function tearDownAfterClass() + { } /** * Test "Client" */ - public function testClient() { + public function testClient() + { $testClient = new Client(); } /** * Test attribute "client" */ - public function testPropertyClient() { - + public function testPropertyClient() + { } } - diff --git a/samples/server/petstore/php-slim/test/Model/DogTest.php b/samples/server/petstore/php-slim/test/Model/DogTest.php index 0a240c78c3..93654a6864 100644 --- a/samples/server/petstore/php-slim/test/Model/DogTest.php +++ b/samples/server/petstore/php-slim/test/Model/DogTest.php @@ -36,62 +36,63 @@ use OpenAPIServer\Model\Dog; * @link https://github.com/openapitools/openapi-generator * @coversDefaultClass \OpenAPIServer\Model\Dog */ -class DogTest extends \PHPUnit_Framework_TestCase { +class DogTest extends \PHPUnit_Framework_TestCase +{ /** * Setup before running any test cases */ - public static function setUpBeforeClass() { - + public static function setUpBeforeClass() + { } /** * Setup before running each test case */ - public function setUp() { - + public function setUp() + { } /** * Clean up after running each test case */ - public function tearDown() { - + public function tearDown() + { } /** * Clean up after running all test cases */ - public static function tearDownAfterClass() { - + public static function tearDownAfterClass() + { } /** * Test "Dog" */ - public function testDog() { + public function testDog() + { $testDog = new Dog(); } /** * Test attribute "className" */ - public function testPropertyClassName() { - + public function testPropertyClassName() + { } /** * Test attribute "color" */ - public function testPropertyColor() { - + public function testPropertyColor() + { } /** * Test attribute "breed" */ - public function testPropertyBreed() { - + public function testPropertyBreed() + { } } - diff --git a/samples/server/petstore/php-slim/test/Model/EnumArraysTest.php b/samples/server/petstore/php-slim/test/Model/EnumArraysTest.php index 9d11e5cdac..467139153a 100644 --- a/samples/server/petstore/php-slim/test/Model/EnumArraysTest.php +++ b/samples/server/petstore/php-slim/test/Model/EnumArraysTest.php @@ -36,55 +36,56 @@ use OpenAPIServer\Model\EnumArrays; * @link https://github.com/openapitools/openapi-generator * @coversDefaultClass \OpenAPIServer\Model\EnumArrays */ -class EnumArraysTest extends \PHPUnit_Framework_TestCase { +class EnumArraysTest extends \PHPUnit_Framework_TestCase +{ /** * Setup before running any test cases */ - public static function setUpBeforeClass() { - + public static function setUpBeforeClass() + { } /** * Setup before running each test case */ - public function setUp() { - + public function setUp() + { } /** * Clean up after running each test case */ - public function tearDown() { - + public function tearDown() + { } /** * Clean up after running all test cases */ - public static function tearDownAfterClass() { - + public static function tearDownAfterClass() + { } /** * Test "EnumArrays" */ - public function testEnumArrays() { + public function testEnumArrays() + { $testEnumArrays = new EnumArrays(); } /** * Test attribute "justSymbol" */ - public function testPropertyJustSymbol() { - + public function testPropertyJustSymbol() + { } /** * Test attribute "arrayEnum" */ - public function testPropertyArrayEnum() { - + public function testPropertyArrayEnum() + { } } - diff --git a/samples/server/petstore/php-slim/test/Model/EnumClassTest.php b/samples/server/petstore/php-slim/test/Model/EnumClassTest.php index 95ed9693c7..95784e82ae 100644 --- a/samples/server/petstore/php-slim/test/Model/EnumClassTest.php +++ b/samples/server/petstore/php-slim/test/Model/EnumClassTest.php @@ -36,41 +36,42 @@ use OpenAPIServer\Model\EnumClass; * @link https://github.com/openapitools/openapi-generator * @coversDefaultClass \OpenAPIServer\Model\EnumClass */ -class EnumClassTest extends \PHPUnit_Framework_TestCase { +class EnumClassTest extends \PHPUnit_Framework_TestCase +{ /** * Setup before running any test cases */ - public static function setUpBeforeClass() { - + public static function setUpBeforeClass() + { } /** * Setup before running each test case */ - public function setUp() { - + public function setUp() + { } /** * Clean up after running each test case */ - public function tearDown() { - + public function tearDown() + { } /** * Clean up after running all test cases */ - public static function tearDownAfterClass() { - + public static function tearDownAfterClass() + { } /** * Test "EnumClass" */ - public function testEnumClass() { + public function testEnumClass() + { $testEnumClass = new EnumClass(); } } - diff --git a/samples/server/petstore/php-slim/test/Model/EnumTestTest.php b/samples/server/petstore/php-slim/test/Model/EnumTestTest.php index fd95271cb1..dc8ae64328 100644 --- a/samples/server/petstore/php-slim/test/Model/EnumTestTest.php +++ b/samples/server/petstore/php-slim/test/Model/EnumTestTest.php @@ -36,76 +36,77 @@ use OpenAPIServer\Model\EnumTest; * @link https://github.com/openapitools/openapi-generator * @coversDefaultClass \OpenAPIServer\Model\EnumTest */ -class EnumTestTest extends \PHPUnit_Framework_TestCase { +class EnumTestTest extends \PHPUnit_Framework_TestCase +{ /** * Setup before running any test cases */ - public static function setUpBeforeClass() { - + public static function setUpBeforeClass() + { } /** * Setup before running each test case */ - public function setUp() { - + public function setUp() + { } /** * Clean up after running each test case */ - public function tearDown() { - + public function tearDown() + { } /** * Clean up after running all test cases */ - public static function tearDownAfterClass() { - + public static function tearDownAfterClass() + { } /** * Test "EnumTest" */ - public function testEnumTest() { + public function testEnumTest() + { $testEnumTest = new EnumTest(); } /** * Test attribute "enumString" */ - public function testPropertyEnumString() { - + public function testPropertyEnumString() + { } /** * Test attribute "enumStringRequired" */ - public function testPropertyEnumStringRequired() { - + public function testPropertyEnumStringRequired() + { } /** * Test attribute "enumInteger" */ - public function testPropertyEnumInteger() { - + public function testPropertyEnumInteger() + { } /** * Test attribute "enumNumber" */ - public function testPropertyEnumNumber() { - + public function testPropertyEnumNumber() + { } /** * Test attribute "outerEnum" */ - public function testPropertyOuterEnum() { - + public function testPropertyOuterEnum() + { } } - diff --git a/samples/server/petstore/php-slim/test/Model/FileSchemaTestClassTest.php b/samples/server/petstore/php-slim/test/Model/FileSchemaTestClassTest.php index 7416c0bd6c..38bc7db086 100644 --- a/samples/server/petstore/php-slim/test/Model/FileSchemaTestClassTest.php +++ b/samples/server/petstore/php-slim/test/Model/FileSchemaTestClassTest.php @@ -36,55 +36,56 @@ use OpenAPIServer\Model\FileSchemaTestClass; * @link https://github.com/openapitools/openapi-generator * @coversDefaultClass \OpenAPIServer\Model\FileSchemaTestClass */ -class FileSchemaTestClassTest extends \PHPUnit_Framework_TestCase { +class FileSchemaTestClassTest extends \PHPUnit_Framework_TestCase +{ /** * Setup before running any test cases */ - public static function setUpBeforeClass() { - + public static function setUpBeforeClass() + { } /** * Setup before running each test case */ - public function setUp() { - + public function setUp() + { } /** * Clean up after running each test case */ - public function tearDown() { - + public function tearDown() + { } /** * Clean up after running all test cases */ - public static function tearDownAfterClass() { - + public static function tearDownAfterClass() + { } /** * Test "FileSchemaTestClass" */ - public function testFileSchemaTestClass() { + public function testFileSchemaTestClass() + { $testFileSchemaTestClass = new FileSchemaTestClass(); } /** * Test attribute "file" */ - public function testPropertyFile() { - + public function testPropertyFile() + { } /** * Test attribute "files" */ - public function testPropertyFiles() { - + public function testPropertyFiles() + { } } - diff --git a/samples/server/petstore/php-slim/test/Model/FileTest.php b/samples/server/petstore/php-slim/test/Model/FileTest.php index 01d6820a80..57129a8c54 100644 --- a/samples/server/petstore/php-slim/test/Model/FileTest.php +++ b/samples/server/petstore/php-slim/test/Model/FileTest.php @@ -36,48 +36,49 @@ use OpenAPIServer\Model\File; * @link https://github.com/openapitools/openapi-generator * @coversDefaultClass \OpenAPIServer\Model\File */ -class FileTest extends \PHPUnit_Framework_TestCase { +class FileTest extends \PHPUnit_Framework_TestCase +{ /** * Setup before running any test cases */ - public static function setUpBeforeClass() { - + public static function setUpBeforeClass() + { } /** * Setup before running each test case */ - public function setUp() { - + public function setUp() + { } /** * Clean up after running each test case */ - public function tearDown() { - + public function tearDown() + { } /** * Clean up after running all test cases */ - public static function tearDownAfterClass() { - + public static function tearDownAfterClass() + { } /** * Test "File" */ - public function testFile() { + public function testFile() + { $testFile = new File(); } /** * Test attribute "sourceURI" */ - public function testPropertySourceURI() { - + public function testPropertySourceURI() + { } } - diff --git a/samples/server/petstore/php-slim/test/Model/FormatTestTest.php b/samples/server/petstore/php-slim/test/Model/FormatTestTest.php index ee6f993c3d..90cb8475b1 100644 --- a/samples/server/petstore/php-slim/test/Model/FormatTestTest.php +++ b/samples/server/petstore/php-slim/test/Model/FormatTestTest.php @@ -36,132 +36,133 @@ use OpenAPIServer\Model\FormatTest; * @link https://github.com/openapitools/openapi-generator * @coversDefaultClass \OpenAPIServer\Model\FormatTest */ -class FormatTestTest extends \PHPUnit_Framework_TestCase { +class FormatTestTest extends \PHPUnit_Framework_TestCase +{ /** * Setup before running any test cases */ - public static function setUpBeforeClass() { - + public static function setUpBeforeClass() + { } /** * Setup before running each test case */ - public function setUp() { - + public function setUp() + { } /** * Clean up after running each test case */ - public function tearDown() { - + public function tearDown() + { } /** * Clean up after running all test cases */ - public static function tearDownAfterClass() { - + public static function tearDownAfterClass() + { } /** * Test "FormatTest" */ - public function testFormatTest() { + public function testFormatTest() + { $testFormatTest = new FormatTest(); } /** * Test attribute "integer" */ - public function testPropertyInteger() { - + public function testPropertyInteger() + { } /** * Test attribute "int32" */ - public function testPropertyInt32() { - + public function testPropertyInt32() + { } /** * Test attribute "int64" */ - public function testPropertyInt64() { - + public function testPropertyInt64() + { } /** * Test attribute "number" */ - public function testPropertyNumber() { - + public function testPropertyNumber() + { } /** * Test attribute "float" */ - public function testPropertyFloat() { - + public function testPropertyFloat() + { } /** * Test attribute "double" */ - public function testPropertyDouble() { - + public function testPropertyDouble() + { } /** * Test attribute "string" */ - public function testPropertyString() { - + public function testPropertyString() + { } /** * Test attribute "byte" */ - public function testPropertyByte() { - + public function testPropertyByte() + { } /** * Test attribute "binary" */ - public function testPropertyBinary() { - + public function testPropertyBinary() + { } /** * Test attribute "date" */ - public function testPropertyDate() { - + public function testPropertyDate() + { } /** * Test attribute "dateTime" */ - public function testPropertyDateTime() { - + public function testPropertyDateTime() + { } /** * Test attribute "uuid" */ - public function testPropertyUuid() { - + public function testPropertyUuid() + { } /** * Test attribute "password" */ - public function testPropertyPassword() { - + public function testPropertyPassword() + { } } - diff --git a/samples/server/petstore/php-slim/test/Model/HasOnlyReadOnlyTest.php b/samples/server/petstore/php-slim/test/Model/HasOnlyReadOnlyTest.php index 67b1631156..d886b0c964 100644 --- a/samples/server/petstore/php-slim/test/Model/HasOnlyReadOnlyTest.php +++ b/samples/server/petstore/php-slim/test/Model/HasOnlyReadOnlyTest.php @@ -36,55 +36,56 @@ use OpenAPIServer\Model\HasOnlyReadOnly; * @link https://github.com/openapitools/openapi-generator * @coversDefaultClass \OpenAPIServer\Model\HasOnlyReadOnly */ -class HasOnlyReadOnlyTest extends \PHPUnit_Framework_TestCase { +class HasOnlyReadOnlyTest extends \PHPUnit_Framework_TestCase +{ /** * Setup before running any test cases */ - public static function setUpBeforeClass() { - + public static function setUpBeforeClass() + { } /** * Setup before running each test case */ - public function setUp() { - + public function setUp() + { } /** * Clean up after running each test case */ - public function tearDown() { - + public function tearDown() + { } /** * Clean up after running all test cases */ - public static function tearDownAfterClass() { - + public static function tearDownAfterClass() + { } /** * Test "HasOnlyReadOnly" */ - public function testHasOnlyReadOnly() { + public function testHasOnlyReadOnly() + { $testHasOnlyReadOnly = new HasOnlyReadOnly(); } /** * Test attribute "bar" */ - public function testPropertyBar() { - + public function testPropertyBar() + { } /** * Test attribute "foo" */ - public function testPropertyFoo() { - + public function testPropertyFoo() + { } } - diff --git a/samples/server/petstore/php-slim/test/Model/MapTestTest.php b/samples/server/petstore/php-slim/test/Model/MapTestTest.php index 47bbd8a330..d3c0b8e136 100644 --- a/samples/server/petstore/php-slim/test/Model/MapTestTest.php +++ b/samples/server/petstore/php-slim/test/Model/MapTestTest.php @@ -36,69 +36,70 @@ use OpenAPIServer\Model\MapTest; * @link https://github.com/openapitools/openapi-generator * @coversDefaultClass \OpenAPIServer\Model\MapTest */ -class MapTestTest extends \PHPUnit_Framework_TestCase { +class MapTestTest extends \PHPUnit_Framework_TestCase +{ /** * Setup before running any test cases */ - public static function setUpBeforeClass() { - + public static function setUpBeforeClass() + { } /** * Setup before running each test case */ - public function setUp() { - + public function setUp() + { } /** * Clean up after running each test case */ - public function tearDown() { - + public function tearDown() + { } /** * Clean up after running all test cases */ - public static function tearDownAfterClass() { - + public static function tearDownAfterClass() + { } /** * Test "MapTest" */ - public function testMapTest() { + public function testMapTest() + { $testMapTest = new MapTest(); } /** * Test attribute "mapMapOfString" */ - public function testPropertyMapMapOfString() { - + public function testPropertyMapMapOfString() + { } /** * Test attribute "mapOfEnumString" */ - public function testPropertyMapOfEnumString() { - + public function testPropertyMapOfEnumString() + { } /** * Test attribute "directMap" */ - public function testPropertyDirectMap() { - + public function testPropertyDirectMap() + { } /** * Test attribute "indirectMap" */ - public function testPropertyIndirectMap() { - + public function testPropertyIndirectMap() + { } } - diff --git a/samples/server/petstore/php-slim/test/Model/MixedPropertiesAndAdditionalPropertiesClassTest.php b/samples/server/petstore/php-slim/test/Model/MixedPropertiesAndAdditionalPropertiesClassTest.php index 7356a017be..5ee64f596d 100644 --- a/samples/server/petstore/php-slim/test/Model/MixedPropertiesAndAdditionalPropertiesClassTest.php +++ b/samples/server/petstore/php-slim/test/Model/MixedPropertiesAndAdditionalPropertiesClassTest.php @@ -36,62 +36,63 @@ use OpenAPIServer\Model\MixedPropertiesAndAdditionalPropertiesClass; * @link https://github.com/openapitools/openapi-generator * @coversDefaultClass \OpenAPIServer\Model\MixedPropertiesAndAdditionalPropertiesClass */ -class MixedPropertiesAndAdditionalPropertiesClassTest extends \PHPUnit_Framework_TestCase { +class MixedPropertiesAndAdditionalPropertiesClassTest extends \PHPUnit_Framework_TestCase +{ /** * Setup before running any test cases */ - public static function setUpBeforeClass() { - + public static function setUpBeforeClass() + { } /** * Setup before running each test case */ - public function setUp() { - + public function setUp() + { } /** * Clean up after running each test case */ - public function tearDown() { - + public function tearDown() + { } /** * Clean up after running all test cases */ - public static function tearDownAfterClass() { - + public static function tearDownAfterClass() + { } /** * Test "MixedPropertiesAndAdditionalPropertiesClass" */ - public function testMixedPropertiesAndAdditionalPropertiesClass() { + public function testMixedPropertiesAndAdditionalPropertiesClass() + { $testMixedPropertiesAndAdditionalPropertiesClass = new MixedPropertiesAndAdditionalPropertiesClass(); } /** * Test attribute "uuid" */ - public function testPropertyUuid() { - + public function testPropertyUuid() + { } /** * Test attribute "dateTime" */ - public function testPropertyDateTime() { - + public function testPropertyDateTime() + { } /** * Test attribute "map" */ - public function testPropertyMap() { - + public function testPropertyMap() + { } } - diff --git a/samples/server/petstore/php-slim/test/Model/Model200ResponseTest.php b/samples/server/petstore/php-slim/test/Model/Model200ResponseTest.php index 01301c810b..36706cf0c2 100644 --- a/samples/server/petstore/php-slim/test/Model/Model200ResponseTest.php +++ b/samples/server/petstore/php-slim/test/Model/Model200ResponseTest.php @@ -36,55 +36,56 @@ use OpenAPIServer\Model\Model200Response; * @link https://github.com/openapitools/openapi-generator * @coversDefaultClass \OpenAPIServer\Model\Model200Response */ -class Model200ResponseTest extends \PHPUnit_Framework_TestCase { +class Model200ResponseTest extends \PHPUnit_Framework_TestCase +{ /** * Setup before running any test cases */ - public static function setUpBeforeClass() { - + public static function setUpBeforeClass() + { } /** * Setup before running each test case */ - public function setUp() { - + public function setUp() + { } /** * Clean up after running each test case */ - public function tearDown() { - + public function tearDown() + { } /** * Clean up after running all test cases */ - public static function tearDownAfterClass() { - + public static function tearDownAfterClass() + { } /** * Test "Model200Response" */ - public function testModel200Response() { + public function testModel200Response() + { $testModel200Response = new Model200Response(); } /** * Test attribute "name" */ - public function testPropertyName() { - + public function testPropertyName() + { } /** * Test attribute "class" */ - public function testPropertyClass() { - + public function testPropertyClass() + { } } - diff --git a/samples/server/petstore/php-slim/test/Model/ModelListTest.php b/samples/server/petstore/php-slim/test/Model/ModelListTest.php index 4f8b171329..c73f1a80e9 100644 --- a/samples/server/petstore/php-slim/test/Model/ModelListTest.php +++ b/samples/server/petstore/php-slim/test/Model/ModelListTest.php @@ -36,48 +36,49 @@ use OpenAPIServer\Model\ModelList; * @link https://github.com/openapitools/openapi-generator * @coversDefaultClass \OpenAPIServer\Model\ModelList */ -class ModelListTest extends \PHPUnit_Framework_TestCase { +class ModelListTest extends \PHPUnit_Framework_TestCase +{ /** * Setup before running any test cases */ - public static function setUpBeforeClass() { - + public static function setUpBeforeClass() + { } /** * Setup before running each test case */ - public function setUp() { - + public function setUp() + { } /** * Clean up after running each test case */ - public function tearDown() { - + public function tearDown() + { } /** * Clean up after running all test cases */ - public static function tearDownAfterClass() { - + public static function tearDownAfterClass() + { } /** * Test "ModelList" */ - public function testModelList() { + public function testModelList() + { $testModelList = new ModelList(); } /** * Test attribute "_123list" */ - public function testProperty123list() { - + public function testProperty123list() + { } } - diff --git a/samples/server/petstore/php-slim/test/Model/ModelReturnTest.php b/samples/server/petstore/php-slim/test/Model/ModelReturnTest.php index d087f796c7..1ba2a4eba6 100644 --- a/samples/server/petstore/php-slim/test/Model/ModelReturnTest.php +++ b/samples/server/petstore/php-slim/test/Model/ModelReturnTest.php @@ -36,48 +36,49 @@ use OpenAPIServer\Model\ModelReturn; * @link https://github.com/openapitools/openapi-generator * @coversDefaultClass \OpenAPIServer\Model\ModelReturn */ -class ModelReturnTest extends \PHPUnit_Framework_TestCase { +class ModelReturnTest extends \PHPUnit_Framework_TestCase +{ /** * Setup before running any test cases */ - public static function setUpBeforeClass() { - + public static function setUpBeforeClass() + { } /** * Setup before running each test case */ - public function setUp() { - + public function setUp() + { } /** * Clean up after running each test case */ - public function tearDown() { - + public function tearDown() + { } /** * Clean up after running all test cases */ - public static function tearDownAfterClass() { - + public static function tearDownAfterClass() + { } /** * Test "ModelReturn" */ - public function testModelReturn() { + public function testModelReturn() + { $testModelReturn = new ModelReturn(); } /** * Test attribute "return" */ - public function testPropertyReturn() { - + public function testPropertyReturn() + { } } - diff --git a/samples/server/petstore/php-slim/test/Model/NameTest.php b/samples/server/petstore/php-slim/test/Model/NameTest.php index 8e8104c7a2..70558568c0 100644 --- a/samples/server/petstore/php-slim/test/Model/NameTest.php +++ b/samples/server/petstore/php-slim/test/Model/NameTest.php @@ -36,69 +36,70 @@ use OpenAPIServer\Model\Name; * @link https://github.com/openapitools/openapi-generator * @coversDefaultClass \OpenAPIServer\Model\Name */ -class NameTest extends \PHPUnit_Framework_TestCase { +class NameTest extends \PHPUnit_Framework_TestCase +{ /** * Setup before running any test cases */ - public static function setUpBeforeClass() { - + public static function setUpBeforeClass() + { } /** * Setup before running each test case */ - public function setUp() { - + public function setUp() + { } /** * Clean up after running each test case */ - public function tearDown() { - + public function tearDown() + { } /** * Clean up after running all test cases */ - public static function tearDownAfterClass() { - + public static function tearDownAfterClass() + { } /** * Test "Name" */ - public function testName() { + public function testName() + { $testName = new Name(); } /** * Test attribute "name" */ - public function testPropertyName() { - + public function testPropertyName() + { } /** * Test attribute "snakeCase" */ - public function testPropertySnakeCase() { - + public function testPropertySnakeCase() + { } /** * Test attribute "property" */ - public function testPropertyProperty() { - + public function testPropertyProperty() + { } /** * Test attribute "_123number" */ - public function testProperty123number() { - + public function testProperty123number() + { } } - diff --git a/samples/server/petstore/php-slim/test/Model/NumberOnlyTest.php b/samples/server/petstore/php-slim/test/Model/NumberOnlyTest.php index 68320527de..38f1055102 100644 --- a/samples/server/petstore/php-slim/test/Model/NumberOnlyTest.php +++ b/samples/server/petstore/php-slim/test/Model/NumberOnlyTest.php @@ -36,48 +36,49 @@ use OpenAPIServer\Model\NumberOnly; * @link https://github.com/openapitools/openapi-generator * @coversDefaultClass \OpenAPIServer\Model\NumberOnly */ -class NumberOnlyTest extends \PHPUnit_Framework_TestCase { +class NumberOnlyTest extends \PHPUnit_Framework_TestCase +{ /** * Setup before running any test cases */ - public static function setUpBeforeClass() { - + public static function setUpBeforeClass() + { } /** * Setup before running each test case */ - public function setUp() { - + public function setUp() + { } /** * Clean up after running each test case */ - public function tearDown() { - + public function tearDown() + { } /** * Clean up after running all test cases */ - public static function tearDownAfterClass() { - + public static function tearDownAfterClass() + { } /** * Test "NumberOnly" */ - public function testNumberOnly() { + public function testNumberOnly() + { $testNumberOnly = new NumberOnly(); } /** * Test attribute "justNumber" */ - public function testPropertyJustNumber() { - + public function testPropertyJustNumber() + { } } - diff --git a/samples/server/petstore/php-slim/test/Model/OrderTest.php b/samples/server/petstore/php-slim/test/Model/OrderTest.php index 615dd0797b..7542b27a8c 100644 --- a/samples/server/petstore/php-slim/test/Model/OrderTest.php +++ b/samples/server/petstore/php-slim/test/Model/OrderTest.php @@ -36,83 +36,84 @@ use OpenAPIServer\Model\Order; * @link https://github.com/openapitools/openapi-generator * @coversDefaultClass \OpenAPIServer\Model\Order */ -class OrderTest extends \PHPUnit_Framework_TestCase { +class OrderTest extends \PHPUnit_Framework_TestCase +{ /** * Setup before running any test cases */ - public static function setUpBeforeClass() { - + public static function setUpBeforeClass() + { } /** * Setup before running each test case */ - public function setUp() { - + public function setUp() + { } /** * Clean up after running each test case */ - public function tearDown() { - + public function tearDown() + { } /** * Clean up after running all test cases */ - public static function tearDownAfterClass() { - + public static function tearDownAfterClass() + { } /** * Test "Order" */ - public function testOrder() { + public function testOrder() + { $testOrder = new Order(); } /** * Test attribute "id" */ - public function testPropertyId() { - + public function testPropertyId() + { } /** * Test attribute "petId" */ - public function testPropertyPetId() { - + public function testPropertyPetId() + { } /** * Test attribute "quantity" */ - public function testPropertyQuantity() { - + public function testPropertyQuantity() + { } /** * Test attribute "shipDate" */ - public function testPropertyShipDate() { - + public function testPropertyShipDate() + { } /** * Test attribute "status" */ - public function testPropertyStatus() { - + public function testPropertyStatus() + { } /** * Test attribute "complete" */ - public function testPropertyComplete() { - + public function testPropertyComplete() + { } } - diff --git a/samples/server/petstore/php-slim/test/Model/OuterCompositeTest.php b/samples/server/petstore/php-slim/test/Model/OuterCompositeTest.php index ba5c4e87ee..4afa5838af 100644 --- a/samples/server/petstore/php-slim/test/Model/OuterCompositeTest.php +++ b/samples/server/petstore/php-slim/test/Model/OuterCompositeTest.php @@ -36,62 +36,63 @@ use OpenAPIServer\Model\OuterComposite; * @link https://github.com/openapitools/openapi-generator * @coversDefaultClass \OpenAPIServer\Model\OuterComposite */ -class OuterCompositeTest extends \PHPUnit_Framework_TestCase { +class OuterCompositeTest extends \PHPUnit_Framework_TestCase +{ /** * Setup before running any test cases */ - public static function setUpBeforeClass() { - + public static function setUpBeforeClass() + { } /** * Setup before running each test case */ - public function setUp() { - + public function setUp() + { } /** * Clean up after running each test case */ - public function tearDown() { - + public function tearDown() + { } /** * Clean up after running all test cases */ - public static function tearDownAfterClass() { - + public static function tearDownAfterClass() + { } /** * Test "OuterComposite" */ - public function testOuterComposite() { + public function testOuterComposite() + { $testOuterComposite = new OuterComposite(); } /** * Test attribute "myNumber" */ - public function testPropertyMyNumber() { - + public function testPropertyMyNumber() + { } /** * Test attribute "myString" */ - public function testPropertyMyString() { - + public function testPropertyMyString() + { } /** * Test attribute "myBoolean" */ - public function testPropertyMyBoolean() { - + public function testPropertyMyBoolean() + { } } - diff --git a/samples/server/petstore/php-slim/test/Model/OuterEnumTest.php b/samples/server/petstore/php-slim/test/Model/OuterEnumTest.php index 8f4f9ed9f2..45e7df7fbe 100644 --- a/samples/server/petstore/php-slim/test/Model/OuterEnumTest.php +++ b/samples/server/petstore/php-slim/test/Model/OuterEnumTest.php @@ -36,41 +36,42 @@ use OpenAPIServer\Model\OuterEnum; * @link https://github.com/openapitools/openapi-generator * @coversDefaultClass \OpenAPIServer\Model\OuterEnum */ -class OuterEnumTest extends \PHPUnit_Framework_TestCase { +class OuterEnumTest extends \PHPUnit_Framework_TestCase +{ /** * Setup before running any test cases */ - public static function setUpBeforeClass() { - + public static function setUpBeforeClass() + { } /** * Setup before running each test case */ - public function setUp() { - + public function setUp() + { } /** * Clean up after running each test case */ - public function tearDown() { - + public function tearDown() + { } /** * Clean up after running all test cases */ - public static function tearDownAfterClass() { - + public static function tearDownAfterClass() + { } /** * Test "OuterEnum" */ - public function testOuterEnum() { + public function testOuterEnum() + { $testOuterEnum = new OuterEnum(); } } - diff --git a/samples/server/petstore/php-slim/test/Model/PetTest.php b/samples/server/petstore/php-slim/test/Model/PetTest.php index 6f962d1aae..0bf28bb704 100644 --- a/samples/server/petstore/php-slim/test/Model/PetTest.php +++ b/samples/server/petstore/php-slim/test/Model/PetTest.php @@ -36,83 +36,84 @@ use OpenAPIServer\Model\Pet; * @link https://github.com/openapitools/openapi-generator * @coversDefaultClass \OpenAPIServer\Model\Pet */ -class PetTest extends \PHPUnit_Framework_TestCase { +class PetTest extends \PHPUnit_Framework_TestCase +{ /** * Setup before running any test cases */ - public static function setUpBeforeClass() { - + public static function setUpBeforeClass() + { } /** * Setup before running each test case */ - public function setUp() { - + public function setUp() + { } /** * Clean up after running each test case */ - public function tearDown() { - + public function tearDown() + { } /** * Clean up after running all test cases */ - public static function tearDownAfterClass() { - + public static function tearDownAfterClass() + { } /** * Test "Pet" */ - public function testPet() { + public function testPet() + { $testPet = new Pet(); } /** * Test attribute "id" */ - public function testPropertyId() { - + public function testPropertyId() + { } /** * Test attribute "category" */ - public function testPropertyCategory() { - + public function testPropertyCategory() + { } /** * Test attribute "name" */ - public function testPropertyName() { - + public function testPropertyName() + { } /** * Test attribute "photoUrls" */ - public function testPropertyPhotoUrls() { - + public function testPropertyPhotoUrls() + { } /** * Test attribute "tags" */ - public function testPropertyTags() { - + public function testPropertyTags() + { } /** * Test attribute "status" */ - public function testPropertyStatus() { - + public function testPropertyStatus() + { } } - diff --git a/samples/server/petstore/php-slim/test/Model/ReadOnlyFirstTest.php b/samples/server/petstore/php-slim/test/Model/ReadOnlyFirstTest.php index b26d3317d7..d47f78d8bb 100644 --- a/samples/server/petstore/php-slim/test/Model/ReadOnlyFirstTest.php +++ b/samples/server/petstore/php-slim/test/Model/ReadOnlyFirstTest.php @@ -36,55 +36,56 @@ use OpenAPIServer\Model\ReadOnlyFirst; * @link https://github.com/openapitools/openapi-generator * @coversDefaultClass \OpenAPIServer\Model\ReadOnlyFirst */ -class ReadOnlyFirstTest extends \PHPUnit_Framework_TestCase { +class ReadOnlyFirstTest extends \PHPUnit_Framework_TestCase +{ /** * Setup before running any test cases */ - public static function setUpBeforeClass() { - + public static function setUpBeforeClass() + { } /** * Setup before running each test case */ - public function setUp() { - + public function setUp() + { } /** * Clean up after running each test case */ - public function tearDown() { - + public function tearDown() + { } /** * Clean up after running all test cases */ - public static function tearDownAfterClass() { - + public static function tearDownAfterClass() + { } /** * Test "ReadOnlyFirst" */ - public function testReadOnlyFirst() { + public function testReadOnlyFirst() + { $testReadOnlyFirst = new ReadOnlyFirst(); } /** * Test attribute "bar" */ - public function testPropertyBar() { - + public function testPropertyBar() + { } /** * Test attribute "baz" */ - public function testPropertyBaz() { - + public function testPropertyBaz() + { } } - diff --git a/samples/server/petstore/php-slim/test/Model/SpecialModelNameTest.php b/samples/server/petstore/php-slim/test/Model/SpecialModelNameTest.php index 391d12f8b7..197e25622d 100644 --- a/samples/server/petstore/php-slim/test/Model/SpecialModelNameTest.php +++ b/samples/server/petstore/php-slim/test/Model/SpecialModelNameTest.php @@ -36,48 +36,49 @@ use OpenAPIServer\Model\SpecialModelName; * @link https://github.com/openapitools/openapi-generator * @coversDefaultClass \OpenAPIServer\Model\SpecialModelName */ -class SpecialModelNameTest extends \PHPUnit_Framework_TestCase { +class SpecialModelNameTest extends \PHPUnit_Framework_TestCase +{ /** * Setup before running any test cases */ - public static function setUpBeforeClass() { - + public static function setUpBeforeClass() + { } /** * Setup before running each test case */ - public function setUp() { - + public function setUp() + { } /** * Clean up after running each test case */ - public function tearDown() { - + public function tearDown() + { } /** * Clean up after running all test cases */ - public static function tearDownAfterClass() { - + public static function tearDownAfterClass() + { } /** * Test "SpecialModelName" */ - public function testSpecialModelName() { + public function testSpecialModelName() + { $testSpecialModelName = new SpecialModelName(); } /** * Test attribute "specialPropertyName" */ - public function testPropertySpecialPropertyName() { - + public function testPropertySpecialPropertyName() + { } } - diff --git a/samples/server/petstore/php-slim/test/Model/StringBooleanMapTest.php b/samples/server/petstore/php-slim/test/Model/StringBooleanMapTest.php index 600f610a3e..41fe1a9f8d 100644 --- a/samples/server/petstore/php-slim/test/Model/StringBooleanMapTest.php +++ b/samples/server/petstore/php-slim/test/Model/StringBooleanMapTest.php @@ -36,41 +36,42 @@ use OpenAPIServer\Model\StringBooleanMap; * @link https://github.com/openapitools/openapi-generator * @coversDefaultClass \OpenAPIServer\Model\StringBooleanMap */ -class StringBooleanMapTest extends \PHPUnit_Framework_TestCase { +class StringBooleanMapTest extends \PHPUnit_Framework_TestCase +{ /** * Setup before running any test cases */ - public static function setUpBeforeClass() { - + public static function setUpBeforeClass() + { } /** * Setup before running each test case */ - public function setUp() { - + public function setUp() + { } /** * Clean up after running each test case */ - public function tearDown() { - + public function tearDown() + { } /** * Clean up after running all test cases */ - public static function tearDownAfterClass() { - + public static function tearDownAfterClass() + { } /** * Test "StringBooleanMap" */ - public function testStringBooleanMap() { + public function testStringBooleanMap() + { $testStringBooleanMap = new StringBooleanMap(); } } - diff --git a/samples/server/petstore/php-slim/test/Model/TagTest.php b/samples/server/petstore/php-slim/test/Model/TagTest.php index 3289c8a779..69f2abeb0b 100644 --- a/samples/server/petstore/php-slim/test/Model/TagTest.php +++ b/samples/server/petstore/php-slim/test/Model/TagTest.php @@ -36,55 +36,56 @@ use OpenAPIServer\Model\Tag; * @link https://github.com/openapitools/openapi-generator * @coversDefaultClass \OpenAPIServer\Model\Tag */ -class TagTest extends \PHPUnit_Framework_TestCase { +class TagTest extends \PHPUnit_Framework_TestCase +{ /** * Setup before running any test cases */ - public static function setUpBeforeClass() { - + public static function setUpBeforeClass() + { } /** * Setup before running each test case */ - public function setUp() { - + public function setUp() + { } /** * Clean up after running each test case */ - public function tearDown() { - + public function tearDown() + { } /** * Clean up after running all test cases */ - public static function tearDownAfterClass() { - + public static function tearDownAfterClass() + { } /** * Test "Tag" */ - public function testTag() { + public function testTag() + { $testTag = new Tag(); } /** * Test attribute "id" */ - public function testPropertyId() { - + public function testPropertyId() + { } /** * Test attribute "name" */ - public function testPropertyName() { - + public function testPropertyName() + { } } - diff --git a/samples/server/petstore/php-slim/test/Model/UserTest.php b/samples/server/petstore/php-slim/test/Model/UserTest.php index 9bd3a0e2c1..7f40f26f10 100644 --- a/samples/server/petstore/php-slim/test/Model/UserTest.php +++ b/samples/server/petstore/php-slim/test/Model/UserTest.php @@ -36,97 +36,98 @@ use OpenAPIServer\Model\User; * @link https://github.com/openapitools/openapi-generator * @coversDefaultClass \OpenAPIServer\Model\User */ -class UserTest extends \PHPUnit_Framework_TestCase { +class UserTest extends \PHPUnit_Framework_TestCase +{ /** * Setup before running any test cases */ - public static function setUpBeforeClass() { - + public static function setUpBeforeClass() + { } /** * Setup before running each test case */ - public function setUp() { - + public function setUp() + { } /** * Clean up after running each test case */ - public function tearDown() { - + public function tearDown() + { } /** * Clean up after running all test cases */ - public static function tearDownAfterClass() { - + public static function tearDownAfterClass() + { } /** * Test "User" */ - public function testUser() { + public function testUser() + { $testUser = new User(); } /** * Test attribute "id" */ - public function testPropertyId() { - + public function testPropertyId() + { } /** * Test attribute "username" */ - public function testPropertyUsername() { - + public function testPropertyUsername() + { } /** * Test attribute "firstName" */ - public function testPropertyFirstName() { - + public function testPropertyFirstName() + { } /** * Test attribute "lastName" */ - public function testPropertyLastName() { - + public function testPropertyLastName() + { } /** * Test attribute "email" */ - public function testPropertyEmail() { - + public function testPropertyEmail() + { } /** * Test attribute "password" */ - public function testPropertyPassword() { - + public function testPropertyPassword() + { } /** * Test attribute "phone" */ - public function testPropertyPhone() { - + public function testPropertyPhone() + { } /** * Test attribute "userStatus" */ - public function testPropertyUserStatus() { - + public function testPropertyUserStatus() + { } } - diff --git a/shippable.yml b/shippable.yml index 27c3ccec46..21476c33af 100644 --- a/shippable.yml +++ b/shippable.yml @@ -12,7 +12,7 @@ build: ci: - mvn --quiet clean install # ensure all modifications created by 'mature' generators are in the git repo - - ./bin/utils/ensure-up-to-date + #- ./bin/utils/ensure-up-to-date # prepare environment for tests - sudo apt-get update -qq # install stack @@ -39,3 +39,5 @@ build: - ./bin/run-all-petstore # generate all petstore samples (openapi3) - ./bin/openapi3/run-all-petstore + # generate test scripts + - ./bin/tests/run-all-test